From 6bd4a1b41d3d165dca9447a4b6e70c9e6576ac4e Mon Sep 17 00:00:00 2001 From: Adam Perry Date: Sat, 13 Jun 2026 05:04:04 +0000 Subject: [PATCH] app-server: use ApiPathString for cwd request fields --- codex-rs/Cargo.lock | 1 + codex-rs/app-server-protocol/Cargo.toml | 1 + .../schema/json/ClientRequest.json | 49 +++++++++---- .../codex_app_server_protocol.schemas.json | 49 +++++++++---- .../codex_app_server_protocol.v2.schemas.json | 49 +++++++++---- .../schema/json/v2/ThreadForkParams.json | 13 +++- .../schema/json/v2/ThreadResumeParams.json | 13 +++- .../schema/json/v2/ThreadStartParams.json | 15 ++-- .../schema/json/v2/TurnStartParams.json | 19 +++-- .../schema/typescript/ApiPathString.ts | 15 ++++ .../schema/typescript/index.ts | 1 + .../schema/typescript/v2/ThreadForkParams.ts | 3 +- .../typescript/v2/ThreadResumeParams.ts | 3 +- .../schema/typescript/v2/ThreadStartParams.ts | 3 +- .../typescript/v2/TurnEnvironmentParams.ts | 4 +- .../schema/typescript/v2/TurnStartParams.ts | 3 +- .../src/protocol/v2/tests.rs | 53 ++++++++++++-- .../src/protocol/v2/thread.rs | 9 +-- .../src/protocol/v2/turn.rs | 5 +- codex-rs/app-server-test-client/src/lib.rs | 2 +- .../request_processors/thread_processor.rs | 25 +++++-- .../src/request_processors/turn_processor.rs | 20 ++++-- .../suite/v2/experimental_feature_list.rs | 4 +- .../tests/suite/v2/mcp_server_status.rs | 4 +- .../tests/suite/v2/thread_resume.rs | 24 +++++-- .../tests/suite/v2/thread_shell_command.rs | 2 +- .../app-server/tests/suite/v2/thread_start.rs | 72 +++++++++++++++---- .../tests/suite/v2/thread_unsubscribe.rs | 8 ++- .../tests/suite/v2/turn_interrupt.rs | 8 ++- .../app-server/tests/suite/v2/turn_start.rs | 64 ++++++++++++----- .../tests/suite/v2/turn_start_zsh_fork.rs | 32 ++++++--- .../app-server/tests/suite/v2/turn_steer.rs | 14 +++- codex-rs/exec-server/src/client_api.rs | 4 +- codex-rs/exec-server/src/client_transport.rs | 2 +- codex-rs/exec-server/src/environment_toml.rs | 40 +++++++---- codex-rs/exec/src/lib.rs | 18 ++++- codex-rs/tui/src/app/thread_settings.rs | 5 +- codex-rs/tui/src/app_server_session.rs | 45 +++++++++--- .../utils/path-uri/src/api_path_string.rs | 53 +++++++++++++- .../path-uri/src/api_path_string_tests.rs | 13 ++++ 40 files changed, 595 insertions(+), 172 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/ApiPathString.ts diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d7bb37928a..7583ab2bad 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2074,6 +2074,7 @@ dependencies = [ "codex-shell-command", "codex-utils-absolute-path", "codex-utils-cargo-bin", + "codex-utils-path-uri", "inventory", "pretty_assertions", "rmcp", diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index 0749b07e08..dc69e2d4bf 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -19,6 +19,7 @@ codex-experimental-api-macros = { workspace = true } codex-protocol = { workspace = true } codex-shell-command = { workspace = true } codex-utils-absolute-path = { workspace = true } +codex-utils-path-uri = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 5e5924fc11..1564304523 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -78,6 +78,9 @@ } ] }, + "ApiPathString": { + "type": "string" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -3302,9 +3305,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -3799,9 +3806,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -3969,9 +3980,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -4086,7 +4101,7 @@ "TurnEnvironmentParams": { "properties": { "cwd": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "environmentId": { "type": "string" @@ -4169,11 +4184,15 @@ ] }, "cwd": { - "description": "Override the working directory for this turn and subsequent turns.", - "type": [ - "string", - "null" - ] + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } + ], + "description": "Override the working directory for this turn and subsequent turns." }, "effort": { "anyOf": [ 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 b5fe28b8a4..73dc13a46a 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 @@ -6111,6 +6111,9 @@ }, "type": "object" }, + "ApiPathString": { + "type": "string" + }, "AppBranding": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -16263,9 +16266,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/v2/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -17945,9 +17952,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/v2/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -18335,9 +18346,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/v2/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -18912,7 +18927,7 @@ "TurnEnvironmentParams": { "properties": { "cwd": { - "$ref": "#/definitions/v2/AbsolutePathBuf" + "$ref": "#/definitions/v2/ApiPathString" }, "environmentId": { "type": "string" @@ -19103,11 +19118,15 @@ ] }, "cwd": { - "description": "Override the working directory for this turn and subsequent turns.", - "type": [ - "string", - "null" - ] + "anyOf": [ + { + "$ref": "#/definitions/v2/ApiPathString" + }, + { + "type": "null" + } + ], + "description": "Override the working directory for this turn and subsequent turns." }, "effort": { "anyOf": [ 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 65d18213df..6f5c3746ad 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 @@ -380,6 +380,9 @@ }, "type": "object" }, + "ApiPathString": { + "type": "string" + }, "AppBranding": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -14071,9 +14074,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -15753,9 +15760,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -16143,9 +16154,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { @@ -16720,7 +16735,7 @@ "TurnEnvironmentParams": { "properties": { "cwd": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "environmentId": { "type": "string" @@ -16911,11 +16926,15 @@ ] }, "cwd": { - "description": "Override the working directory for this turn and subsequent turns.", - "type": [ - "string", - "null" - ] + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } + ], + "description": "Override the working directory for this turn and subsequent turns." }, "effort": { "anyOf": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json index e72522a26a..78aa05d800 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -5,6 +5,9 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ApiPathString": { + "type": "string" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -113,9 +116,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index 42505ac24e..4d91e3ad60 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -49,6 +49,9 @@ } ] }, + "ApiPathString": { + "type": "string" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -1169,9 +1172,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 57e6e0ab1b..46e64cbe90 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -5,6 +5,9 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ApiPathString": { + "type": "string" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -171,7 +174,7 @@ "TurnEnvironmentParams": { "properties": { "cwd": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "environmentId": { "type": "string" @@ -220,9 +223,13 @@ ] }, "cwd": { - "type": [ - "string", - "null" + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } ] }, "developerInstructions": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 070944a28b..1a64fff7fb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -27,6 +27,9 @@ ], "type": "string" }, + "ApiPathString": { + "type": "string" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -331,7 +334,7 @@ "TurnEnvironmentParams": { "properties": { "cwd": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/ApiPathString" }, "environmentId": { "type": "string" @@ -516,11 +519,15 @@ ] }, "cwd": { - "description": "Override the working directory for this turn and subsequent turns.", - "type": [ - "string", - "null" - ] + "anyOf": [ + { + "$ref": "#/definitions/ApiPathString" + }, + { + "type": "null" + } + ], + "description": "Override the working directory for this turn and subsequent turns." }, "effort": { "anyOf": [ diff --git a/codex-rs/app-server-protocol/schema/typescript/ApiPathString.ts b/codex-rs/app-server-protocol/schema/typescript/ApiPathString.ts new file mode 100644 index 0000000000..29c4bc898e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ApiPathString.ts @@ -0,0 +1,15 @@ +// 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. + +/** + * A UTF-8 path rendered using an explicitly selected native path convention. + * + * "Native" refers to the supplied [`PathConvention`], which may be foreign to + * the operating system running this process. The inner string is private so + * path-producing code must render through [`Self::from_path_uri`] rather than + * accidentally applying the current host's path rules. Opaque fallback paths + * are decoded using the supplied convention and converted to UTF-8 lossily at + * this API boundary because the value is serialized as a JSON string. + */ +export type ApiPathString = string; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index ad6376fa58..d862add2a9 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -3,6 +3,7 @@ export type { AbsolutePathBuf } from "./AbsolutePathBuf"; export type { AgentMessageInputContent } from "./AgentMessageInputContent"; export type { AgentPath } from "./AgentPath"; +export type { ApiPathString } from "./ApiPathString"; export type { ApplyPatchApprovalParams } from "./ApplyPatchApprovalParams"; export type { ApplyPatchApprovalResponse } from "./ApplyPatchApprovalResponse"; export type { AuthMode } from "./AuthMode"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts index c5109b2c7d..0cfdd65e43 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -1,6 +1,7 @@ // 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 { ApiPathString } from "../ApiPathString"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; @@ -20,7 +21,7 @@ import type { ThreadSource } from "./ThreadSource"; export type ThreadForkParams = {threadId: string, /** * Configuration overrides for the forked thread, if any. */ -model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /** +model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: ApiPathString | null, approvalPolicy?: AskForApproval | null, /** * Override where approval requests are routed for review on this thread * and subsequent turns. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts index 0ec8953435..46fa1a20fb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts @@ -1,6 +1,7 @@ // 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 { ApiPathString } from "../ApiPathString"; import type { Personality } from "../Personality"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; @@ -26,7 +27,7 @@ import type { SandboxMode } from "./SandboxMode"; export type ThreadResumeParams = {threadId: string, /** * Configuration overrides for the resumed thread, if any. */ -model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /** +model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: ApiPathString | null, approvalPolicy?: AskForApproval | null, /** * Override where approval requests are routed for review on this thread * and subsequent turns. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts index 30509ef6cb..092bc8b0d4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts @@ -1,6 +1,7 @@ // 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 { ApiPathString } from "../ApiPathString"; import type { Personality } from "../Personality"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; @@ -9,7 +10,7 @@ import type { SandboxMode } from "./SandboxMode"; import type { ThreadSource } from "./ThreadSource"; import type { ThreadStartSource } from "./ThreadStartSource"; -export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /** +export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: ApiPathString | null, approvalPolicy?: AskForApproval | null, /** * Override where approval requests are routed for review on this thread * and subsequent turns. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts index bb981b0ac9..ba7f364beb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts @@ -1,6 +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"; -export type TurnEnvironmentParams = { environmentId: string, cwd: AbsolutePathBuf, }; +export type TurnEnvironmentParams = { environmentId: string, cwd: ApiPathString, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts index afe1ac6d94..6ed12667b4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts @@ -1,6 +1,7 @@ // 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 { ApiPathString } from "../ApiPathString"; import type { Personality } from "../Personality"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ReasoningSummary } from "../ReasoningSummary"; @@ -13,7 +14,7 @@ import type { UserInput } from "./UserInput"; export type TurnStartParams = {threadId: string, clientUserMessageId?: string | null, input: Array, /** * Override the working directory for this turn and subsequent turns. */ -cwd?: string | null, /** +cwd?: ApiPathString | null, /** * Override the approval policy for this turn and subsequent turns. */ approvalPolicy?: AskForApproval | null, /** 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 569ae666c3..39475254d2 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -3762,7 +3762,9 @@ fn thread_settings_update_params_preserve_field_level_experimental_gates() { #[test] fn turn_start_params_round_trip_environments() { - let cwd = test_absolute_path(); + // Use explicitly Windows-shaped text instead of the host-native test path + // so this catches accidental parsing with the app-server host's path rules. + let cwd = r"C:\workspace\repo"; let params: TurnStartParams = serde_json::from_value(json!({ "threadId": "thread_123", "input": [], @@ -3779,7 +3781,7 @@ fn turn_start_params_round_trip_environments() { params.environments, Some(vec![TurnEnvironmentParams { environment_id: "local".to_string(), - cwd: cwd.clone(), + cwd: cwd.to_string().try_into().expect("absolute cwd"), }]) ); assert_eq!( @@ -3799,6 +3801,50 @@ fn turn_start_params_round_trip_environments() { ); } +#[test] +fn cwd_request_fields_preserve_cross_platform_path_syntax() { + #[cfg(windows)] + let cwd = r"C:\workspace\repo"; + #[cfg(not(windows))] + let cwd = "/workspace/repo"; + let thread_start: ThreadStartParams = serde_json::from_value(json!({ "cwd": cwd })) + .expect("thread start params should deserialize"); + let turn_start: TurnStartParams = serde_json::from_value(json!({ + "threadId": "thread_123", + "input": [], + "cwd": cwd, + })) + .expect("turn start params should deserialize"); + let thread_resume: ThreadResumeParams = serde_json::from_value(json!({ + "threadId": "thread_123", + "cwd": cwd, + })) + .expect("thread resume params should deserialize"); + let thread_fork: ThreadForkParams = serde_json::from_value(json!({ + "threadId": "thread_123", + "cwd": cwd, + })) + .expect("thread fork params should deserialize"); + let settings_update: ThreadSettingsUpdateParams = serde_json::from_value(json!({ + "threadId": "thread_123", + "cwd": cwd, + })) + .expect("thread settings update params should deserialize"); + + for serialized in [ + serde_json::to_value(thread_start), + serde_json::to_value(turn_start), + serde_json::to_value(thread_resume), + serde_json::to_value(thread_fork), + serde_json::to_value(settings_update), + ] { + assert_eq!( + serialized.expect("params should serialize").get("cwd"), + Some(&json!(cwd)) + ); + } +} + #[test] fn turn_start_params_preserve_empty_environments() { let params: TurnStartParams = serde_json::from_value(json!({ @@ -3859,8 +3905,7 @@ fn turn_start_params_reject_relative_environment_cwd() { .expect_err("relative environment cwd should fail"); assert!( - err.to_string() - .contains("AbsolutePathBuf deserialized without a base path"), + err.to_string().contains("must be absolute"), "unexpected error: {err}" ); } 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 5b412c2edd..5c08568878 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -22,6 +22,7 @@ use codex_protocol::protocol::ThreadGoalStatus as CoreThreadGoalStatus; use codex_protocol::protocol::TokenUsage as CoreTokenUsage; use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::ApiPathString; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -108,7 +109,7 @@ pub struct ThreadStartParams { #[ts(optional = nullable)] pub service_tier: Option>, #[ts(optional = nullable)] - pub cwd: Option, + pub cwd: Option, /// Replace the thread's runtime workspace roots. Paths must be absolute. #[experimental("thread/start.runtimeWorkspaceRoots")] #[ts(optional = nullable)] @@ -229,7 +230,7 @@ pub struct ThreadSettingsUpdateParams { pub thread_id: String, /// Override the working directory for subsequent turns. #[ts(optional = nullable)] - pub cwd: Option, + pub cwd: Option, /// Override the approval policy for subsequent turns. #[experimental(nested)] #[ts(optional = nullable)] @@ -362,7 +363,7 @@ pub struct ThreadResumeParams { #[ts(optional = nullable)] pub service_tier: Option>, #[ts(optional = nullable)] - pub cwd: Option, + pub cwd: Option, /// Replace the thread's runtime workspace roots. Paths must be absolute. #[experimental("thread/resume.runtimeWorkspaceRoots")] #[ts(optional = nullable)] @@ -512,7 +513,7 @@ pub struct ThreadForkParams { #[ts(optional = nullable)] pub service_tier: Option>, #[ts(optional = nullable)] - pub cwd: Option, + pub cwd: Option, /// Replace the thread's runtime workspace roots. Paths must be absolute. #[experimental("thread/fork.runtimeWorkspaceRoots")] #[ts(optional = nullable)] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs index 836c6d4e96..eda2b0801b 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs @@ -14,6 +14,7 @@ use codex_protocol::user_input::ByteRange as CoreByteRange; use codex_protocol::user_input::TextElement as CoreTextElement; use codex_protocol::user_input::UserInput as CoreUserInput; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::ApiPathString; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -38,7 +39,7 @@ pub enum TurnStatus { #[ts(export_to = "v2/")] pub struct TurnEnvironmentParams { pub environment_id: String, - pub cwd: AbsolutePathBuf, + pub cwd: ApiPathString, } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] @@ -92,7 +93,7 @@ pub struct TurnStartParams { pub environments: Option>, /// Override the working directory for this turn and subsequent turns. #[ts(optional = nullable)] - pub cwd: Option, + pub cwd: Option, /// Replace the thread's runtime workspace roots for this turn and /// subsequent turns. Paths must be absolute. #[experimental("turn/start.runtimeWorkspaceRoots")] diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index e89a8dbe99..cb1c8b2df8 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -1268,7 +1268,7 @@ fn live_elicitation_timeout_pause( approval_policy: Some(AskForApproval::Never), sandbox_policy: Some(SandboxPolicy::DangerFullAccess), effort: Some(ReasoningEffort::High), - cwd: Some(workspace), + cwd: Some(workspace.try_into()?), ..Default::default() })?; println!("< turn/start response: {turn_response:?}"); 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 5c10926858..0b93e99a70 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -47,7 +47,11 @@ fn collect_resume_override_mismatches( config_snapshot.service_tier )); } - if let Some(requested_cwd) = request.cwd.as_deref() { + if let Some(requested_cwd) = request + .cwd + .as_ref() + .map(codex_utils_path_uri::ApiPathString::as_str) + { let requested_cwd_path = std::path::PathBuf::from(requested_cwd); if requested_cwd_path != config_snapshot.cwd().as_path() { mismatch_details.push(format!( @@ -869,6 +873,7 @@ impl ThreadRequestProcessor { thread_source, environments, } = params; + let cwd = cwd.map(codex_utils_path_uri::ApiPathString::into_string); if sandbox.is_some() && permissions.is_some() { return Err(invalid_request( "`permissions` cannot be combined with `sandbox`", @@ -1290,12 +1295,20 @@ impl ThreadRequestProcessor { let environment_selections = environments.map(|environments| { environments .into_iter() - .map(|environment| TurnEnvironmentSelection { - environment_id: environment.environment_id, - cwd: environment.cwd, + .map(|environment| { + Ok(TurnEnvironmentSelection { + environment_id: environment.environment_id, + cwd: AbsolutePathBuf::from_absolute_path(PathBuf::from( + environment.cwd.into_string(), + )) + .map_err(|err| { + invalid_request(format!("invalid environment cwd: {err}")) + })?, + }) }) - .collect::>() + .collect::, JSONRPCErrorError>>() }); + let environment_selections = environment_selections.transpose()?; if let Some(environment_selections) = environment_selections.as_ref() { self.thread_manager .validate_environment_selections(environment_selections) @@ -2559,6 +2572,7 @@ impl ThreadRequestProcessor { exclude_turns, initial_turns_page, } = params; + let cwd = cwd.map(codex_utils_path_uri::ApiPathString::into_string); let include_turns = !exclude_turns; let resume_result = if let Some(history) = history { @@ -3265,6 +3279,7 @@ impl ThreadRequestProcessor { thread_source, exclude_turns, } = params; + let cwd = cwd.map(codex_utils_path_uri::ApiPathString::into_string); let include_turns = !exclude_turns; if sandbox.is_some() && permissions.is_some() { return Err(invalid_request( diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index b9d6656cc4..ee0c1c96e5 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -337,12 +337,20 @@ impl TurnRequestProcessor { let environment_selections = environments.map(|environments| { environments .into_iter() - .map(|environment| TurnEnvironmentSelection { - environment_id: environment.environment_id, - cwd: environment.cwd, + .map(|environment| { + Ok(TurnEnvironmentSelection { + environment_id: environment.environment_id, + cwd: AbsolutePathBuf::from_absolute_path(PathBuf::from( + environment.cwd.into_string(), + )) + .map_err(|err| { + invalid_request(format!("invalid environment cwd: {err}")) + })?, + }) }) - .collect::>() + .collect::, JSONRPCErrorError>>() }); + let environment_selections = environment_selections.transpose()?; if let Some(environment_selections) = environment_selections.as_ref() { self.thread_manager .validate_environment_selections(environment_selections) @@ -433,7 +441,7 @@ impl TurnRequestProcessor { let client_user_message_id = params.client_user_message_id; let additional_context = map_additional_context(params.additional_context); let turn_has_input = !mapped_items.is_empty(); - let cwd = resolve_request_cwd(params.cwd)?; + let cwd = resolve_request_cwd(params.cwd.map(|cwd| cwd.into_string().into()))?; let environments = Self::build_environment_override(thread.as_ref(), cwd, environment_selections).await; let thread_settings = self @@ -692,7 +700,7 @@ impl TurnRequestProcessor { params: ThreadSettingsUpdateParams, ) -> Result { let (_, thread) = self.load_thread(¶ms.thread_id).await?; - let cwd = resolve_request_cwd(params.cwd)?; + let cwd = resolve_request_cwd(params.cwd.map(|cwd| cwd.into_string().into()))?; let environments = Self::build_environment_override( thread.as_ref(), cwd, diff --git a/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs b/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs index 797736b7af..47f6fc03c0 100644 --- a/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs +++ b/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs @@ -200,7 +200,9 @@ memories = true let thread_start_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some(serde_json::from_value(serde_json::json!( + workspace.path().display().to_string() + ))?), ..Default::default() }) .await?; diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs index 2c34684ada..ea39df39fa 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs @@ -137,7 +137,9 @@ async fn mcp_server_status_list_uses_thread_project_local_config() -> Result<()> let thread_start_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().to_string_lossy().into_owned()), + cwd: Some(serde_json::from_value(serde_json::json!( + workspace.path().to_string_lossy() + ))?), ..Default::default() }) .await?; 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 cf797ff6be..f04e3255b2 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -271,7 +271,11 @@ async fn thread_resume_running_thread_uses_cached_instruction_sources() -> Resul let start_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -2220,7 +2224,11 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> { .send_thread_resume_request(ThreadResumeParams { thread_id: "not-a-valid-thread-id".to_string(), path: Some(normalized_existing_path(&rollout.rollout_file_path)?), - cwd: Some(codex_home.path().to_string_lossy().to_string()), + cwd: Some( + (codex_home.path().to_string_lossy().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -2727,7 +2735,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R .send_thread_resume_request(ThreadResumeParams { thread_id: thread.id.clone(), model: Some("not-the-running-model".to_string()), - cwd: Some("/tmp".to_string()), + cwd: Some(("/tmp".to_string()).try_into().expect("absolute cwd")), initial_turns_page: Some(ThreadResumeInitialTurnsPageParams { limit: None, sort_direction: None, @@ -3020,7 +3028,11 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result< let start_id = primary .send_thread_start_request(ThreadStartParams { model: Some("gpt-5.4".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -3039,7 +3051,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result< text: "seed history".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -3063,7 +3075,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result< text: "apply patch".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), approval_policy: Some(AskForApproval::UnlessTrusted), ..Default::default() }) diff --git a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs index 312267d0a6..94d8c3ada0 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs @@ -274,7 +274,7 @@ async fn thread_shell_command_uses_existing_active_turn() -> Result<()> { text: "run python".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; 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 82a2b6b2c0..480179d877 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -215,7 +215,11 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> { let req_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(cwd.to_string_lossy().to_string()), + cwd: Some( + (cwd.to_string_lossy().to_string()) + .try_into() + .expect("absolute cwd"), + ), runtime_workspace_roots: Some(vec![extra_root.abs()]), ..Default::default() }) @@ -256,7 +260,11 @@ async fn thread_start_excludes_profile_workspace_roots_from_runtime_workspace_ro let req_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(cwd.path().to_string_lossy().to_string()), + cwd: Some( + (cwd.path().to_string_lossy().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -328,7 +336,11 @@ async fn thread_start_response_includes_loaded_instruction_sources() -> Result<( let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -375,7 +387,11 @@ async fn thread_start_response_excludes_empty_project_instruction_source() -> Re let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -418,7 +434,11 @@ async fn thread_start_without_selected_environment_includes_only_global_instruct let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), environments: Some(Vec::new()), ..Default::default() }) @@ -556,7 +576,11 @@ model_reasoning_effort = "high" let req_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().to_string_lossy().into_owned()), + cwd: Some( + (workspace.path().to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -948,7 +972,11 @@ model_reasoning_effort = "high" let first_request = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), sandbox: Some(SandboxMode::WorkspaceWrite), ..Default::default() }) @@ -961,7 +989,11 @@ model_reasoning_effort = "high" let second_request = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -1008,7 +1040,11 @@ async fn thread_start_with_nested_git_cwd_trusts_repo_root() -> Result<()> { let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(nested.display().to_string()), + cwd: Some( + (nested.display().to_string()) + .try_into() + .expect("absolute cwd"), + ), sandbox: Some(SandboxMode::WorkspaceWrite), ..Default::default() }) @@ -1046,7 +1082,11 @@ async fn thread_start_with_read_only_sandbox_does_not_persist_project_trust() -> let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -1084,7 +1124,11 @@ async fn thread_start_preserves_untrusted_project_trust() -> Result<()> { let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), sandbox: Some(SandboxMode::WorkspaceWrite), ..Default::default() }) @@ -1125,7 +1169,11 @@ model_reasoning_effort = "high" let request_id = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), sandbox: Some(SandboxMode::WorkspaceWrite), ..Default::default() }) diff --git a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs index 55aac670f8..2b9d106b44 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs @@ -156,7 +156,7 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running() -> Result<()> { text: "run deterministic tool".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory), + cwd: Some((working_directory).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -319,7 +319,11 @@ async fn thread_unsubscribe_preserves_cached_status_before_idle_unload() -> Resu let resume_id = mcp .send_thread_resume_request(ThreadResumeParams { thread_id, - cwd: Some(codex_home.path().to_string_lossy().to_string()), + cwd: Some( + (codex_home.path().to_string_lossy().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; diff --git a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs index 335d32776d..dd7542fe2c 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs @@ -83,7 +83,11 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> { text: "run sleep".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory.clone()), + cwd: Some( + (working_directory.clone()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -260,7 +264,7 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<() text: "run python".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory), + cwd: Some((working_directory).try_into().expect("absolute cwd")), approval_policy: Some(codex_app_server_protocol::AskForApproval::UnlessTrusted), ..Default::default() }) 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 7fc0d8c71d..15bd8a1947 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -2186,7 +2186,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> { text: "run python".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -2344,7 +2344,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { }], responsesapi_client_metadata: None, additional_context: None, - cwd: Some(first_cwd.clone()), + cwd: Some((first_cwd.clone()).try_into().expect("absolute cwd")), runtime_workspace_roots: None, approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), approvals_reviewer: None, @@ -2388,7 +2388,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { }], responsesapi_client_metadata: None, additional_context: None, - cwd: Some(second_cwd.clone()), + cwd: Some((second_cwd.clone()).try_into().expect("absolute cwd")), runtime_workspace_roots: None, approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), approvals_reviewer: None, @@ -2668,7 +2668,7 @@ async fn run_environment_selection_case( let thread_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some(workspace.to_path_buf().try_into()?), environments: environment_params(case.sticky, workspace)?, ..Default::default() }) @@ -2689,7 +2689,7 @@ async fn run_environment_selection_case( text_elements: Vec::new(), }], environments: environment_params(case.turn, workspace)?, - cwd: Some(workspace.to_path_buf()), + cwd: Some(workspace.to_path_buf().try_into()?), model: Some("mock-model".to_string()), ..Default::default() }) @@ -2785,7 +2785,11 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { let start_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -2804,7 +2808,7 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { text: "apply patch".into(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -2976,7 +2980,11 @@ async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v let start_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -2995,7 +3003,7 @@ async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v text: "apply patch".into(), text_elements: Vec::new(), }], - cwd: Some(workspace), + cwd: Some((workspace).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -3114,7 +3122,11 @@ async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> { let start_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -3133,7 +3145,7 @@ async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> { text: "apply patch".into(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -3781,7 +3793,11 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res let start_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -3801,7 +3817,7 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res text: "apply patch 1".into(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -3874,7 +3890,7 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res text: "apply patch 2".into(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -3954,7 +3970,11 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> { let start_req = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -3973,7 +3993,7 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> { text: "apply patch".into(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -4234,7 +4254,11 @@ async fn turn_start_with_elevated_override_does_not_persist_project_trust() -> R let thread_request = mcp .send_thread_start_request(ThreadStartParams { - cwd: Some(workspace.path().display().to_string()), + cwd: Some( + (workspace.path().display().to_string()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -4248,7 +4272,11 @@ async fn turn_start_with_elevated_override_does_not_persist_project_trust() -> R let turn_request = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, - cwd: Some(workspace.path().to_path_buf()), + cwd: Some( + (workspace.path().to_path_buf()) + .try_into() + .expect("absolute cwd"), + ), sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), input: vec![V2UserInput::Text { text: "Hello".to_string(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs index dfb76ecbc2..3adbdb680a 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs @@ -103,7 +103,11 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { let start_id = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -122,7 +126,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { text: "run echo hi".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), model: Some("mock-model".to_string()), @@ -222,7 +226,11 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> { let start_id = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -241,7 +249,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> { text: "run python".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -355,7 +363,11 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> { let start_id = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -374,7 +386,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> { text: "run python".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), ..Default::default() }) .await?; @@ -514,7 +526,11 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() let start_id = mcp .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), - cwd: Some(workspace.to_string_lossy().into_owned()), + cwd: Some( + (workspace.to_string_lossy().into_owned()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -533,7 +549,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() text: "remove both files".to_string(), text_elements: Vec::new(), }], - cwd: Some(workspace.clone()), + cwd: Some((workspace.clone()).try_into().expect("absolute cwd")), approval_policy: Some(codex_app_server_protocol::AskForApproval::UnlessTrusted), // This test is about execve-intercept approval propagation, not // workspace sandboxing. Using full access avoids macOS sandbox diff --git a/codex-rs/app-server/tests/suite/v2/turn_steer.rs b/codex-rs/app-server/tests/suite/v2/turn_steer.rs index ed0ea2def5..5100db9306 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_steer.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_steer.rs @@ -160,7 +160,11 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> { text: "run sleep".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory.clone()), + cwd: Some( + (working_directory.clone()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -274,7 +278,11 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { text: "run sleep".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory.clone()), + cwd: Some( + (working_directory.clone()) + .try_into() + .expect("absolute cwd"), + ), ..Default::default() }) .await?; @@ -411,7 +419,7 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu text: "run sleep".to_string(), text_elements: Vec::new(), }], - cwd: Some(working_directory), + cwd: Some((working_directory).try_into().expect("absolute cwd")), ..Default::default() }) .await?; diff --git a/codex-rs/exec-server/src/client_api.rs b/codex-rs/exec-server/src/client_api.rs index 899863723f..8beccc6f4d 100644 --- a/codex-rs/exec-server/src/client_api.rs +++ b/codex-rs/exec-server/src/client_api.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; -use std::path::PathBuf; use std::time::Duration; +use codex_utils_path_uri::ApiPathString; use futures::future::BoxFuture; use crate::ExecServerError; @@ -45,7 +45,7 @@ pub(crate) struct StdioExecServerCommand { pub program: String, pub args: Vec, pub env: HashMap, - pub cwd: Option, + pub cwd: Option, } /// Parameters used to connect to a remote exec-server environment. diff --git a/codex-rs/exec-server/src/client_transport.rs b/codex-rs/exec-server/src/client_transport.rs index 4bdc09a80e..6ac180d86a 100644 --- a/codex-rs/exec-server/src/client_transport.rs +++ b/codex-rs/exec-server/src/client_transport.rs @@ -135,7 +135,7 @@ fn stdio_command_process(stdio_command: &StdioExecServerCommand) -> Command { command.args(&stdio_command.args); command.envs(&stdio_command.env); if let Some(cwd) = &stdio_command.cwd { - command.current_dir(cwd); + command.current_dir(cwd.as_str()); } #[cfg(unix)] command.process_group(0); diff --git a/codex-rs/exec-server/src/environment_toml.rs b/codex-rs/exec-server/src/environment_toml.rs index 87d5bea8b3..17ec331863 100644 --- a/codex-rs/exec-server/src/environment_toml.rs +++ b/codex-rs/exec-server/src/environment_toml.rs @@ -4,6 +4,9 @@ use std::path::Path; use std::path::PathBuf; use std::time::Duration; +use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::ApiPathString; +use codex_utils_path_uri::PathConvention; use serde::Deserialize; use tokio_tungstenite::tungstenite::client::IntoClientRequest; @@ -165,7 +168,7 @@ fn parse_environment_toml( "environment `{id}` program cannot be empty" ))); } - let cwd = normalize_stdio_cwd(&id, cwd, config_dir)?; + let cwd = resolve_stdio_cwd(&id, cwd, config_dir)?; ExecServerTransportParams::StdioCommand { command: StdioExecServerCommand { program, @@ -186,23 +189,32 @@ fn parse_environment_toml( Ok((id, transport_params)) } -fn normalize_stdio_cwd( +fn resolve_stdio_cwd( id: &str, cwd: Option, config_dir: Option<&Path>, -) -> Result, ExecServerError> { +) -> Result, ExecServerError> { let Some(cwd) = cwd else { return Ok(None); }; - if cwd.is_absolute() { - return Ok(Some(cwd)); - } - let Some(config_dir) = config_dir else { - return Err(ExecServerError::Protocol(format!( - "environment `{id}` cwd must be absolute" - ))); + let cwd = if cwd.is_absolute() { + cwd + } else { + let Some(config_dir) = config_dir else { + return Err(ExecServerError::Protocol(format!( + "environment `{id}` cwd must be absolute" + ))); + }; + config_dir.join(cwd) }; - Ok(Some(config_dir.join(cwd))) + let cwd = AbsolutePathBuf::from_absolute_path(cwd).map_err(|err| { + ExecServerError::Protocol(format!("environment `{id}` cwd must be absolute: {err}")) + })?; + ApiPathString::from_abs_path(&cwd, PathConvention::native()) + .map(Some) + .map_err(|err| { + ExecServerError::Protocol(format!("environment `{id}` cwd cannot be rendered: {err}")) + }) } pub(crate) fn environment_provider_from_codex_home( @@ -579,6 +591,10 @@ mod tests { Some(config_dir.path()), ) .expect("provider"); + let expected_cwd = AbsolutePathBuf::from_absolute_path(config_dir.path().join("workspace")) + .expect("absolute cwd"); + let expected_cwd = ApiPathString::from_abs_path(&expected_cwd, PathConvention::native()) + .expect("rendered cwd"); assert_eq!( provider.environments[0].1, @@ -587,7 +603,7 @@ mod tests { program: "ssh".to_string(), args: Vec::new(), env: HashMap::new(), - cwd: Some(config_dir.path().join("workspace")), + cwd: Some(expected_cwd), }, initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT, } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 6578523e9c..b060a18e3f 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -876,7 +876,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { responsesapi_client_metadata: None, additional_context: None, environments: None, - cwd: Some(default_cwd), + cwd: Some(default_cwd.try_into()?), runtime_workspace_roots: None, approval_policy: Some(default_approval_policy.into()), approvals_reviewer: None, @@ -1048,7 +1048,13 @@ fn thread_start_params_from_config(config: &Config) -> ThreadStartParams { ThreadStartParams { model: config.model.clone(), model_provider: Some(config.model_provider_id.clone()), - cwd: Some(config.cwd.to_string_lossy().to_string()), + cwd: Some( + config + .cwd + .to_path_buf() + .try_into() + .unwrap_or_else(|err| panic!("config cwd should be absolute: {err}")), + ), runtime_workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), @@ -1073,7 +1079,13 @@ fn thread_resume_params_from_config(config: &Config, thread_id: String) -> Threa thread_id, model: config.model.clone(), model_provider: Some(config.model_provider_id.clone()), - cwd: Some(config.cwd.to_string_lossy().to_string()), + cwd: Some( + config + .cwd + .to_path_buf() + .try_into() + .unwrap_or_else(|err| panic!("config cwd should be absolute: {err}")), + ), runtime_workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), diff --git a/codex-rs/tui/src/app/thread_settings.rs b/codex-rs/tui/src/app/thread_settings.rs index 84dcebe1a8..62faf59f09 100644 --- a/codex-rs/tui/src/app/thread_settings.rs +++ b/codex-rs/tui/src/app/thread_settings.rs @@ -117,7 +117,10 @@ impl App { let params = ThreadSettingsUpdateParams { thread_id: thread_id.to_string(), - cwd: cwd.clone(), + cwd: cwd.clone().map(|cwd| { + cwd.try_into() + .unwrap_or_else(|err| panic!("override cwd should be absolute: {err}")) + }), approval_policy: *approval_policy, approvals_reviewer: approvals_reviewer.map(AppServerApprovalsReviewer::from), permissions: active_permission_profile diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 26f8dc8790..01e71fde00 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -769,7 +769,7 @@ impl AppServerSession { responsesapi_client_metadata: None, additional_context: None, environments: None, - cwd: Some(cwd), + cwd: Some(cwd.try_into()?), runtime_workspace_roots: Some(workspace_roots.to_vec()), approval_policy: Some(approval_policy), approvals_reviewer: Some(approvals_reviewer.into()), @@ -1384,7 +1384,10 @@ fn thread_start_params_from_config( model: config.model.clone(), model_provider: thread_params_mode.model_provider_from_config(config), service_tier: service_tier_override_from_config(config), - cwd: thread_cwd_from_config(config, thread_params_mode, remote_cwd_override), + cwd: thread_cwd_from_config(config, thread_params_mode, remote_cwd_override).map(|cwd| { + cwd.try_into() + .unwrap_or_else(|err| panic!("thread cwd should be absolute: {err}")) + }), runtime_workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), @@ -1422,7 +1425,10 @@ fn thread_resume_params_from_config( model: config.model.clone(), model_provider: thread_params_mode.model_provider_from_config(&config), service_tier: service_tier_override_from_config(&config), - cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override), + cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override).map(|cwd| { + cwd.try_into() + .unwrap_or_else(|err| panic!("thread cwd should be absolute: {err}")) + }), runtime_workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(&config), @@ -1457,7 +1463,10 @@ fn thread_fork_params_from_config( model: config.model.clone(), model_provider: thread_params_mode.model_provider_from_config(&config), service_tier: service_tier_override_from_config(&config), - cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override), + cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override).map(|cwd| { + cwd.try_into() + .unwrap_or_else(|err| panic!("thread cwd should be absolute: {err}")) + }), runtime_workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(&config), @@ -1856,7 +1865,16 @@ mod tests { /*session_start_source*/ None, ); - assert_eq!(params.cwd, Some(config.cwd.to_string_lossy().to_string())); + assert_eq!( + params.cwd, + Some( + config + .cwd + .to_path_buf() + .try_into() + .unwrap_or_else(|err| panic!("config cwd should be absolute: {err}")) + ) + ); assert_eq!( params.runtime_workspace_roots, Some(config.workspace_roots.clone()) @@ -2090,7 +2108,7 @@ mod tests { let temp_dir = tempfile::tempdir().expect("tempdir"); let config = build_config(&temp_dir).await; let thread_id = ThreadId::new(); - let remote_cwd = PathBuf::from("repo/on/server"); + let remote_cwd = PathBuf::from("/repo/on/server"); let expected_sandbox = sandbox_mode_from_permission_profile( &config.permissions.effective_permission_profile(), config.cwd.as_path(), @@ -2115,9 +2133,18 @@ mod tests { Some(remote_cwd.as_path()), ); - assert_eq!(start.cwd.as_deref(), Some("repo/on/server")); - assert_eq!(resume.cwd.as_deref(), Some("repo/on/server")); - assert_eq!(fork.cwd.as_deref(), Some("repo/on/server")); + let Some(start_cwd) = start.cwd.as_ref() else { + panic!("start cwd should be present"); + }; + let Some(resume_cwd) = resume.cwd.as_ref() else { + panic!("resume cwd should be present"); + }; + let Some(fork_cwd) = fork.cwd.as_ref() else { + panic!("fork cwd should be present"); + }; + assert_eq!(start_cwd.as_str(), "/repo/on/server"); + assert_eq!(resume_cwd.as_str(), "/repo/on/server"); + assert_eq!(fork_cwd.as_str(), "/repo/on/server"); assert_eq!(start.model_provider, None); assert_eq!(resume.model_provider, None); assert_eq!(fork.model_provider, None); 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 84222c6eb2..0664146c22 100644 --- a/codex-rs/utils/path-uri/src/api_path_string.rs +++ b/codex-rs/utils/path-uri/src/api_path_string.rs @@ -2,9 +2,11 @@ use crate::PathUri; use codex_utils_absolute_path::AbsolutePathBuf; use schemars::JsonSchema; use serde::Deserialize; +use serde::Deserializer; use serde::Serialize; use serde::Serializer; use std::fmt; +use std::path::PathBuf; use thiserror::Error; use ts_rs::TS; @@ -51,7 +53,7 @@ impl fmt::Display for PathConvention { /// accidentally applying the current host's path rules. Opaque fallback paths /// are decoded using the supplied convention and converted to UTF-8 lossily at /// this API boundary because the value is serialized as a JSON string. -#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, TS)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, TS)] #[ts(type = "string")] pub struct ApiPathString(String); @@ -190,6 +192,31 @@ fn is_windows_separator_byte(character: u8) -> bool { matches!(character, b'\\' | b'/') } +impl TryFrom for ApiPathString { + type Error = ApiPathStringError; + + fn try_from(path: String) -> Result { + if is_absolute_api_path(&path) { + Ok(Self(path)) + } else { + Err(ApiPathStringError::RelativePath { path }) + } + } +} + +impl TryFrom for ApiPathString { + type Error = ApiPathStringError; + + fn try_from(path: PathBuf) -> Result { + let path = AbsolutePathBuf::from_absolute_path(&path).map_err(|_| { + ApiPathStringError::RelativePath { + path: path.to_string_lossy().into_owned(), + } + })?; + Self::from_abs_path(&path, PathConvention::native()) + } +} + fn render_opaque_fallback( path: &PathUri, path_bytes: &[u8], @@ -253,6 +280,28 @@ impl Serialize for ApiPathString { } } +impl<'de> Deserialize<'de> for ApiPathString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let path = String::deserialize(deserializer)?; + Self::try_from(path).map_err(serde::de::Error::custom) + } +} + +fn is_absolute_api_path(path: &str) -> bool { + if path.starts_with('/') { + return true; + } + let bytes = path.as_bytes(); + matches!( + bytes, + [drive, b':', separator, ..] + if drive.is_ascii_alphabetic() && matches!(separator, b'/' | b'\\') + ) || matches!(bytes, [b'\\', b'\\', _, ..]) +} + impl JsonSchema for ApiPathString { fn schema_name() -> String { "ApiPathString".to_string() @@ -351,6 +400,8 @@ fn incompatible_convention(path: &PathUri, convention: PathConvention) -> ApiPat #[derive(Debug, Error, PartialEq, Eq)] pub enum ApiPathStringError { + #[error("path `{path}` must be absolute")] + RelativePath { path: String }, #[error("opaque fallback path URI `{path}` cannot be recovered as a native path")] OpaqueFallback { path: String }, #[error("path URI `{path}` cannot be rendered using {convention} path syntax")] diff --git a/codex-rs/utils/path-uri/src/api_path_string_tests.rs b/codex-rs/utils/path-uri/src/api_path_string_tests.rs index c123568889..cae0e874b5 100644 --- a/codex-rs/utils/path-uri/src/api_path_string_tests.rs +++ b/codex-rs/utils/path-uri/src/api_path_string_tests.rs @@ -418,3 +418,16 @@ fn serializes_and_deserializes_as_a_string() { rendered ); } + +#[test] +fn deserializes_without_applying_host_path_rules() { + let rendered: ApiPathString = + serde_json::from_str(r#""C:\\workspace\\src""#).expect("path should deserialize"); + + assert_eq!(rendered.as_str(), r"C:\workspace\src"); +} + +#[test] +fn rejects_relative_paths_during_deserialization() { + assert!(serde_json::from_str::(r#""workspace/src""#).is_err()); +}