diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 4c8853bf00..b161f30aa9 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -16927,7 +16927,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/v2/AbsolutePathBuf" + "$ref": "#/definitions/v2/ApiPathString" }, "type": "array" }, @@ -18631,7 +18631,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/v2/AbsolutePathBuf" + "$ref": "#/definitions/v2/ApiPathString" }, "type": "array" }, @@ -19047,7 +19047,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/v2/AbsolutePathBuf" + "$ref": "#/definitions/v2/ApiPathString" }, "type": "array" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 3d44c7a9bb..a4e1e9051a 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -14735,7 +14735,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, @@ -16439,7 +16439,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, @@ -16855,7 +16855,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 164d7de103..bbf0e46fb8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -2328,7 +2328,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index eeea70a8a2..7f092f3479 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -2354,7 +2354,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 6f68740ef6..972fc92148 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -2328,7 +2328,7 @@ "default": [], "description": "Instruction source files currently loaded for this thread.", "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "type": "array" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts index c5b1201c26..957e7a0f11 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts @@ -2,6 +2,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AbsolutePathBuf } from "../AbsolutePathBuf"; +import type { ApiPathString } from "../ApiPathString"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; @@ -11,7 +12,7 @@ import type { Thread } from "./Thread"; export type ThreadForkResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: string | null, cwd: AbsolutePathBuf, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, /** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ approvalsReviewer: ApprovalsReviewer, /** diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts index 7a4f90377c..7ef5f73760 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts @@ -2,6 +2,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AbsolutePathBuf } from "../AbsolutePathBuf"; +import type { ApiPathString } from "../ApiPathString"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; @@ -11,7 +12,7 @@ import type { Thread } from "./Thread"; export type ThreadResumeResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: string | null, cwd: AbsolutePathBuf, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, /** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ approvalsReviewer: ApprovalsReviewer, /** diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts index 85929eefe3..46e7d5ddd0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts @@ -1,7 +1,6 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AbsolutePathBuf } from "../AbsolutePathBuf"; import type { ApiPathString } from "../ApiPathString"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; @@ -12,7 +11,7 @@ import type { Thread } from "./Thread"; export type ThreadStartResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: string | null, cwd: ApiPathString, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, /** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ approvalsReviewer: ApprovalsReviewer, /** diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 003284b53b..ad428b0080 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -2518,7 +2518,9 @@ mod tests { service_tier: None, cwd: codex_utils_path_uri::ApiPathString::from_abs_path(&cwd), runtime_workspace_roots: Vec::new(), - instruction_sources: vec![absolute_path("/tmp/AGENTS.md")], + instruction_sources: vec![codex_utils_path_uri::ApiPathString::from_abs_path( + &absolute_path("/tmp/AGENTS.md"), + )], approval_policy: v2::AskForApproval::OnFailure, approvals_reviewer: v2::ApprovalsReviewer::User, sandbox: 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 72e4575e2b..5f63cad6e9 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -3627,16 +3627,31 @@ fn thread_lifecycle_responses_default_missing_optional_fields() { serde_json::from_value(response.clone()).expect("thread/start response"); let resume: ThreadResumeResponse = serde_json::from_value(response.clone()).expect("thread/resume response"); - let fork: ThreadForkResponse = serde_json::from_value(response).expect("thread/fork response"); + let fork: ThreadForkResponse = + serde_json::from_value(response.clone()).expect("thread/fork response"); - assert_eq!(start.instruction_sources, Vec::::new()); + assert_eq!(start.instruction_sources, Vec::::new()); assert_eq!(start.thread.parent_thread_id, None); - assert_eq!(resume.instruction_sources, Vec::::new()); - assert_eq!(fork.instruction_sources, Vec::::new()); + assert_eq!(resume.instruction_sources, Vec::::new()); + assert_eq!(fork.instruction_sources, Vec::::new()); assert_eq!(start.active_permission_profile, None); assert_eq!(resume.active_permission_profile, None); assert_eq!(resume.initial_turns_page, None); assert_eq!(fork.active_permission_profile, None); + + let foreign_source: ApiPathString = + serde_json::from_value(json!(r"C:\workspace\AGENTS.md")).expect("foreign source"); + let mut response_with_foreign_source = response; + response_with_foreign_source["instructionSources"] = json!([foreign_source.as_str()]); + let start: ThreadStartResponse = serde_json::from_value(response_with_foreign_source.clone()) + .expect("thread/start response with foreign source"); + let resume: ThreadResumeResponse = serde_json::from_value(response_with_foreign_source.clone()) + .expect("thread/resume response with foreign source"); + let fork: ThreadForkResponse = serde_json::from_value(response_with_foreign_source) + .expect("thread/fork response with foreign source"); + assert_eq!(start.instruction_sources, vec![foreign_source.clone()]); + assert_eq!(resume.instruction_sources, vec![foreign_source.clone()]); + assert_eq!(fork.instruction_sources, vec![foreign_source]); } #[test] 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 d383f25669..278fdfedce 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -164,7 +164,7 @@ pub struct ThreadStartResponse { pub runtime_workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] - pub instruction_sources: Vec, + pub instruction_sources: Vec, #[experimental(nested)] pub approval_policy: AskForApproval, /// Reviewer currently used for approval requests on this thread. @@ -378,7 +378,7 @@ pub struct ThreadResumeResponse { pub runtime_workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] - pub instruction_sources: Vec, + pub instruction_sources: Vec, #[experimental(nested)] pub approval_policy: AskForApproval, /// Reviewer currently used for approval requests on this thread. @@ -526,7 +526,7 @@ pub struct ThreadForkResponse { pub runtime_workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] - pub instruction_sources: Vec, + pub instruction_sources: Vec, #[experimental(nested)] pub approval_policy: AskForApproval, /// Reviewer currently used for approval requests on this thread. diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 09ed00ca6f..6e4efa06c3 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -599,6 +599,7 @@ use self::config_errors::*; use self::request_errors::*; use self::thread_goal_processor::api_thread_goal_from_state; use self::thread_lifecycle::*; +use self::thread_response_paths::thread_response_instruction_sources; use self::thread_response_paths::thread_response_runtime_workspace_roots; use self::thread_resume_redaction::*; use self::thread_summary::*; 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 fd9e93e189..105d2a08f6 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -641,7 +641,14 @@ pub(super) async fn handle_pending_thread_resume_request( reasoning_effort, .. } = config_snapshot; - let instruction_sources = pending.instruction_sources; + let instruction_sources = + match thread_response_instruction_sources(&pending.instruction_sources) { + Ok(instruction_sources) => instruction_sources, + Err(error) => { + outgoing.send_error(request_id, error).await; + return; + } + }; let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path()); let active_permission_profile = thread_response_active_permission_profile(active_permission_profile); 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 f925f9b2ca..fe7ee03a0a 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1174,7 +1174,8 @@ impl ThreadRequestProcessor { ) .await?; - let instruction_sources = thread.instruction_sources().await; + let instruction_sources = + thread_response_instruction_sources(&thread.instruction_sources().await)?; let config_snapshot = thread .config_snapshot() .instrument(tracing::info_span!( @@ -2682,7 +2683,8 @@ impl ThreadRequestProcessor { self.outgoing.send_error(request_id, err).await; return Ok(()); } - let instruction_sources = codex_thread.instruction_sources().await; + let instruction_sources = + thread_response_instruction_sources(&codex_thread.instruction_sources().await)?; let SessionConfiguredEvent { rollout_path, .. } = session_configured; let Some(rollout_path) = rollout_path else { let error = @@ -3421,7 +3423,8 @@ impl ThreadRequestProcessor { .map_err(|err| core_thread_write_error("inherit source thread name", err))?; } - let instruction_sources = forked_thread.instruction_sources().await; + let instruction_sources = + thread_response_instruction_sources(&forked_thread.instruction_sources().await)?; // Auto-attach a conversation listener when forking a thread. log_listener_attach_result( diff --git a/codex-rs/app-server/src/request_processors/thread_response_paths.rs b/codex-rs/app-server/src/request_processors/thread_response_paths.rs index eb3e04a7c5..40d0ba2cec 100644 --- a/codex-rs/app-server/src/request_processors/thread_response_paths.rs +++ b/codex-rs/app-server/src/request_processors/thread_response_paths.rs @@ -27,10 +27,30 @@ pub(super) fn thread_response_runtime_workspace_roots( "could not infer the path convention for runtime workspace root `{environment_cwd}`" )) })?; - return render_path_uri(environment_cwd, convention); + return render_path_uri(environment_cwd, convention, "runtime workspace root"); } - render_path_uri(&PathUri::from_abs_path(root), PathConvention::native()) + render_path_uri( + &PathUri::from_abs_path(root), + PathConvention::native(), + "runtime workspace root", + ) + }) + .collect() +} + +pub(super) fn thread_response_instruction_sources( + instruction_sources: &[PathUri], +) -> Result, JSONRPCErrorError> { + instruction_sources + .iter() + .map(|source| { + let convention = source.infer_path_convention().ok_or_else(|| { + internal_error(format!( + "could not infer the path convention for instruction source `{source}`" + )) + })?; + render_path_uri(source, convention, "instruction source") }) .collect() } @@ -38,10 +58,11 @@ pub(super) fn thread_response_runtime_workspace_roots( fn render_path_uri( path: &PathUri, convention: PathConvention, + description: &str, ) -> Result { ApiPathString::from_path_uri(path, convention).map_err(|err| { internal_error(format!( - "could not render runtime workspace root `{path}` using {convention}: {err}" + "could not render {description} `{path}` using {convention}: {err}" )) }) } diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 6d2b48a4c8..ad84fdf522 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -13,7 +13,9 @@ use codex_protocol::ThreadId; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_rollout::state_db::StateDbHandle; +#[cfg(test)] use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathUri; use std::collections::HashMap; use std::collections::HashSet; use std::sync::Arc; @@ -31,7 +33,7 @@ pub(crate) struct PendingThreadResumeRequest { pub(crate) request_id: ConnectionRequestId, pub(crate) history_items: Vec, pub(crate) config_snapshot: ThreadConfigSnapshot, - pub(crate) instruction_sources: Vec, + pub(crate) instruction_sources: Vec, pub(crate) thread_summary: codex_app_server_protocol::Thread, pub(crate) emit_thread_goal_update: bool, pub(crate) thread_goal_state_db: Option, 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 e67184bf01..a4a1e7a892 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -286,7 +286,13 @@ async fn thread_resume_running_thread_uses_cached_instruction_sources() -> Resul .. } = to_response::(start_resp)?; let project_agents = AbsolutePathBuf::try_from(project_agents)?; - assert_eq!(instruction_sources, vec![project_agents.clone()]); + assert_eq!( + instruction_sources, + vec![ApiPathString::from_abs_path( + &project_agents, + PathConvention::native(), + )?] + ); let turn_id = mcp .send_turn_start_request(TurnStartParams { @@ -328,7 +334,13 @@ async fn thread_resume_running_thread_uses_cached_instruction_sources() -> Resul .. } = to_response::(resume_resp)?; - assert_eq!(instruction_sources, vec![project_agents]); + assert_eq!( + instruction_sources, + vec![ApiPathString::from_abs_path( + &project_agents, + PathConvention::native(), + )?] + ); Ok(()) } 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 60ccea8320..3f543dcdd5 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -426,7 +426,7 @@ async fn thread_start_response_includes_loaded_instruction_sources() -> Result<( let instruction_sources = instruction_sources .into_iter() - .map(normalize_path_for_comparison) + .map(|path| normalize_path_for_comparison(path.as_str())) .collect::>(); let expected_instruction_sources = vec![ std::fs::canonicalize(global_agents_path)?, @@ -473,7 +473,7 @@ async fn thread_start_response_excludes_empty_project_instruction_source() -> Re let instruction_sources = instruction_sources .into_iter() - .map(normalize_path_for_comparison) + .map(|path| normalize_path_for_comparison(path.as_str())) .collect::>(); let expected_instruction_sources = vec![normalize_path_for_comparison(std::fs::canonicalize( global_agents_path, @@ -519,7 +519,7 @@ async fn thread_start_without_selected_environment_includes_only_global_instruct assert_eq!( instruction_sources .into_iter() - .map(normalize_path_for_comparison) + .map(|path| normalize_path_for_comparison(path.as_str())) .collect::>(), vec![normalize_path_for_comparison(std::fs::canonicalize( global_agents_path, diff --git a/codex-rs/core/src/agents_md.rs b/codex-rs/core/src/agents_md.rs index 861e7b4ac7..022b019f40 100644 --- a/codex-rs/core/src/agents_md.rs +++ b/codex-rs/core/src/agents_md.rs @@ -29,6 +29,8 @@ use codex_extension_api::UserInstructions; use codex_features::Feature; use codex_prompts::HIERARCHICAL_AGENTS_MESSAGE; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::ApiPathString; +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use std::io; use toml::Value as TomlValue; @@ -53,16 +55,11 @@ pub(crate) async fn load_project_instructions( let mut loaded = LoadedAgentsMd::from_user_instructions(user_instructions); for turn_environment in &environments.turn_environments { let filesystem = turn_environment.environment.get_filesystem(); - // TODO(anp): Migrate AGENTS.md discovery to PathUri so instructions can be loaded from - // environment-native foreign working directories. - let Ok(cwd) = turn_environment.cwd().to_abs_path() else { - continue; - }; match read_agents_md( config, filesystem.as_ref(), &turn_environment.environment_id, - &cwd, + turn_environment.cwd(), ) .await { @@ -97,7 +94,7 @@ async fn read_agents_md( config: &Config, fs: &dyn ExecutorFileSystem, environment_id: &str, - cwd: &AbsolutePathBuf, + cwd: &PathUri, ) -> io::Result> { let max_total = config.project_doc_max_bytes; @@ -118,15 +115,14 @@ async fn read_agents_md( break; } - let path_uri = PathUri::from_abs_path(&p); - match fs.get_metadata(&path_uri, /*sandbox*/ None).await { + match fs.get_metadata(&p, /*sandbox*/ None).await { Ok(metadata) if !metadata.is_file => continue, Ok(_) => {} Err(err) if err.kind() == io::ErrorKind::NotFound => continue, Err(err) => return Err(err), } - let mut data = match fs.read_file(&path_uri, /*sandbox*/ None).await { + let mut data = match fs.read_file(&p, /*sandbox*/ None).await { Ok(data) => data, Err(err) if err.kind() == io::ErrorKind::NotFound => continue, Err(err) => return Err(err), @@ -139,7 +135,7 @@ async fn read_agents_md( if size > remaining { tracing::warn!( "Project doc `{}` exceeds remaining budget ({} bytes) - truncating.", - p.display(), + render_path_uri(&p), remaining, ); } @@ -169,10 +165,16 @@ async fn read_agents_md( /// directory, inclusive. Symlinks are allowed. async fn agents_md_paths( config: &Config, - cwd: &AbsolutePathBuf, + cwd: &PathUri, fs: &dyn ExecutorFileSystem, -) -> io::Result> { +) -> io::Result> { let dir = cwd.clone(); + let convention = cwd.infer_path_convention().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("could not infer path convention for AGENTS.md cwd `{cwd}`"), + ) + })?; let mut merged = TomlValue::Table(toml::map::Map::new()); for layer in config.config_layer_stack.get_layers( @@ -194,28 +196,28 @@ async fn agents_md_paths( }; let mut project_root = None; if !project_root_markers.is_empty() { - for ancestor in dir.ancestors() { + let mut ancestor = Some(dir.clone()); + while let Some(current) = ancestor { for marker in &project_root_markers { - let marker_path = ancestor.join(marker); - let marker_path_uri = PathUri::from_abs_path(&marker_path); - let marker_exists = match fs.get_metadata(&marker_path_uri, /*sandbox*/ None).await - { + let marker_path = current.join(marker).map_err(path_uri_error)?; + let marker_exists = match fs.get_metadata(&marker_path, /*sandbox*/ None).await { Ok(_) => true, Err(err) if err.kind() == io::ErrorKind::NotFound => false, Err(err) => return Err(err), }; if marker_exists { - project_root = Some(ancestor.clone()); + project_root = Some(current.clone()); break; } } if project_root.is_some() { break; } + ancestor = parent_within_path_root(¤t, convention); } } - let search_dirs: Vec = if let Some(root) = project_root { + let search_dirs: Vec = if let Some(root) = project_root { let mut dirs = Vec::new(); let mut cursor = dir.clone(); loop { @@ -223,7 +225,7 @@ async fn agents_md_paths( if cursor == root { break; } - let Some(parent) = cursor.parent() else { + let Some(parent) = parent_within_path_root(&cursor, convention) else { break; }; cursor = parent; @@ -234,13 +236,12 @@ async fn agents_md_paths( vec![dir] }; - let mut found: Vec = Vec::new(); + let mut found: Vec = Vec::new(); let candidate_filenames = candidate_filenames(config); for d in search_dirs { for name in &candidate_filenames { - let candidate = d.join(name); - let candidate_uri = PathUri::from_abs_path(&candidate); - match fs.get_metadata(&candidate_uri, /*sandbox*/ None).await { + let candidate = d.join(name).map_err(path_uri_error)?; + match fs.get_metadata(&candidate, /*sandbox*/ None).await { Ok(md) if md.is_file => { found.push(candidate); break; @@ -255,6 +256,20 @@ async fn agents_md_paths( Ok(found) } +fn parent_within_path_root(path: &PathUri, convention: PathConvention) -> Option { + let minimum_depth = usize::from(convention == PathConvention::Windows); + let depth = path + .encoded_path() + .split('/') + .filter(|segment| !segment.is_empty()) + .count(); + (depth > minimum_depth).then(|| path.parent()).flatten() +} + +fn path_uri_error(err: impl std::error::Error + Send + Sync + 'static) -> io::Error { + io::Error::new(io::ErrorKind::InvalidInput, err) +} + fn candidate_filenames(config: &Config) -> Vec<&str> { let mut names: Vec<&str> = Vec::with_capacity(2 + config.project_doc_fallback_filenames.len()); names.push(LOCAL_AGENTS_MD_FILENAME); @@ -371,7 +386,7 @@ impl LoadedAgentsMd { fn environment_labeled_text(&self) -> String { let mut output = String::new(); let mut has_previous = false; - let mut previous_environment: Option<(&str, &AbsolutePathBuf)> = None; + let mut previous_environment: Option<(&str, &PathUri)> = None; if let Some(instructions) = &self.user_instructions { output.push_str(&instructions.text); has_previous = true; @@ -394,7 +409,7 @@ impl LoadedAgentsMd { output.push_str(&format!( "for `{}` with root {}\n\n", environment_id, - cwd.display() + render_path_uri(cwd) )); } output.push_str(&entry.contents); @@ -420,8 +435,7 @@ impl LoadedAgentsMd { let directory = if self.has_multiple_project_environments() { None } else { - self.single_project_cwd() - .map(|cwd| cwd.to_string_lossy().into_owned()) + self.single_project_cwd().map(render_path_uri) }; ContextUserInstructions { directory, @@ -436,10 +450,10 @@ impl LoadedAgentsMd { } /// Returns the AGENTS.md files that supplied instruction entries. - pub fn sources(&self) -> impl Iterator { + pub fn sources(&self) -> impl Iterator + '_ { self.user_instructions .iter() - .map(|instructions| &instructions.source) + .map(|instructions| PathUri::from_abs_path(&instructions.source)) .chain( self.entries .iter() @@ -463,7 +477,7 @@ impl LoadedAgentsMd { }) } - fn single_project_cwd(&self) -> Option<&AbsolutePathBuf> { + fn single_project_cwd(&self) -> Option<&PathUri> { self.entries .iter() .find_map(|entry| match &entry.provenance { @@ -488,9 +502,9 @@ enum InstructionProvenance { /// Workspace instructions discovered from project AGENTS.md files. Project { /// Exact AGENTS.md file, distinct from the environment's selected cwd. - source_path: AbsolutePathBuf, + source_path: PathUri, environment_id: String, - cwd: AbsolutePathBuf, + cwd: PathUri, }, /// Instructions without a file source, including internally defined guidance. @@ -498,14 +512,22 @@ enum InstructionProvenance { } impl InstructionProvenance { - fn path(&self) -> Option<&AbsolutePathBuf> { + fn path(&self) -> Option { match self { - Self::Project { source_path, .. } => Some(source_path), + Self::Project { source_path, .. } => Some(source_path.clone()), Self::Internal => None, } } } +fn render_path_uri(path: &PathUri) -> String { + let Some(convention) = path.infer_path_convention() else { + return path.to_string(); + }; + ApiPathString::from_path_uri(path, convention) + .map(ApiPathString::into_string) + .unwrap_or_else(|_| path.to_string()) +} #[cfg(test)] #[path = "agents_md_tests.rs"] mod tests; diff --git a/codex-rs/core/src/agents_md_tests.rs b/codex-rs/core/src/agents_md_tests.rs index 104293a059..12767a809b 100644 --- a/codex-rs/core/src/agents_md_tests.rs +++ b/codex-rs/core/src/agents_md_tests.rs @@ -237,7 +237,15 @@ async fn load_agents_md(config: &TestConfig) -> Option { } async fn agents_md_paths(config: &TestConfig) -> std::io::Result> { - super::agents_md_paths(&config.config, &config.cwd, LOCAL_FS.as_ref()).await + super::agents_md_paths( + &config.config, + &PathUri::from_abs_path(&config.cwd), + LOCAL_FS.as_ref(), + ) + .await? + .into_iter() + .map(|path| path.to_abs_path()) + .collect() } fn resolved_local_environments( @@ -263,12 +271,59 @@ fn resolved_local_environments( fn project_provenance(path: AbsolutePathBuf, cwd: AbsolutePathBuf) -> InstructionProvenance { InstructionProvenance::Project { - source_path: path, + source_path: PathUri::from_abs_path(&path), environment_id: "local".to_string(), - cwd, + cwd: PathUri::from_abs_path(&cwd), } } +#[test] +fn path_uri_parent_walk_stops_at_the_owning_root() { + for (path, expected_parent) in [ + ("file:///C:/workspace/project", Some("file:///C:/workspace")), + ("file:///C:/workspace", Some("file:///C:")), + ("file:///C:", None), + ("file://server/share/project", Some("file://server/share")), + ("file://server/share", None), + ("file:///workspace", Some("file:///")), + ("file:///", None), + ] { + let path = PathUri::parse(path).expect("path URI"); + let convention = path.infer_path_convention().expect("path convention"); + assert_eq!( + parent_within_path_root(&path, convention), + expected_parent.map(|parent| PathUri::parse(parent).expect("parent URI")), + "parent for {path}" + ); + } +} + +#[test] +fn remote_agents_md_uses_environment_native_paths() { + let cwd = PathUri::parse("file:///C:/codex%20runtime").expect("Windows cwd URI"); + let source_path = cwd.join("AGENTS.md").expect("AGENTS.md URI"); + let loaded = LoadedAgentsMd { + user_instructions: None, + entries: vec![InstructionEntry { + contents: "remote instructions".to_string(), + provenance: InstructionProvenance::Project { + source_path: source_path.clone(), + environment_id: "remote".to_string(), + cwd, + }, + }], + }; + + assert_eq!( + loaded.render(), + r#"# AGENTS.md instructions for C:\codex runtime + + +remote instructions +"# + ); + assert_eq!(loaded.sources().collect::>(), vec![source_path]); +} /// Helper that returns a `Config` pointing at `root` and using `limit` as /// the maximum number of bytes to embed from AGENTS.md. The caller can /// optionally specify a custom `instructions` string – when `None` the @@ -494,9 +549,14 @@ async fn read_agents_md_propagates_metadata_errors() { }; let cwd = config.cwd.clone(); - let err = read_agents_md(&config.config, &fs, "local", &cwd) - .await - .expect_err("metadata error"); + let err = read_agents_md( + &config.config, + &fs, + "local", + &PathUri::from_abs_path(&cwd), + ) + .await + .expect_err("metadata error"); assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); } @@ -512,9 +572,14 @@ async fn read_agents_md_propagates_read_errors() { }; let cwd = config.cwd.clone(); - let err = read_agents_md(&config.config, &fs, "local", &cwd) - .await - .expect_err("read error"); + let err = read_agents_md( + &config.config, + &fs, + "local", + &PathUri::from_abs_path(&cwd), + ) + .await + .expect_err("read error"); assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); } @@ -530,9 +595,14 @@ async fn read_agents_md_ignores_files_removed_after_discovery() { }; let cwd = config.cwd.clone(); - let loaded = read_agents_md(&config.config, &fs, "local", &cwd) - .await - .expect("removed file is recoverable"); + let loaded = read_agents_md( + &config.config, + &fs, + "local", + &PathUri::from_abs_path(&cwd), + ) + .await + .expect("removed file is recoverable"); assert_eq!(loaded, None); } @@ -645,17 +715,18 @@ secondary doc"#, ); assert_eq!(loaded.render(), expected_fragment); assert_eq!( - loaded.sources().cloned().collect::>(), + loaded.sources().collect::>(), vec![ - config - .user_instructions - .as_ref() - .expect("global instructions") - .source - .clone(), - primary.path().join("AGENTS.md").abs(), - primary_nested.join("AGENTS.md").abs(), - secondary.path().join("AGENTS.md").abs(), + PathUri::from_abs_path( + &config + .user_instructions + .as_ref() + .expect("global instructions") + .source, + ), + PathUri::from_abs_path(&primary.path().join("AGENTS.md").abs()), + PathUri::from_abs_path(&primary_nested.join("AGENTS.md").abs()), + PathUri::from_abs_path(&secondary.path().join("AGENTS.md").abs()), ] ); } @@ -884,7 +955,10 @@ async fn concatenates_root_and_cwd_docs() { assert_eq!(loaded.text(), "root doc\n\ncrate doc"); assert_eq!( loaded.sources().collect::>(), - vec![&root_agents, &crate_agents] + vec![ + PathUri::from_abs_path(&root_agents), + PathUri::from_abs_path(&crate_agents), + ] ); } @@ -1036,7 +1110,10 @@ async fn instruction_sources_include_global_before_agents_md_docs() { assert_eq!(loaded.user_instructions(), cfg.user_instructions.as_ref()); assert_eq!( loaded.sources().collect::>(), - vec![&global_agents, &project_agents] + vec![ + PathUri::from_abs_path(&global_agents), + PathUri::from_abs_path(&project_agents), + ] ); assert_eq!( loaded.text(), @@ -1077,7 +1154,10 @@ async fn child_agents_message_after_project_docs_is_not_an_instruction_source() assert_eq!(loaded, expected); assert_eq!( loaded.sources().collect::>(), - vec![&global_agents, &project_agents] + vec![ + PathUri::from_abs_path(&global_agents), + PathUri::from_abs_path(&project_agents), + ] ); assert_eq!( loaded.text(), diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 451b497827..98b217725a 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -41,6 +41,7 @@ use codex_thread_store::ThreadMetadataPatch; use codex_thread_store::ThreadStoreError; use codex_thread_store::ThreadStoreResult; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathUri; use rmcp::model::ReadResourceRequestParams; use std::collections::BTreeMap; use std::collections::HashMap; @@ -543,7 +544,7 @@ impl CodexThread { } /// Returns the files that supplied the thread's loaded model instructions. - pub async fn instruction_sources(&self) -> Vec { + pub async fn instruction_sources(&self) -> Vec { self.codex.instruction_sources().await } diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 17d62a3eeb..05971561a8 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -819,15 +819,13 @@ impl Codex { state.session_configuration.thread_config_snapshot() } - pub(crate) async fn instruction_sources(&self) -> Vec { + pub(crate) async fn instruction_sources(&self) -> Vec { let state = self.session.state.lock().await; state .session_configuration .loaded_agents_md .as_ref() - .map_or_else(Vec::new, |instructions| { - instructions.sources().cloned().collect() - }) + .map_or_else(Vec::new, |instructions| instructions.sources().collect()) } pub(crate) async fn thread_environment_selections(&self) -> Vec { diff --git a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs index 5e9eaa365e..0310b41307 100644 --- a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs +++ b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs @@ -279,8 +279,13 @@ async fn app_server_starts_thread_with_windows_environment_native_cwd() -> Resul assert!(!response.thread.id.is_empty()); assert_eq!(response.cwd.as_str(), NATIVE_CWD); assert_eq!(response.runtime_workspace_roots, vec![response.cwd.clone()]); - // TODO(anp): Discover and report instruction sources from the remote filesystem. - assert_eq!(response.instruction_sources, Vec::new()); + assert_eq!( + response.instruction_sources, + vec![ApiPathString::from_native_absolute_path( + r"C:\windows\AGENTS.md", + PathConvention::Windows, + )?] + ); assert_eq!( response.active_permission_profile, Some(ActivePermissionProfile::read_only()) @@ -355,13 +360,21 @@ async fn app_server_starts_thread_with_windows_environment_native_cwd() -> Resul .received_requests() .await .context("failed to fetch received requests")?; - let initial_request = requests.first().context("missing initial model request")?; - let model_request_includes_remote_instructions = initial_request - .body_json::()? - .to_string() - .contains(AGENTS_INSTRUCTIONS); - // TODO(anp): Load remote workspace instructions into the model context. - assert!(!model_request_includes_remote_instructions); + let remote_instructions = requests + .iter() + .filter_map(|request| request.body_json::().ok()) + .flat_map(|body| body["input"].as_array().cloned().unwrap_or_default()) + .filter_map(|item| item.get("content").and_then(Value::as_array).cloned()) + .flatten() + .filter_map(|content| { + content + .get("text") + .and_then(Value::as_str) + .map(str::to_string) + }) + .find(|text| text.contains(AGENTS_INSTRUCTIONS)) + .context("remote workspace instructions should be model visible")?; + assert!(remote_instructions.contains(r"# AGENTS.md instructions for C:\windows")); let first_request = requests .iter() diff --git a/codex-rs/core/tests/suite/agents_md.rs b/codex-rs/core/tests/suite/agents_md.rs index a4ab404065..8ff5bea8f3 100644 --- a/codex-rs/core/tests/suite/agents_md.rs +++ b/codex-rs/core/tests/suite/agents_md.rs @@ -96,6 +96,10 @@ fn expected_provider_only_instruction_fragment(contents: &str) -> String { format!("# AGENTS.md instructions\n\n\n{contents}\n") } +fn path_uri(path: &AbsolutePathBuf) -> PathUri { + PathUri::from_abs_path(path) +} + fn assert_single_instruction_fragment(request: &responses::ResponsesRequest, expected: &str) { assert_eq!(instruction_fragments(request), vec![expected.to_string()]); } @@ -334,8 +338,8 @@ async fn symlinked_cwd_uses_logical_parent_for_agents_discovery() -> Result<()> assert_eq!( test.codex.instruction_sources().await, vec![ - logical_root.join("AGENTS.md"), - test.config.cwd.join("AGENTS.md") + path_uri(&logical_root.join("AGENTS.md")), + path_uri(&test.config.cwd.join("AGENTS.md")) ] ); @@ -385,7 +389,7 @@ async fn selected_environment_sources_match_model_visible_instructions() -> Resu assert_eq!( test.codex.instruction_sources().await, - vec![global_agents, project_agents] + vec![path_uri(&global_agents), path_uri(&project_agents)] ); test.submit_turn("hello").await?; @@ -453,7 +457,7 @@ async fn loads_user_instructions_without_a_primary_environment() -> Result<()> { assert_eq!(provider.load_count(), 2); assert_eq!( no_environment_thread.thread.instruction_sources().await, - vec![global_source] + vec![path_uri(&global_source)] ); no_environment_thread @@ -520,7 +524,7 @@ async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Re }); let test = builder.build_with_remote_env(&server).await?; let project_source = test.config.cwd.join(GLOBAL_AGENTS_FILENAME); - let creation_sources = vec![global_source.clone(), project_source.clone()]; + let creation_sources = vec![path_uri(&global_source), path_uri(&project_source)]; // Confirm the thread records both creation-time sources in composition order. assert_eq!(test.codex.instruction_sources().await, creation_sources); @@ -670,9 +674,9 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho assert_eq!( thread.thread.instruction_sources().await, vec![ - global_source.clone(), - remote_source.clone(), - local_source.clone().try_into()?, + path_uri(&global_source), + path_uri(&remote_source), + PathUri::from_path(&local_source)?, ] ); @@ -710,7 +714,11 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho assert_eq!(provider.load_count(), 2); assert_eq!( thread.thread.instruction_sources().await, - vec![global_source, remote_source, local_source.try_into()?] + vec![ + path_uri(&global_source), + path_uri(&remote_source), + PathUri::from_path(&local_source)?, + ] ); Ok(()) @@ -739,7 +747,10 @@ async fn invalid_utf8_global_instructions_are_lossy() -> Result<()> { test.submit_turn("inspect lossy global instructions") .await?; - assert_eq!(test.codex.instruction_sources().await, vec![source.clone()]); + assert_eq!( + test.codex.instruction_sources().await, + vec![path_uri(&source)] + ); let expected_fragment = expected_provider_only_instruction_fragment("global\u{FFFD}instructions"); assert_single_instruction_fragment(&response_mock.single_request(), &expected_fragment); @@ -782,7 +793,7 @@ async fn cold_resume_replays_rendered_instructions_but_reports_current_config_so // Assert the pre-resume thread reports the source used to create its snapshot. assert_eq!( initial.codex.instruction_sources().await, - vec![old_source.clone()], + vec![path_uri(&old_source)], "initial thread reports the creation-time global source" ); initial.submit_turn("persist instructions").await?; @@ -812,7 +823,7 @@ async fn cold_resume_replays_rendered_instructions_but_reports_current_config_so // Assert the API reports the new source while model history replays the old structured prefix. assert_eq!( resumed.codex.instruction_sources().await, - vec![new_source], + vec![path_uri(&new_source)], "resume reports sources from the newly loaded config" ); @@ -866,7 +877,7 @@ async fn fork_replays_rendered_instructions_from_shared_history() -> Result<()> // Assert the parent reports the source used to create its snapshot. assert_eq!( parent.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "parent reports the creation-time global source" ); parent.submit_turn("persist instructions").await?; @@ -901,7 +912,7 @@ async fn fork_replays_rendered_instructions_from_shared_history() -> Result<()> // Assert the fork reports the new source before issuing its first turn. assert_eq!( forked.thread.instruction_sources().await, - vec![new_source], + vec![path_uri(&new_source)], "fork config should reflect the newly loaded global source" ); @@ -1031,7 +1042,7 @@ async fn run_subagent_global_instruction_case(fork_context: bool) -> Result<()> // Assert the parent reports the creation-time source before spawning. assert_eq!( test.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "parent reports the creation-time global source before spawning" ); test.submit_turn(SPAWN_SEED_PROMPT).await?; @@ -1074,12 +1085,12 @@ async fn run_subagent_global_instruction_case(fork_context: bool) -> Result<()> assert_single_instruction_fragment(&child_request, &expected_fragment); assert_eq!( test.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "running parent retains the creation-time global source after spawning" ); assert_eq!( child_thread.instruction_sources().await, - vec![source], + vec![path_uri(&source)], "subagent reports the parent's creation-time source" ); if fork_context { diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index cff88f57a8..15e68afd97 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -25,6 +25,7 @@ use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathUri; use core_test_support::PathBufExt; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; @@ -283,6 +284,10 @@ fn write_global_file( Ok(path.abs()) } +fn path_uri(path: &AbsolutePathBuf) -> PathUri { + PathUri::from_abs_path(path) +} + fn instruction_fragments(request: &responses::ResponsesRequest) -> Vec { request .message_input_texts("user") @@ -4590,7 +4595,7 @@ async fn manual_compaction_keeps_the_creation_time_global_instructions() -> Resu // Assert the pre-compaction source list points at the creation-time file. assert_eq!( test.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "thread reports the creation-time global source before compaction" ); @@ -4620,7 +4625,7 @@ async fn manual_compaction_keeps_the_creation_time_global_instructions() -> Resu assert_single_instruction_fragment(&requests[2], &expected_fragment); assert_eq!( test.codex.instruction_sources().await, - vec![source], + vec![path_uri(&source)], "thread retains the creation-time global source after compaction" ); @@ -4670,7 +4675,7 @@ async fn mid_turn_compaction_keeps_the_creation_time_global_instructions() -> Re // Assert the pre-compaction source list points at the creation-time file. assert_eq!( test.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "thread reports the creation-time global source before mid-turn compaction" ); @@ -4692,7 +4697,7 @@ async fn mid_turn_compaction_keeps_the_creation_time_global_instructions() -> Re assert_single_instruction_fragment(&requests[2], &expected_fragment); assert_eq!( test.codex.instruction_sources().await, - vec![source], + vec![path_uri(&source)], "thread retains the creation-time global source after mid-turn compaction" ); @@ -4777,7 +4782,7 @@ async fn remote_v2_compaction_keeps_creation_time_instructions_after_same_path_m ); assert_eq!( test.codex.instruction_sources().await, - vec![source.clone()], + vec![path_uri(&source)], "running thread retains the selected same-path source" ); assert_eq!( @@ -4826,7 +4831,7 @@ async fn remote_v2_compaction_keeps_creation_time_instructions_after_same_path_m ); assert_eq!( resumed.codex.instruction_sources().await, - vec![source], + vec![path_uri(&source)], "cold-resumed thread reports the same rewritten source path" ); diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 0ea6a54b43..82c8586b1a 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -122,6 +122,7 @@ use codex_protocol::openai_models::ReasoningEffortPreset; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::ApiPathString; use codex_utils_path_uri::PathConvention; +use codex_utils_path_uri::PathUri; use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; @@ -1548,6 +1549,12 @@ async fn thread_session_state_from_thread_start_response( .map(api_path_to_native_runtime_workspace_root) .collect::, _>>() .map_err(|err| format!("runtime workspace root is invalid: {err}"))?; + let instruction_source_paths = response + .instruction_sources + .iter() + .map(api_path_to_path_uri) + .collect::, _>>() + .map_err(|err| format!("instruction source is invalid: {err}"))?; let permission_profile = display_permission_profile_from_thread_response( &response.sandbox, cwd.as_path(), @@ -1568,7 +1575,7 @@ async fn thread_session_state_from_thread_start_response( response.active_permission_profile.clone().map(Into::into), cwd, runtime_workspace_roots, - response.instruction_sources.clone(), + instruction_source_paths, response.reasoning_effort.clone(), config, ) @@ -1608,11 +1615,25 @@ fn api_path_to_native_runtime_workspace_root( api_path_to_native_absolute_path(path) } +fn api_path_to_path_uri(path: &ApiPathString) -> Result { + let convention = path + .infer_absolute_path_convention() + .ok_or_else(|| format!("path `{}` is not absolute", path.as_str()))?; + path.to_path_uri(convention) + .map_err(|err| format!("path `{}` is invalid: {err}", path.as_str())) +} + async fn thread_session_state_from_thread_resume_response( response: &ThreadResumeResponse, config: &Config, thread_params_mode: ThreadParamsMode, ) -> Result { + let instruction_source_paths = response + .instruction_sources + .iter() + .map(api_path_to_path_uri) + .collect::, _>>() + .map_err(|err| format!("instruction source is invalid: {err}"))?; let permission_profile = if matches!(thread_params_mode, ThreadParamsMode::Embedded) && response.active_permission_profile.is_none() { @@ -1642,7 +1663,7 @@ async fn thread_session_state_from_thread_resume_response( response.active_permission_profile.clone().map(Into::into), response.cwd.clone(), response.runtime_workspace_roots.clone(), - response.instruction_sources.clone(), + instruction_source_paths, response.reasoning_effort.clone(), config, ) @@ -1654,6 +1675,12 @@ async fn thread_session_state_from_thread_fork_response( config: &Config, thread_params_mode: ThreadParamsMode, ) -> Result { + let instruction_source_paths = response + .instruction_sources + .iter() + .map(api_path_to_path_uri) + .collect::, _>>() + .map_err(|err| format!("instruction source is invalid: {err}"))?; let permission_profile = display_permission_profile_from_thread_response( &response.sandbox, response.cwd.as_path(), @@ -1674,7 +1701,7 @@ async fn thread_session_state_from_thread_fork_response( response.active_permission_profile.clone().map(Into::into), response.cwd.clone(), response.runtime_workspace_roots.clone(), - response.instruction_sources.clone(), + instruction_source_paths, response.reasoning_effort.clone(), config, ) @@ -1713,7 +1740,7 @@ async fn thread_session_state_from_thread_response( active_permission_profile: Option, cwd: AbsolutePathBuf, runtime_workspace_roots: Vec, - instruction_source_paths: Vec, + instruction_source_paths: Vec, reasoning_effort: Option, config: &Config, ) -> Result { @@ -2423,7 +2450,9 @@ mod tests { test_path_buf("/tmp/project").abs(), test_path_buf("/tmp/project/extra").abs(), ], - instruction_sources: vec![test_path_buf("/tmp/project/AGENTS.md").abs()], + instruction_sources: vec![ + ApiPathString::from_abs_path(&test_path_buf("/tmp/project/AGENTS.md").abs()), + ], approval_policy: codex_app_server_protocol::AskForApproval::Never, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::User, sandbox: read_only_profile @@ -2449,7 +2478,12 @@ mod tests { ); assert_eq!( started.session.instruction_source_paths, - response.instruction_sources + response + .instruction_sources + .iter() + .map(api_path_to_path_uri) + .collect::, _>>() + .expect("instruction source paths") ); assert_eq!(started.session.permission_profile, read_only_profile); assert_eq!(started.turns.len(), 1); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 611ccdaf55..39a2c76267 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -680,7 +680,7 @@ pub(crate) struct ChatWidget { // App-server-backed command runner for status-line workspace metadata lookups. workspace_command_runner: Option, // Instruction source files loaded for the current session, supplied by app-server. - instruction_source_paths: Vec, + instruction_source_paths: Vec, // Runtime network proxy bind addresses from SessionConfigured. session_network_proxy: Option, // Shared latch so we only warn once about invalid status-line item IDs. diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 37f20ad970..b1c9bfc6d4 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -589,7 +589,9 @@ async fn ctrl_d_with_modal_open_does_not_quit() { #[tokio::test] async fn slash_init_does_not_depend_on_loaded_instruction_sources() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.instruction_source_paths = vec![chat.config.cwd.join("project-instructions.md")]; + chat.instruction_source_paths = vec![codex_utils_path_uri::PathUri::from_abs_path( + &chat.config.cwd.join("project-instructions.md"), + )]; submit_composer_text(&mut chat, "/init"); diff --git a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs index c206313549..362af4b1c2 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs @@ -98,7 +98,9 @@ async fn status_command_uses_catalog_default_reasoning_when_config_empty() { #[tokio::test] async fn status_command_renders_instruction_sources_from_thread_session() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.instruction_source_paths = vec![chat.config.cwd.join("AGENTS.md")]; + chat.instruction_source_paths = vec![codex_utils_path_uri::PathUri::from_abs_path( + &chat.config.cwd.join("AGENTS.md"), + )]; chat.dispatch_command(SlashCommand::Status); diff --git a/codex-rs/tui/src/session_state.rs b/codex-rs/tui/src/session_state.rs index 7988ba2264..059e148a79 100644 --- a/codex-rs/tui/src/session_state.rs +++ b/codex-rs/tui/src/session_state.rs @@ -12,6 +12,7 @@ use codex_protocol::config_types::Personality; use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathUri; #[derive(Debug, Clone, PartialEq)] pub(crate) struct SessionNetworkProxyRuntime { @@ -47,7 +48,7 @@ pub(crate) struct ThreadSessionState { pub(crate) active_permission_profile: Option, pub(crate) cwd: AbsolutePathBuf, pub(crate) runtime_workspace_roots: Vec, - pub(crate) instruction_source_paths: Vec, + pub(crate) instruction_source_paths: Vec, pub(crate) reasoning_effort: Option, pub(crate) collaboration_mode: Option>, pub(crate) personality: Option, diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index f3ceeb435f..777ddec398 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -5,7 +5,9 @@ use crate::text_formatting; use chrono::DateTime; use chrono::Local; use codex_protocol::account::PlanType; -use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::ApiPathString; +use codex_utils_path_uri::PathConvention; +use codex_utils_path_uri::PathUri; use std::path::Path; use unicode_width::UnicodeWidthStr; @@ -33,10 +35,23 @@ pub(crate) fn compose_model_display( (model_name.to_string(), details) } -pub(crate) fn compose_agents_summary(config: &Config, paths: &[AbsolutePathBuf]) -> String { +pub(crate) fn compose_agents_summary(config: &Config, paths: &[PathUri]) -> String { let mut rels: Vec = Vec::new(); - for p in paths { + for path in paths { + if path.infer_path_convention() != Some(PathConvention::native()) { + let display = path + .infer_path_convention() + .and_then(|convention| ApiPathString::from_path_uri(path, convention).ok()) + .map(ApiPathString::into_string) + .unwrap_or_else(|| path.to_string()); + rels.push(display); + continue; + } + let Ok(p) = path.to_abs_path() else { + rels.push(path.to_string()); + continue; + }; let p = p.as_path(); let file_name = p .file_name() @@ -229,7 +244,10 @@ mod tests { let config = test_config(&codex_home, &cwd).await; assert_eq!( - compose_agents_summary(&config, &[global_agents_path.abs()]), + compose_agents_summary( + &config, + &[PathUri::from_abs_path(&global_agents_path.abs())] + ), format_directory_display(&global_agents_path, /*max_width*/ None) ); } @@ -242,11 +260,27 @@ mod tests { let config = test_config(&codex_home, &cwd).await; assert_eq!( - compose_agents_summary(&config, &[override_path.abs()]), + compose_agents_summary(&config, &[PathUri::from_abs_path(&override_path.abs())]), format_directory_display(&override_path, /*max_width*/ None) ); } + #[tokio::test] + async fn compose_agents_summary_preserves_foreign_path_convention() { + let codex_home = TempDir::new().expect("temp codex home"); + let cwd = TempDir::new().expect("temp cwd"); + let config = test_config(&codex_home, &cwd).await; + + assert_eq!( + compose_agents_summary( + &config, + &[PathUri::parse("file:///C:/remote%20workspace/AGENTS.md") + .expect("Windows instruction source")] + ), + r"C:\remote workspace\AGENTS.md" + ); + } + #[tokio::test] async fn compose_agents_summary_orders_global_before_project_agents() { let codex_home = TempDir::new().expect("temp codex home"); @@ -258,8 +292,8 @@ mod tests { let summary = compose_agents_summary( &config, &[ - global_agents_path.clone().abs(), - project_agents_path.clone().abs(), + PathUri::from_abs_path(&global_agents_path.clone().abs()), + PathUri::from_abs_path(&project_agents_path.clone().abs()), ], ); let mut paths = summary.split(", ");