Merge remote-tracking branch 'origin/main' into etraut/goal-capacity-retry

This commit is contained in:
Eric Traut
2026-07-08 21:42:07 -07:00
311 changed files with 7573 additions and 2915 deletions
+3
View File
@@ -1,5 +1,8 @@
# Core crate ownership.
/codex-rs/arg0/ @openai/codex-core-agent-team
/codex-rs/codex-mcp/ @openai/codex-core-agent-team
/codex-rs/core/ @openai/codex-core-agent-team
/codex-rs/exec-server/ @openai/codex-core-agent-team
/codex-rs/exec-server-protocol/ @openai/codex-core-agent-team
/codex-rs/ext/extension-api/ @openai/codex-core-agent-team
/codex-rs/prompts/ @openai/codex-core-agent-team
+6 -20
View File
@@ -12,7 +12,8 @@ outputs:
runs:
using: composite
steps:
- uses: ./.github/actions/setup-ci
- id: setup_ci
uses: ./.github/actions/setup-ci
- name: Set up Bazel
uses: bazel-contrib/setup-bazel@c5acdfb288317d0b5c0bbd7a396a3dc868bb0f86 # 0.19.0
@@ -20,30 +21,15 @@ runs:
# and Windows can use the runner's standalone Bazel, ignoring .bazelversion.
with:
bazelisk-version: 1.28.1
# setup-bazel writes an explicit output_base, which otherwise overrides
# BAZEL_OUTPUT_USER_ROOT and leaves Bazel's I/O-heavy trees on C:.
output-base: ${{ steps.setup_ci.outputs.bazel-output-base }}
- name: Configure Bazel repository cache
id: configure_bazel_repository_cache
shell: pwsh
run: |
# Keep the repository cache under HOME on all runners. Windows `D:\a`
# cache paths match `.bazelrc`, but `actions/cache/restore` currently
# returns HTTP 400 for that path in the Windows clippy job.
$repositoryCachePath = Join-Path $HOME '.cache/bazel-repo-cache'
"repository-cache-path=$repositoryCachePath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"BAZEL_REPOSITORY_CACHE=$repositoryCachePath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Configure Bazel output root (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
# Use the shortest available drive to reduce argv/path length issues,
# but avoid the drive root because some Windows test launchers mis-handle
# MANIFEST paths there.
$hasDDrive = Test-Path 'D:\'
$bazelOutputUserRoot = if ($hasDDrive) { 'D:\b' } else { 'C:\b' }
$repoContentsCache = Join-Path $env:RUNNER_TEMP "bazel-repo-contents-cache-$env:GITHUB_RUN_ID-$env:GITHUB_JOB"
"BAZEL_OUTPUT_USER_ROOT=$bazelOutputUserRoot" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
"BAZEL_REPO_CONTENTS_CACHE=$repoContentsCache" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
"repository-cache-path=$env:BAZEL_REPOSITORY_CACHE" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
- name: Expose MSVC SDK environment (Windows)
if: runner.os == 'Windows'
+56 -4
View File
@@ -1,14 +1,66 @@
name: setup-ci
description: Prepare common tools and environment shared by CI jobs.
outputs:
bazel-output-base:
description: Filesystem path used for Bazel's output base.
value: ${{ steps.configure_ci_build_paths.outputs.bazel-output-base }}
cargo-target-dir:
description: Filesystem path used for Cargo's target directory.
value: ${{ steps.configure_ci_build_paths.outputs.cargo-target-dir }}
runs:
using: composite
steps:
# TODO(anp): Move this under CI_BUILD_ROOT once all consumers use the
# shared build-path contract.
- name: Configure Cargo target directory
# setup-ci expects either this step or the Unix fallback below to define
# CI_BUILD_ROOT. Windows puts it on a Dev Drive because Cargo and Bazel
# spend significant time reading and writing build/cache trees.
- name: Configure Dev Drive (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: ./.github/scripts/setup-dev-drive.ps1
- name: Configure CI build root (Unix)
if: runner.os != 'Windows'
shell: bash
run: echo "CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-$GITHUB_WORKSPACE/codex-rs/target}" >> "$GITHUB_ENV"
run: echo "CI_BUILD_ROOT=$HOME/.cache/codex-ci" >> "$GITHUB_ENV"
- name: Configure CI build paths
id: configure_ci_build_paths
shell: bash
run: |
set -euo pipefail
# setup-bazel passes output_base explicitly, so keep both it and the
# user root under the shared build root. Keep these directory names tiny
# on every platform so Windows Bazel paths do not overflow argv or
# confuse test MANIFEST handling.
bazel_output_base="$CI_BUILD_ROOT/o"
bazel_output_user_root="$CI_BUILD_ROOT/b"
bazel_repository_cache="$CI_BUILD_ROOT/bazel-repository-cache"
bazel_repo_contents_cache="$CI_BUILD_ROOT/bazel-repo-contents-cache-$GITHUB_RUN_ID-$GITHUB_JOB"
cargo_target_dir="$CI_BUILD_ROOT/cargo-target"
tmp="$CI_BUILD_ROOT/tmp"
build_dirs=(
"$bazel_output_base"
"$bazel_output_user_root"
"$bazel_repository_cache"
"$bazel_repo_contents_cache"
"$cargo_target_dir"
"$tmp"
)
mkdir -p "${build_dirs[@]}"
echo "bazel-output-base=$bazel_output_base" >> "$GITHUB_OUTPUT"
echo "cargo-target-dir=$cargo_target_dir" >> "$GITHUB_OUTPUT"
{
echo "BAZEL_OUTPUT_BASE=$bazel_output_base"
echo "BAZEL_OUTPUT_USER_ROOT=$bazel_output_user_root"
echo "BAZEL_REPOSITORY_CACHE=$bazel_repository_cache"
echo "BAZEL_REPO_CONTENTS_CACHE=$bazel_repo_contents_cache"
echo "CARGO_TARGET_DIR=$cargo_target_dir"
echo "TEMP=$tmp"
echo "TMP=$tmp"
} >> "$GITHUB_ENV"
- name: Prefer the Git CLI for Cargo git dependencies
shell: bash
+44 -15
View File
@@ -131,25 +131,54 @@ def bazel_args_without_remote_execution(args: Sequence[str]) -> list[str]:
def bazel_args_with_remote_config(
args: Sequence[str], env: Mapping[str, str]
) -> list[str]:
command_idx = next(
(idx for idx, arg in enumerate(args) if not arg.startswith("-")),
None,
)
if command_idx is None:
raise ValueError("expected a Bazel command")
config = remote_config(args, env)
if config is None:
return bazel_args_without_remote_execution(args)
configured_args = bazel_args_without_remote_execution(args)
else:
# `remote_config()` returns a configuration only when this key is present.
api_key = env["BUILDBUDDY_API_KEY"]
remote_args = [
f"--config={config}",
f"--remote_header=x-buildbuddy-api-key={api_key}",
]
# `remote_config()` returns a configuration only when this key is present.
api_key = env["BUILDBUDDY_API_KEY"]
remote_args = [
f"--config={config}",
f"--remote_header=x-buildbuddy-api-key={api_key}",
# Insert immediately after the Bazel command. This keeps wrapper-added
# options out of positional payloads and lets later CI configs override
# shared RBE defaults such as the Windows cross-compilation exec platforms.
configured_args = [
*args[: command_idx + 1],
*remote_args,
*args[command_idx + 1 :],
]
try:
separator_idx = configured_args.index("--")
except ValueError:
separator_idx = len(configured_args)
cache_args = [
f"{option_prefix}{env[env_name]}"
for env_name, option_prefix in (
("BAZEL_REPO_CONTENTS_CACHE", "--repo_contents_cache="),
("BAZEL_REPOSITORY_CACHE", "--repository_cache="),
)
if env.get(env_name)
and not any(
arg.startswith(option_prefix) for arg in configured_args[:separator_idx]
)
]
return [
*configured_args[:separator_idx],
*cache_args,
*configured_args[separator_idx:],
]
# Insert immediately after the Bazel command. This keeps wrapper-added
# options out of positional payloads and lets later CI configs override
# shared RBE defaults such as the Windows cross-compilation exec platforms.
insertion_idx = next(
(idx + 1 for idx, arg in enumerate(args) if not arg.startswith("-")),
len(args),
)
return [*args[:insertion_idx], *remote_args, *args[insertion_idx:]]
def bazel_command(*args: str, env: Mapping[str, str] | None = None) -> list[str]:
+19 -18
View File
@@ -1,14 +1,15 @@
# Configure a fast drive for Windows CI jobs.
#
# GitHub-hosted Windows runners do not always expose a secondary D: volume. When
# they do not, try to create a Dev Drive VHD and fall back to C: if the runner
# image does not allow that provisioning path.
# they do not, create a Dev Drive VHD. CI depends on this path for its
# build directories where CI spends significant time doing I/O, so fail the
# job if no real Dev Drive is available.
function Use-FallbackDrive {
param([string]$Reason)
function Test-DevDrive {
param([string]$Drive)
Write-Warning "$Reason Falling back to C:"
return "C:"
& fsutil devdrv query $Drive *> $null
return $LASTEXITCODE -eq 0
}
function Invoke-BestEffort {
@@ -21,10 +22,14 @@ function Invoke-BestEffort {
}
}
if (Test-Path "D:\") {
Write-Output "Using existing drive at D:"
if ((Test-Path "D:\") -and (Test-DevDrive "D:")) {
Write-Output "Using existing Dev Drive at D:"
$Drive = "D:"
} else {
if (Test-Path "D:\") {
Write-Output "Existing D: volume is not a Dev Drive; provisioning a new Dev Drive VHD."
}
try {
$VhdPath = Join-Path $env:RUNNER_TEMP "codex-dev-drive.vhdx"
$SizeBytes = 64GB
@@ -42,21 +47,17 @@ if (Test-Path "D:\") {
$Drive = "$($Volume.DriveLetter):"
if (-not (Test-DevDrive $Drive)) {
throw "Provisioned volume at $Drive did not pass Dev Drive verification."
}
Invoke-BestEffort { fsutil devdrv trust $Drive } "Trusting Dev Drive $Drive"
Invoke-BestEffort { fsutil devdrv enable /disallowAv } "Disabling AV filter attachment for Dev Drives"
Invoke-BestEffort { fsutil devdrv query $Drive } "Querying Dev Drive $Drive"
Write-Output "Using Dev Drive at $Drive"
} catch {
$Drive = Use-FallbackDrive "Failed to create Dev Drive: $($_.Exception.Message)"
throw "Failed to create Dev Drive: $($_.Exception.Message)"
}
}
$Tmp = "$Drive\codex-tmp"
New-Item -Path $Tmp -ItemType Directory -Force | Out-Null
@(
"DEV_DRIVE=$Drive"
"TMP=$Tmp"
"TEMP=$Tmp"
) | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
"CI_BUILD_ROOT=$Drive" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
@@ -214,6 +214,48 @@ class RunBazelWithBuildBuddyTest(unittest.TestCase):
],
)
def test_bazel_command_uses_configured_local_caches(self) -> None:
env = {
"BAZEL_REPO_CONTENTS_CACHE": "/tmp/bazel-repo-contents",
"BAZEL_REPOSITORY_CACHE": "/tmp/bazel-repository",
}
self.assertEqual(
run_bazel_with_buildbuddy.bazel_command(
"build",
"--config=local",
"//codex-rs/...",
env=env,
),
[
"bazel",
"build",
"--config=local",
"//codex-rs/...",
"--repo_contents_cache=/tmp/bazel-repo-contents",
"--repository_cache=/tmp/bazel-repository",
],
)
def test_bazel_command_adds_local_caches_before_separator(self) -> None:
self.assertEqual(
run_bazel_with_buildbuddy.bazel_command(
"build",
"//codex-rs/...",
"--",
"--program-arg",
env={"BAZEL_REPOSITORY_CACHE": "/tmp/bazel-repository"},
),
[
"bazel",
"build",
"//codex-rs/...",
"--repository_cache=/tmp/bazel-repository",
"--",
"--program-arg",
],
)
def test_main_preserves_spaced_argument_and_child_exit_status(self) -> None:
spaced_arg = (
r"--test_env=PATH=C:\Program Files\PowerShell\7;C:\Program Files\Git\bin"
+11 -7
View File
@@ -47,13 +47,17 @@ version = "149.2.0"
)
)
def test_setup_ci_change_requires_canary_and_source_build(self) -> None:
changed_files = {".github/actions/setup-ci/action.yml"}
self.assertTrue(canary_required(changed_files, "149.2.0", "149.2.0"))
self.assertTrue(
windows_source_required(changed_files, "149.2.0", "149.2.0")
)
def test_shared_ci_setup_changes_require_canary_and_source_build(self) -> None:
for path in (
".github/actions/setup-ci/action.yml",
".github/scripts/setup-dev-drive.ps1",
):
with self.subTest(path=path):
changed_files = {path}
self.assertTrue(canary_required(changed_files, "149.2.0", "149.2.0"))
self.assertTrue(
windows_source_required(changed_files, "149.2.0", "149.2.0")
)
def test_manual_dispatch_requires_source_build(self) -> None:
self.assertTrue(
+2
View File
@@ -25,6 +25,7 @@ CANARY_PATH_PATTERNS = {
".github/scripts/run_bazel_with_buildbuddy.py",
".github/scripts/rusty_v8_bazel.py",
".github/scripts/rusty_v8_module_bazel.py",
".github/scripts/setup-dev-drive.ps1",
".github/scripts/v8_canary_changes.py",
".github/workflows/postmerge-ci.yml",
".github/workflows/rusty-v8-release.yml",
@@ -44,6 +45,7 @@ WINDOWS_SOURCE_BUILD_PATHS = {
".github/actions/setup-ci/**",
".github/scripts/rusty_v8_bazel.py",
".github/scripts/rusty_v8_module_bazel.py",
".github/scripts/setup-dev-drive.ps1",
".github/scripts/v8_canary_changes.py",
".github/workflows/rusty-v8-release.yml",
".github/workflows/v8-canary.yml",
@@ -71,11 +71,6 @@ jobs:
with:
persist-credentials: false
- name: Configure Dev Drive (Windows)
if: ${{ runner.os == 'Windows' }}
shell: pwsh
run: ../.github/scripts/setup-dev-drive.ps1
- uses: ./.github/actions/setup-ci
- name: Install Linux build dependencies
@@ -136,11 +131,7 @@ jobs:
echo "Using sccache GitHub backend"
else
echo "SCCACHE_GHA_ENABLED=false" >> "$GITHUB_ENV"
if [[ -n "${DEV_DRIVE:-}" ]]; then
echo "SCCACHE_DIR=${DEV_DRIVE}\\.sccache" >> "$GITHUB_ENV"
else
echo "SCCACHE_DIR=${{ github.workspace }}/.sccache" >> "$GITHUB_ENV"
fi
echo "SCCACHE_DIR=${CI_BUILD_ROOT}/sccache" >> "$GITHUB_ENV"
echo "Using sccache local disk + actions/cache fallback"
fi
+1 -2
View File
@@ -160,8 +160,7 @@ jobs:
continue-on-error: true
uses: actions/cache/save@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
with:
path: |
~/.cache/bazel-repo-cache
path: ${{ steps.setup_bazel.outputs.repository-cache-path }}
key: bazel-cache-x86_64-unknown-linux-gnu-${{ hashFiles('MODULE.bazel', 'codex-rs/Cargo.lock', 'codex-rs/Cargo.toml') }}
- name: Check for a clean worktree
+5 -6
View File
@@ -308,8 +308,6 @@ jobs:
runs-on: ${{ matrix.runner }}
permissions:
contents: read
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/upstream-rusty-v8/target
strategy:
fail-fast: false
matrix:
@@ -322,7 +320,8 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- uses: ./.github/actions/setup-ci
- id: setup_ci
uses: ./.github/actions/setup-ci
- name: Configure git for upstream checkout
shell: bash
@@ -366,8 +365,8 @@ jobs:
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5
with:
path: |
${{ env.CARGO_TARGET_DIR }}/sccache
${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release/gn_out
${{ steps.setup_ci.outputs.cargo-target-dir }}/sccache
${{ steps.setup_ci.outputs.cargo-target-dir }}/${{ matrix.target }}/release/gn_out
key: rusty-v8-source-${{ matrix.target }}-${{ matrix.runner }}-sandbox-${{ hashFiles('upstream-rusty-v8/Cargo.lock', 'upstream-rusty-v8/build.rs', 'upstream-rusty-v8/git_submodule_status.txt') }}
restore-keys: |
rusty-v8-source-${{ matrix.target }}-${{ matrix.runner }}-sandbox-
@@ -376,7 +375,7 @@ jobs:
shell: pwsh
env:
SCCACHE_CACHE_SIZE: 256M
SCCACHE_DIR: ${{ env.CARGO_TARGET_DIR }}/sccache
SCCACHE_DIR: ${{ steps.setup_ci.outputs.cargo-target-dir }}/sccache
SCCACHE_IDLE_TIMEOUT: 0
run: |
$version = "v0.8.2"
+1 -1
View File
@@ -253,7 +253,7 @@ Use `just bench-smoke` to dry-run the benchmark for a single iteration to ensure
- Tests should exercise app-server's public JSON-RPC API.
- Use similar server mocking as for core integration tests.
- Use `TestAppServer::new_with_auto_env()` and `TestAppServer::send_thread_start_request_with_auto_env()`
- Use `TestAppServer::builder().build()` and `TestAppServer::send_thread_start_request_with_auto_env()`
by default to ensure that new tests work with foreign app/exec OSes. See `$remote-tests` for
details.
+50 -5
View File
@@ -11,6 +11,7 @@ import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const codexPackageRoot = realpathSync(path.join(__dirname, ".."));
const PLATFORM_PACKAGE_BY_TARGET = {
"x86_64-unknown-linux-musl": "@openai/codex-linux-x64",
@@ -98,7 +99,9 @@ function findCodexExecutable() {
const updateCommand =
packageManager === "bun"
? "bun install -g @openai/codex@latest"
: "npm install -g @openai/codex@latest";
: packageManager === "pnpm"
? "pnpm add -g @openai/codex@latest"
: "npm install -g @openai/codex@latest";
throw new Error(
`Missing optional dependency ${platformPackage}. Reinstall Codex: ${updateCommand}`,
);
@@ -112,11 +115,47 @@ const binaryPath = findCodexExecutable();
// and guarantees that when either the child terminates or the parent
// receives a fatal signal, both processes exit in a predictable manner.
function isPnpmOwnedCodexInstall(nodeModulesDir) {
if (!existsSync(path.join(nodeModulesDir, ".modules.yaml"))) {
return false;
}
try {
return (
realpathSync(path.join(nodeModulesDir, "@openai", "codex")) ===
codexPackageRoot
);
} catch {
return false;
}
}
/**
* Use heuristics to detect the package manager that was used to install Codex
* in order to give the user a hint about how to update it.
*/
function detectPackageManager() {
// pnpm's owning node_modules directory can be several parents above the
// package in isolated global layouts. Search ancestors of both the canonical
// package root and lexical entrypoint because pnpm may link either path.
const entrypointDir = path.dirname(path.resolve(process.argv[1]));
for (const startDir of new Set([codexPackageRoot, entrypointDir])) {
const filesystemRoot = path.parse(startDir).root;
for (
let currentDir = startDir;
currentDir !== filesystemRoot;
currentDir = path.dirname(currentDir)
) {
if (isPnpmOwnedCodexInstall(path.join(currentDir, "node_modules"))) {
return "pnpm";
}
}
if (isPnpmOwnedCodexInstall(path.join(filesystemRoot, "node_modules"))) {
return "pnpm";
}
}
const userAgent = process.env.npm_config_user_agent || "";
if (/\bbun\//.test(userAgent)) {
return "bun";
@@ -137,15 +176,21 @@ function detectPackageManager() {
return userAgent ? "npm" : null;
}
const packageManager = detectPackageManager();
const packageManagerEnvVar =
detectPackageManager() === "bun"
packageManager === "bun"
? "CODEX_MANAGED_BY_BUN"
: "CODEX_MANAGED_BY_NPM";
: packageManager === "pnpm"
? "CODEX_MANAGED_BY_PNPM"
: "CODEX_MANAGED_BY_NPM";
const env = {
...process.env,
[packageManagerEnvVar]: "1",
CODEX_MANAGED_PACKAGE_ROOT: realpathSync(path.join(__dirname, "..")),
CODEX_MANAGED_PACKAGE_ROOT: codexPackageRoot,
};
delete env.CODEX_MANAGED_BY_NPM;
delete env.CODEX_MANAGED_BY_BUN;
delete env.CODEX_MANAGED_BY_PNPM;
env[packageManagerEnvVar] = "1";
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: "inherit",
-26
View File
@@ -1,26 +0,0 @@
name: Cargo audit
on:
pull_request:
push:
branches:
- main
permissions:
contents: read
jobs:
audit:
runs-on: ubuntu-latest
defaults:
run:
working-directory: codex-rs
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0
- name: Install cargo-audit
uses: taiki-e/install-action@v2
with:
tool: cargo-audit
- name: Run cargo audit
run: cargo audit --deny warnings
+26
View File
@@ -409,11 +409,14 @@ dependencies = [
"codex-protocol",
"codex-utils-cargo-bin",
"core_test_support",
"pretty_assertions",
"serde",
"serde_json",
"shlex",
"tempfile",
"tokio",
"tokio-util",
"url",
"uuid",
"wiremock",
]
@@ -1940,6 +1943,7 @@ dependencies = [
"codex-http-client",
"codex-protocol",
"codex-utils-rustls-provider",
"codex-websocket-client",
"eventsource-stream",
"futures",
"http 1.4.0",
@@ -1994,6 +1998,7 @@ dependencies = [
"codex-guardian",
"codex-home",
"codex-hooks",
"codex-http-client",
"codex-image-generation-extension",
"codex-login",
"codex-mcp",
@@ -2755,6 +2760,7 @@ dependencies = [
"codex-extension-api",
"codex-features",
"codex-home",
"codex-image-generation-extension",
"codex-login",
"codex-model-provider-info",
"codex-models-manager",
@@ -2805,6 +2811,7 @@ dependencies = [
"tracing-subscriber",
"tracing-test",
"url",
"which 8.0.0",
"wiremock",
"zip 2.4.2",
]
@@ -3438,6 +3445,7 @@ dependencies = [
"codex-exec-server",
"codex-extension-api",
"codex-home",
"codex-image-generation-extension",
"codex-login",
"codex-protocol",
"codex-shell-command",
@@ -3587,6 +3595,7 @@ version = "0.0.0"
dependencies = [
"chrono",
"codex-collaboration-mode-templates",
"codex-http-client",
"codex-login",
"codex-otel",
"codex-protocol",
@@ -4472,6 +4481,7 @@ dependencies = [
"codex-api",
"codex-core",
"codex-extension-api",
"codex-extension-items",
"codex-login",
"codex-model-provider",
"codex-model-provider-info",
@@ -4484,6 +4494,22 @@ dependencies = [
"url",
]
[[package]]
name = "codex-websocket-client"
version = "0.0.0"
dependencies = [
"codex-http-client",
"codex-utils-rustls-provider",
"futures",
"pretty_assertions",
"rcgen",
"rustls",
"tokio",
"tokio-rustls",
"tokio-tungstenite",
"url",
]
[[package]]
name = "codex-windows-sandbox"
version = "0.0.0"
+3
View File
@@ -90,6 +90,7 @@ members = [
"tui",
"tools",
"v8-poc",
"websocket-client",
"utils/absolute-path",
"utils/path-uri",
"utils/cargo-bin",
@@ -167,6 +168,7 @@ codex-code-mode = { path = "code-mode" }
codex-code-mode-protocol = { path = "code-mode-protocol" }
codex-home = { path = "codex-home" }
codex-http-client = { path = "http-client" }
codex-websocket-client = { path = "websocket-client" }
codex-config = { path = "config" }
codex-connectors = { path = "connectors" }
codex-connectors-extension = { path = "ext/connectors" }
@@ -427,6 +429,7 @@ thiserror = "2.0.17"
time = "0.3.47"
tiny_http = "0.12"
tokio = "1"
tokio-rustls = "0.26.4"
tokio-stream = "0.1.18"
tokio-test = "0.4"
tokio-tungstenite = { version = "0.28.0", features = [
@@ -140,6 +140,7 @@ use codex_app_server_protocol::TurnStatus as AppServerTurnStatus;
use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::TurnSteerResponse;
use codex_app_server_protocol::UserInput;
use codex_app_server_protocol::WebSearchItem;
use codex_login::default_client::DEFAULT_ORIGINATOR;
use codex_login::default_client::originator;
use codex_plugin::AppConnectorId;
@@ -4401,11 +4402,11 @@ async fn turn_event_counts_completed_tool_items() {
agent_thread_id: "thread-child".to_string(),
agent_path: "/root/child".to_string(),
},
ThreadItem::WebSearch {
ThreadItem::WebSearch(WebSearchItem {
id: "web-1".to_string(),
query: "codex".to_string(),
action: None,
},
}),
ThreadItem::ImageGeneration(ImageGenerationItem {
id: "image-1".to_string(),
status: "completed".to_string(),
+8 -8
View File
@@ -402,7 +402,7 @@ impl TurnToolCounts {
ThreadItem::CollabAgentToolCall { .. } | ThreadItem::SubAgentActivity { .. } => {
self.subagent_tool_call += 1;
}
ThreadItem::WebSearch { .. } => self.web_search += 1,
ThreadItem::WebSearch(_) => self.web_search += 1,
ThreadItem::ImageGeneration(_) => self.image_generation += 1,
ThreadItem::UserMessage { .. }
| ThreadItem::HookPrompt { .. }
@@ -1732,8 +1732,8 @@ fn tracked_tool_item_id(item: &ThreadItem) -> Option<&str> {
| ThreadItem::FileChange { id, .. }
| ThreadItem::McpToolCall { id, .. }
| ThreadItem::DynamicToolCall { id, .. }
| ThreadItem::CollabAgentToolCall { id, .. }
| ThreadItem::WebSearch { id, .. } => Some(id),
| ThreadItem::CollabAgentToolCall { id, .. } => Some(id),
ThreadItem::WebSearch(item) => Some(&item.id),
ThreadItem::ImageGeneration(item) => Some(&item.id),
ThreadItem::UserMessage { .. }
| ThreadItem::HookPrompt { .. }
@@ -2027,11 +2027,11 @@ fn tool_item_event(input: ToolItemEventInput<'_>) -> Option<TrackEventRequest> {
},
))
}
ThreadItem::WebSearch { id, query, action } => {
ThreadItem::WebSearch(item) => {
let base = tool_item_base(
thread_id,
turn_id,
id.clone(),
item.id.clone(),
"web_search".to_string(),
ToolItemOutcome {
terminal_status: ToolItemTerminalStatus::Completed,
@@ -2051,9 +2051,9 @@ fn tool_item_event(input: ToolItemEventInput<'_>) -> Option<TrackEventRequest> {
event_type: "codex_web_search_event",
event_params: CodexWebSearchEventParams {
base,
web_search_action: action.as_ref().map(web_search_action_kind),
query_present: !query.trim().is_empty(),
query_count: web_search_query_count(query, action.as_ref()),
web_search_action: item.action.as_ref().map(web_search_action_kind),
query_present: !item.query.trim().is_empty(),
query_count: web_search_query_count(&item.query, item.action.as_ref()),
},
}))
}
@@ -0,0 +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 { WebSearchAction } from "./v2/WebSearchAction";
export type WebSearchItem = { id: string, query: string, action: WebSearchAction | null, };
+1
View File
@@ -82,6 +82,7 @@ export type { Tool } from "./Tool";
export type { Verbosity } from "./Verbosity";
export type { WebSearchAction } from "./WebSearchAction";
export type { WebSearchContextSize } from "./WebSearchContextSize";
export type { WebSearchItem } from "./WebSearchItem";
export type { WebSearchLocation } from "./WebSearchLocation";
export type { WebSearchMode } from "./WebSearchMode";
export type { WebSearchToolConfig } from "./WebSearchToolConfig";
@@ -5,6 +5,7 @@ import type { ImageGenerationItem } from "../ImageGenerationItem";
import type { LegacyAppPathString } from "../LegacyAppPathString";
import type { MessagePhase } from "../MessagePhase";
import type { ReasoningEffort } from "../ReasoningEffort";
import type { WebSearchItem } from "../WebSearchItem";
import type { JsonValue } from "../serde_json/JsonValue";
import type { CollabAgentState } from "./CollabAgentState";
import type { CollabAgentTool } from "./CollabAgentTool";
@@ -24,7 +25,6 @@ import type { MemoryCitation } from "./MemoryCitation";
import type { PatchApplyStatus } from "./PatchApplyStatus";
import type { SubAgentActivityKind } from "./SubAgentActivityKind";
import type { UserInput } from "./UserInput";
import type { WebSearchAction } from "./WebSearchAction";
export type ThreadItem = { "type": "userMessage", id: string, clientId: string | null, content: Array<UserInput>, } | { "type": "hookPrompt", id: string, fragments: Array<HookPromptFragment>, } | { "type": "agentMessage", id: string, text: string, phase: MessagePhase | null, memoryCitation: MemoryCitation | null, } | { "type": "plan", id: string, text: string, } | { "type": "reasoning", id: string, summary: Array<string>, content: Array<string>, } | { "type": "commandExecution", id: string,
/**
@@ -105,4 +105,4 @@ reasoningEffort: ReasoningEffort | null,
/**
* Last known status of the target agents, when available.
*/
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch", id: string, query: string, action: WebSearchAction | null, } | { "type": "imageView", id: string, path: LegacyAppPathString, } | { "type": "sleep", id: string, durationMs: number, } | { "type": "imageGeneration" } & ImageGenerationItem | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch" } & WebSearchItem | { "type": "imageView", id: string, path: LegacyAppPathString, } | { "type": "sleep", id: string, durationMs: number, } | { "type": "imageGeneration" } & ImageGenerationItem | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
@@ -33,6 +33,9 @@ use codex_protocol::protocol::GuardianAssessmentAction;
use codex_protocol::protocol::GuardianAssessmentEvent;
use codex_protocol::protocol::PatchApplyBeginEvent;
use codex_protocol::protocol::PatchApplyEndEvent;
use codex_protocol::protocol::ReviewOutputEvent;
use codex_protocol::review_format::REVIEW_FALLBACK_MESSAGE;
use codex_protocol::review_format::render_review_output_text;
use codex_shell_command::parse_command::parse_command;
use codex_shell_command::parse_command::shlex_join;
use codex_utils_path_uri::PathConvention;
@@ -41,6 +44,12 @@ use std::collections::HashMap;
use std::path::PathBuf;
use tracing::warn;
pub(crate) fn review_output_text(output: Option<&ReviewOutputEvent>) -> String {
output
.map(render_review_output_text)
.unwrap_or_else(|| REVIEW_FALLBACK_MESSAGE.to_string())
}
pub fn build_file_change_approval_request_item(
payload: &ApplyPatchApprovalRequestEvent,
) -> ThreadItem {
@@ -4,6 +4,7 @@ use crate::protocol::item_builders::build_file_change_approval_request_item;
use crate::protocol::item_builders::build_file_change_begin_item;
use crate::protocol::item_builders::build_file_change_end_item;
use crate::protocol::item_builders::build_item_from_guardian_event;
use crate::protocol::item_builders::review_output_text;
use crate::protocol::v2::CollabAgentState;
use crate::protocol::v2::CollabAgentTool;
use crate::protocol::v2::CollabAgentToolCallStatus;
@@ -21,7 +22,10 @@ use crate::protocol::v2::TurnError;
use crate::protocol::v2::TurnItemsView;
use crate::protocol::v2::TurnStatus;
use crate::protocol::v2::UserInput;
#[cfg(test)]
use crate::protocol::v2::WebSearchAction;
use crate::protocol::v2::WebSearchItem;
use crate::protocol::v2::web_search_action_from_core;
use codex_extension_items::image_generation::ImageGenerationItem;
use codex_protocol::items::parse_hook_prompt_message;
use codex_protocol::models::MessagePhase;
@@ -46,7 +50,6 @@ use codex_protocol::protocol::McpToolCallBeginEvent;
use codex_protocol::protocol::McpToolCallEndEvent;
use codex_protocol::protocol::PatchApplyBeginEvent;
use codex_protocol::protocol::PatchApplyEndEvent;
use codex_protocol::protocol::ReviewOutputEvent;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::TurnAbortedEvent;
@@ -56,6 +59,8 @@ use codex_protocol::protocol::UserMessageEvent;
use codex_protocol::protocol::ViewImageToolCallEvent;
use codex_protocol::protocol::WebSearchBeginEvent;
use codex_protocol::protocol::WebSearchEndEvent;
#[cfg(test)]
use codex_protocol::review_format::REVIEW_FALLBACK_MESSAGE;
use std::collections::HashMap;
use tracing::warn;
use uuid::Uuid;
@@ -587,16 +592,23 @@ impl ThreadHistoryBuilder {
turn_id: &str,
item: &codex_protocol::items::TurnItem,
) {
let is_review_mode_item = matches!(
item,
codex_protocol::items::TurnItem::EnteredReviewMode(_)
| codex_protocol::items::TurnItem::ExitedReviewMode(_)
);
let should_upsert = match item {
codex_protocol::items::TurnItem::Plan(plan) => !plan.text.is_empty(),
codex_protocol::items::TurnItem::Sleep(_)
| codex_protocol::items::TurnItem::HookPrompt(_)
| codex_protocol::items::TurnItem::CommandExecution(_)
| codex_protocol::items::TurnItem::DynamicToolCall(_)
| codex_protocol::items::TurnItem::CollabAgentToolCall(_)
| codex_protocol::items::TurnItem::SubAgentActivity(_)
| codex_protocol::items::TurnItem::Extension(_) => true,
| codex_protocol::items::TurnItem::Extension(_)
| codex_protocol::items::TurnItem::EnteredReviewMode(_)
| codex_protocol::items::TurnItem::ExitedReviewMode(_) => true,
codex_protocol::items::TurnItem::UserMessage(_)
| codex_protocol::items::TurnItem::HookPrompt(_)
| codex_protocol::items::TurnItem::AgentMessage(_)
| codex_protocol::items::TurnItem::Reasoning(_)
| codex_protocol::items::TurnItem::WebSearch(_)
@@ -608,25 +620,30 @@ impl ThreadHistoryBuilder {
};
if should_upsert {
self.upsert_item_in_turn_id(turn_id, ThreadItem::from(item.clone()));
let item = ThreadItem::from(item.clone());
if is_review_mode_item {
self.upsert_review_mode_item(Some(turn_id), item);
} else {
self.upsert_item_in_turn_id(turn_id, item);
}
}
}
fn handle_web_search_begin(&mut self, payload: &WebSearchBeginEvent) {
let item = ThreadItem::WebSearch {
let item = ThreadItem::WebSearch(WebSearchItem {
id: payload.call_id.clone(),
query: String::new(),
action: None,
};
});
self.upsert_item_in_current_turn(item);
}
fn handle_web_search_end(&mut self, payload: &WebSearchEndEvent) {
let item = ThreadItem::WebSearch {
let item = ThreadItem::WebSearch(WebSearchItem {
id: payload.call_id.clone(),
query: payload.query.clone(),
action: Some(WebSearchAction::from(payload.action.clone())),
};
action: Some(web_search_action_from_core(payload.action.clone())),
});
self.upsert_item_in_current_turn(item);
}
@@ -1105,26 +1122,55 @@ impl ThreadHistoryBuilder {
self.push_item_in_current_turn(ThreadItem::ContextCompaction { id });
}
fn handle_entered_review_mode(&mut self, payload: &codex_protocol::protocol::ReviewRequest) {
fn handle_entered_review_mode(
&mut self,
payload: &codex_protocol::protocol::EnteredReviewModeEvent,
) {
let review = payload
.user_facing_hint
.clone()
.unwrap_or_else(|| "Review requested.".to_string());
let id = self.next_item_id();
self.push_item_in_current_turn(ThreadItem::EnteredReviewMode { id, review });
let id = payload
.item_id
.clone()
.unwrap_or_else(|| self.next_item_id());
self.upsert_review_mode_item(
payload.turn_id.as_deref(),
ThreadItem::EnteredReviewMode { id, review },
);
}
fn handle_exited_review_mode(
&mut self,
payload: &codex_protocol::protocol::ExitedReviewModeEvent,
) {
let review = payload
.review_output
let review = review_output_text(payload.review_output.as_ref());
let id = payload
.item_id
.clone()
.unwrap_or_else(|| self.next_item_id());
self.upsert_review_mode_item(
payload.turn_id.as_deref(),
ThreadItem::ExitedReviewMode { id, review },
);
}
fn upsert_review_mode_item(&mut self, turn_id: Option<&str>, item: ThreadItem) {
let Some(turn_id) = turn_id else {
self.upsert_item_in_current_turn(item);
return;
};
let current_turn_matches = self
.current_turn
.as_ref()
.map(render_review_output_text)
.unwrap_or_else(|| REVIEW_FALLBACK_MESSAGE.to_string());
let id = self.next_item_id();
self.push_item_in_current_turn(ThreadItem::ExitedReviewMode { id, review });
.is_some_and(|turn| turn.id == turn_id);
if !current_turn_matches && !self.turns.iter().any(|turn| turn.id == turn_id) {
self.finish_current_turn();
let turn = self.new_turn(Some(turn_id.to_string()));
self.record_changed_pending_turn(&turn);
self.current_turn = Some(turn);
}
self.upsert_item_in_turn_id(turn_id, item);
}
fn handle_error(&mut self, payload: &ErrorEvent) {
@@ -1440,17 +1486,6 @@ impl ThreadHistoryBuilder {
}
}
const REVIEW_FALLBACK_MESSAGE: &str = "Reviewer failed to output a response.";
fn render_review_output_text(output: &ReviewOutputEvent) -> String {
let explanation = output.overall_explanation.trim();
if explanation.is_empty() {
REVIEW_FALLBACK_MESSAGE.to_string()
} else {
explanation.to_string()
}
}
fn convert_dynamic_tool_content_items(
items: &[codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem],
) -> Vec<DynamicToolCallOutputContentItem> {
@@ -1555,6 +1590,8 @@ mod tests {
use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem;
use codex_protocol::items::CommandExecutionItem as CoreCommandExecutionItem;
use codex_protocol::items::CommandExecutionStatus as CoreCommandExecutionStatus;
use codex_protocol::items::EnteredReviewModeItem as CoreEnteredReviewModeItem;
use codex_protocol::items::ExitedReviewModeItem as CoreExitedReviewModeItem;
use codex_protocol::items::HookPromptFragment as CoreHookPromptFragment;
use codex_protocol::items::SleepItem as CoreSleepItem;
use codex_protocol::items::TurnItem as CoreTurnItem;
@@ -1572,12 +1609,15 @@ mod tests {
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::CompactedItem;
use codex_protocol::protocol::DynamicToolCallResponseEvent;
use codex_protocol::protocol::EnteredReviewModeEvent;
use codex_protocol::protocol::ExecCommandEndEvent;
use codex_protocol::protocol::ExecCommandSource;
use codex_protocol::protocol::ExitedReviewModeEvent;
use codex_protocol::protocol::ItemStartedEvent;
use codex_protocol::protocol::McpInvocation;
use codex_protocol::protocol::McpToolCallEndEvent;
use codex_protocol::protocol::PatchApplyBeginEvent;
use codex_protocol::protocol::ReviewTarget;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
@@ -1702,6 +1742,111 @@ mod tests {
);
}
#[test]
fn review_mode_events_replay_persisted_ids() {
let events = vec![
EventMsg::EnteredReviewMode(EnteredReviewModeEvent {
target: ReviewTarget::Custom {
instructions: "review this".into(),
},
user_facing_hint: Some("Review requested.".into()),
turn_id: Some("turn-1".into()),
item_id: Some("entered-review".into()),
}),
EventMsg::ExitedReviewMode(ExitedReviewModeEvent {
turn_id: Some("turn-1".into()),
item_id: Some("exited-review".into()),
review_output: None,
}),
EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "turn-1".into(),
last_agent_message: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
}),
];
let mut builder = ThreadHistoryBuilder::new();
for event in &events {
builder.handle_event(event);
}
let turns = builder.finish();
assert_eq!(turns[0].id, "turn-1");
assert_eq!(
turns[0].items,
vec![
ThreadItem::EnteredReviewMode {
id: "entered-review".into(),
review: "Review requested.".into(),
},
ThreadItem::ExitedReviewMode {
id: "exited-review".into(),
review: REVIEW_FALLBACK_MESSAGE.into(),
},
]
);
}
#[test]
fn review_mode_items_replay_without_turn_started() {
let thread_id = ThreadId::new();
let entered = CoreTurnItem::EnteredReviewMode(CoreEnteredReviewModeItem {
id: "entered-review".into(),
target: ReviewTarget::Custom {
instructions: "review this".into(),
},
user_facing_hint: "Review requested.".into(),
});
let exited = CoreTurnItem::ExitedReviewMode(CoreExitedReviewModeItem {
id: "exited-review".into(),
review_output: None,
});
let events = vec![
EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id,
turn_id: "turn-1".into(),
item: entered,
completed_at_ms: 0,
}),
EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id,
turn_id: "turn-1".into(),
item: exited,
completed_at_ms: 0,
}),
EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "turn-1".into(),
last_agent_message: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
}),
];
let mut builder = ThreadHistoryBuilder::new();
for event in &events {
builder.handle_event(event);
}
let turns = builder.finish();
assert_eq!(turns[0].id, "turn-1");
assert_eq!(
turns[0].items,
vec![
ThreadItem::EnteredReviewMode {
id: "entered-review".into(),
review: "Review requested.".into(),
},
ThreadItem::ExitedReviewMode {
id: "exited-review".into(),
review: REVIEW_FALLBACK_MESSAGE.into(),
},
]
);
}
#[test]
fn rebuilds_user_message_image_details_from_legacy_events() {
let local_path = PathBuf::from("/tmp/local.png");
@@ -2549,14 +2694,14 @@ mod tests {
assert_eq!(turns[0].items.len(), 4);
assert_eq!(
turns[0].items[1],
ThreadItem::WebSearch {
ThreadItem::WebSearch(WebSearchItem {
id: "search-1".into(),
query: "codex".into(),
action: Some(WebSearchAction::Search {
query: Some("codex".into()),
queries: None,
}),
}
})
);
assert_eq!(
turns[0].items[2],
@@ -3882,6 +4027,37 @@ mod tests {
);
}
#[test]
fn canonical_hook_prompt_completion_updates_turn_history() {
let hook_prompt = CoreTurnItem::HookPrompt(codex_protocol::items::HookPromptItem {
id: "hook-prompt-1".into(),
fragments: vec![CoreHookPromptFragment::from_single_hook(
"Retry with tests.",
"hook-run-1",
)],
});
let expected_item = ThreadItem::from(hook_prompt.clone());
let mut builder = ThreadHistoryBuilder::new();
builder.handle_event(&EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-a".into(),
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}));
builder.handle_event(&EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id: ThreadId::new(),
turn_id: "turn-a".into(),
item: hook_prompt,
completed_at_ms: 0,
}));
assert_eq!(
builder.active_turn_snapshot().expect("active turn").items,
vec![expected_item]
);
}
#[test]
fn ignores_plain_user_response_items_in_rollout_replay() {
let items = vec![
@@ -3929,7 +4105,6 @@ mod tests {
..Default::default()
}),
));
assert_eq!(
changes,
ThreadHistoryChangeSet {
@@ -3976,20 +4151,19 @@ mod tests {
},
}),
));
assert_eq!(
changes,
ThreadHistoryChangeSet {
changed_items: vec![ThreadHistoryItemChange {
turn_id: "rollout-0".into(),
item: ThreadItem::WebSearch {
item: ThreadItem::WebSearch(WebSearchItem {
id: "search-1".into(),
query: "codex".into(),
action: Some(WebSearchAction::Search {
query: Some("codex".into()),
queries: None,
}),
},
}),
}],
changed_turns: Vec::new(),
removed_turn_ids: Vec::new(),
@@ -4011,7 +4185,6 @@ mod tests {
text: "raw content".into(),
}),
));
assert_eq!(
changes,
ThreadHistoryChangeSet {
@@ -4111,20 +4284,19 @@ mod tests {
},
})),
]);
assert_eq!(
changes,
ThreadHistoryChangeSet {
changed_items: vec![ThreadHistoryItemChange {
turn_id: "rollout-0".into(),
item: ThreadItem::WebSearch {
item: ThreadItem::WebSearch(WebSearchItem {
id: "search-1".into(),
query: "codex".into(),
action: Some(WebSearchAction::Search {
query: Some("codex".into()),
queries: None,
}),
},
}),
}],
changed_turns: vec![ThreadHistoryTurnChange {
turn_id: "rollout-0".into(),
@@ -10,9 +10,12 @@ use super::UserInput;
use super::shared::v2_enum_from_core;
use crate::protocol::item_builders::command_actions_for_path_uri;
use crate::protocol::item_builders::convert_patch_changes;
use crate::protocol::item_builders::review_output_text;
use codex_experimental_api_macros::ExperimentalApi;
use codex_extension_items::ExtensionItem;
pub use codex_extension_items::image_generation::ImageGenerationItem;
pub use codex_extension_items::web_search::WebSearchAction;
pub use codex_extension_items::web_search::WebSearchItem;
use codex_protocol::approvals::GuardianAssessmentAction as CoreGuardianAssessmentAction;
use codex_protocol::approvals::GuardianAssessmentDecisionSource as CoreGuardianAssessmentDecisionSource;
use codex_protocol::approvals::GuardianCommandSource as CoreGuardianCommandSource;
@@ -358,13 +361,7 @@ pub enum ThreadItem {
agent_thread_id: String,
agent_path: String,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
WebSearch {
id: String,
query: String,
action: Option<WebSearchAction>,
},
WebSearch(WebSearchItem),
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
ImageView {
@@ -432,12 +429,12 @@ impl ThreadItem {
| ThreadItem::DynamicToolCall { id, .. }
| ThreadItem::CollabAgentToolCall { id, .. }
| ThreadItem::SubAgentActivity { id, .. }
| ThreadItem::WebSearch { id, .. }
| ThreadItem::ImageView { id, .. }
| ThreadItem::Sleep { id, .. }
| ThreadItem::EnteredReviewMode { id, .. }
| ThreadItem::ExitedReviewMode { id, .. }
| ThreadItem::ContextCompaction { id, .. } => id,
ThreadItem::WebSearch(item) => &item.id,
ThreadItem::ImageGeneration(item) => &item.id,
}
}
@@ -786,40 +783,20 @@ impl TryFrom<GuardianApprovalReviewAction> for CoreGuardianAssessmentAction {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum WebSearchAction {
Search {
query: Option<String>,
queries: Option<Vec<String>>,
},
OpenPage {
url: Option<String>,
},
FindInPage {
url: Option<String>,
pattern: Option<String>,
},
#[serde(other)]
Other,
}
impl From<codex_protocol::models::WebSearchAction> for WebSearchAction {
fn from(value: codex_protocol::models::WebSearchAction) -> Self {
match value {
codex_protocol::models::WebSearchAction::Search { query, queries } => {
WebSearchAction::Search { query, queries }
}
codex_protocol::models::WebSearchAction::OpenPage { url } => {
WebSearchAction::OpenPage { url }
}
codex_protocol::models::WebSearchAction::FindInPage { url, pattern } => {
WebSearchAction::FindInPage { url, pattern }
}
codex_protocol::models::WebSearchAction::Other => WebSearchAction::Other,
pub(crate) fn web_search_action_from_core(
value: codex_protocol::models::WebSearchAction,
) -> WebSearchAction {
match value {
codex_protocol::models::WebSearchAction::Search { query, queries } => {
WebSearchAction::Search { query, queries }
}
codex_protocol::models::WebSearchAction::OpenPage { url } => {
WebSearchAction::OpenPage { url }
}
codex_protocol::models::WebSearchAction::FindInPage { url, pattern } => {
WebSearchAction::FindInPage { url, pattern }
}
codex_protocol::models::WebSearchAction::Other => WebSearchAction::Other,
}
}
@@ -921,11 +898,11 @@ impl From<CoreTurnItem> for ThreadItem {
agent_thread_id: activity.agent_thread_id.to_string(),
agent_path: String::from(activity.agent_path),
},
CoreTurnItem::WebSearch(search) => ThreadItem::WebSearch {
CoreTurnItem::WebSearch(search) => ThreadItem::WebSearch(WebSearchItem {
id: search.id,
query: search.query,
action: Some(WebSearchAction::from(search.action)),
},
action: Some(web_search_action_from_core(search.action)),
}),
CoreTurnItem::ImageView(image) => ThreadItem::ImageView {
id: image.id,
path: image.path.into(),
@@ -936,6 +913,7 @@ impl From<CoreTurnItem> for ThreadItem {
},
CoreTurnItem::Extension(extension) => match extension {
ExtensionItem::ImageGeneration(item) => ThreadItem::ImageGeneration(item),
ExtensionItem::WebSearch(item) => ThreadItem::WebSearch(item),
},
CoreTurnItem::ImageGeneration(image) => {
ThreadItem::ImageGeneration(ImageGenerationItem {
@@ -946,6 +924,14 @@ impl From<CoreTurnItem> for ThreadItem {
saved_path: image.saved_path,
})
}
CoreTurnItem::EnteredReviewMode(review) => ThreadItem::EnteredReviewMode {
id: review.id,
review: review.user_facing_hint,
},
CoreTurnItem::ExitedReviewMode(review) => ThreadItem::ExitedReviewMode {
id: review.id,
review: review_output_text(review.review_output.as_ref()),
},
CoreTurnItem::FileChange(file_change) => ThreadItem::FileChange {
id: file_change.id,
changes: convert_patch_changes(&file_change.changes),
@@ -19,7 +19,7 @@ use codex_protocol::items::ReasoningItem;
use codex_protocol::items::SubAgentActivityItem;
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
use codex_protocol::items::WebSearchItem;
use codex_protocol::items::WebSearchItem as CoreWebSearchItem;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::memory_citation::MemoryCitation as CoreMemoryCitation;
@@ -2770,7 +2770,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() {
}
);
let search_item = TurnItem::WebSearch(WebSearchItem {
let search_item = TurnItem::WebSearch(CoreWebSearchItem {
id: "search-1".to_string(),
query: "docs".to_string(),
action: CoreWebSearchAction::Search {
@@ -2779,16 +2779,24 @@ fn core_turn_item_into_thread_item_converts_supported_variants() {
},
});
let expected_search_item = WebSearchItem {
id: "search-1".to_string(),
query: "docs".to_string(),
action: Some(WebSearchAction::Search {
query: Some("docs".to_string()),
queries: None,
}),
};
assert_eq!(
ThreadItem::from(search_item),
ThreadItem::WebSearch {
id: "search-1".to_string(),
query: "docs".to_string(),
action: Some(WebSearchAction::Search {
query: Some("docs".to_string()),
queries: None,
}),
}
ThreadItem::WebSearch(expected_search_item.clone())
);
assert_eq!(
ThreadItem::from(TurnItem::Extension(
codex_extension_items::ExtensionItem::WebSearch(expected_search_item.clone()),
)),
ThreadItem::WebSearch(expected_search_item)
);
let image_view_item = TurnItem::ImageView(ImageViewItem {
+1
View File
@@ -5,6 +5,7 @@ codex_rust_crate(
crate_name = "codex_app_server",
extra_binaries = [
"//codex-rs/bwrap:bwrap",
"//codex-rs/code-mode-host:codex-code-mode-host",
],
extra_binaries_non_windows = [
"//codex-rs/cli:codex",
+5
View File
@@ -12,6 +12,10 @@ path = "src/main.rs"
name = "codex-app-server-test-notify-capture"
path = "src/bin/notify_capture.rs"
[[bin]]
name = "exec-server"
path = "src/bin/exec_server.rs"
[lib]
name = "codex_app_server"
path = "src/lib.rs"
@@ -47,6 +51,7 @@ codex-guardian = { workspace = true }
codex-git-utils = { workspace = true }
codex-file-watcher = { workspace = true }
codex-hooks = { workspace = true }
codex-http-client = { workspace = true }
codex-otel = { workspace = true }
codex-plugin = { workspace = true }
codex-shell-command = { workspace = true }
@@ -86,12 +86,9 @@ use codex_app_server_protocol::guardian_auto_approval_review_notification;
use codex_app_server_protocol::item_event_to_server_notification;
use codex_core::CodexThread;
use codex_core::ThreadManager;
use codex_core::review_format::format_review_findings_block;
use codex_core::review_prompts;
use codex_protocol::ThreadId;
use codex_protocol::items::CollabAgentTool as CoreCollabAgentTool;
use codex_protocol::items::TurnItem as CoreTurnItem;
use codex_protocol::items::parse_hook_prompt_message;
use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile;
use codex_protocol::plan_tool::UpdatePlanArgs;
use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo;
@@ -101,7 +98,6 @@ use codex_protocol::protocol::ExecApprovalRequestEvent;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::ReviewOutputEvent;
use codex_protocol::protocol::SubAgentActivityKind;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TurnAbortedEvent;
@@ -837,11 +833,13 @@ pub(crate) async fn apply_bespoke_event_handling(
| EventMsg::CollabResumeEnd(_)
| EventMsg::SubAgentActivity(_)
| EventMsg::ExecCommandBegin(_)
| EventMsg::ExecCommandEnd(_) => {
| EventMsg::ExecCommandEnd(_)
| EventMsg::EnteredReviewMode(_)
| EventMsg::ExitedReviewMode(_) => {
// Deprecated item lifecycle events are still fanned out for raw-event and rollout
// compatibility consumers.
// App-server v2 receives canonical TurnItem lifecycle instead, and dispatches
// dynamic tool requests from canonical DynamicToolCall starts.
// App-server v2 receives TurnItem lifecycle instead, and dispatches dynamic tool
// requests from DynamicToolCall starts.
}
EventMsg::McpToolCallBegin(_) | EventMsg::McpToolCallEnd(_) => {
// Deprecated MCP tool-call events are still fanned out for raw-event and rollout
@@ -938,33 +936,6 @@ pub(crate) async fn apply_bespoke_event_handling(
.await;
}
EventMsg::ViewImageToolCall(_) => {}
EventMsg::EnteredReviewMode(review_request) => {
let review = review_request
.user_facing_hint
.unwrap_or_else(|| review_prompts::user_facing_hint(&review_request.target));
let item = ThreadItem::EnteredReviewMode {
id: event_turn_id.clone(),
review,
};
let started = ItemStartedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
item: item.clone(),
};
outgoing
.send_server_notification(ServerNotification::ItemStarted(started))
.await;
let completed = ItemCompletedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
completed_at_ms: now_unix_timestamp_ms(),
item,
};
outgoing
.send_server_notification(ServerNotification::ItemCompleted(completed))
.await;
}
EventMsg::ItemStarted(event) => {
let should_emit = match &event.item {
// Approval and guardian flows can emit the command start notification before core
@@ -1049,42 +1020,7 @@ pub(crate) async fn apply_bespoke_event_handling(
.send_server_notification(ServerNotification::HookCompleted(notification))
.await;
}
EventMsg::ExitedReviewMode(review_event) => {
let review = match review_event.review_output {
Some(output) => render_review_output_text(&output),
None => REVIEW_FALLBACK_MESSAGE.to_string(),
};
let item = ThreadItem::ExitedReviewMode {
id: event_turn_id.clone(),
review,
};
let started = ItemStartedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
item: item.clone(),
};
outgoing
.send_server_notification(ServerNotification::ItemStarted(started))
.await;
let completed = ItemCompletedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
completed_at_ms: now_unix_timestamp_ms(),
item,
};
outgoing
.send_server_notification(ServerNotification::ItemCompleted(completed))
.await;
}
EventMsg::RawResponseItem(raw_response_item_event) => {
maybe_emit_hook_prompt_item_completed(
conversation_id,
&event_turn_id,
&raw_response_item_event.item,
&outgoing,
)
.await;
maybe_emit_raw_response_item_completed(
conversation_id,
&event_turn_id,
@@ -1462,45 +1398,6 @@ async fn maybe_emit_raw_response_item_completed(
.await;
}
pub(crate) async fn maybe_emit_hook_prompt_item_completed(
conversation_id: ThreadId,
turn_id: &str,
item: &codex_protocol::models::ResponseItem,
outgoing: &ThreadScopedOutgoingMessageSender,
) {
let codex_protocol::models::ResponseItem::Message {
role, content, id, ..
} = item
else {
return;
};
if role != "user" {
return;
}
let Some(hook_prompt) = parse_hook_prompt_message(id.as_ref(), content) else {
return;
};
let notification = ItemCompletedNotification {
thread_id: conversation_id.to_string(),
turn_id: turn_id.to_string(),
completed_at_ms: now_unix_timestamp_ms(),
item: ThreadItem::HookPrompt {
id: hook_prompt.id,
fragments: hook_prompt
.fragments
.into_iter()
.map(codex_app_server_protocol::HookPromptFragment::from)
.collect(),
},
};
outgoing
.send_server_notification(ServerNotification::ItemCompleted(notification))
.await;
}
async fn find_and_remove_turn_summary(
_conversation_id: ThreadId,
thread_state: &Arc<Mutex<ThreadState>>,
@@ -1952,28 +1849,6 @@ fn request_permissions_response_from_client_result(
}))
}
const REVIEW_FALLBACK_MESSAGE: &str = "Reviewer failed to output a response.";
fn render_review_output_text(output: &ReviewOutputEvent) -> String {
let mut sections = Vec::new();
let explanation = output.overall_explanation.trim();
if !explanation.is_empty() {
sections.push(explanation.to_string());
}
if !output.findings.is_empty() {
let findings = format_review_findings_block(&output.findings, /*selection*/ None);
let trimmed = findings.trim();
if !trimmed.is_empty() {
sections.push(trimmed.to_string());
}
}
if sections.is_empty() {
REVIEW_FALLBACK_MESSAGE.to_string()
} else {
sections.join("\n\n")
}
}
fn map_file_change_approval_decision(decision: FileChangeApprovalDecision) -> ReviewDecision {
match decision {
FileChangeApprovalDecision::Accept => ReviewDecision::Approved,
@@ -2182,10 +2057,8 @@ mod tests {
use codex_protocol::AgentPath;
use codex_protocol::items::DynamicToolCallItem;
use codex_protocol::items::DynamicToolCallStatus as CoreDynamicToolCallStatus;
use codex_protocol::items::HookPromptFragment;
use codex_protocol::items::SubAgentActivityItem;
use codex_protocol::items::TurnItem as CoreTurnItem;
use codex_protocol::items::build_hook_prompt_message;
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions;
use codex_protocol::models::PermissionProfile;
@@ -4071,55 +3944,4 @@ mod tests {
assert!(rx.try_recv().is_err(), "no extra messages expected");
Ok(())
}
#[tokio::test]
async fn test_hook_prompt_raw_response_emits_item_completed() -> Result<()> {
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
let outgoing = Arc::new(OutgoingMessageSender::new(
tx,
codex_analytics::AnalyticsEventsClient::disabled(),
));
let conversation_id = ThreadId::new();
let outgoing = ThreadScopedOutgoingMessageSender::new(
outgoing,
vec![ConnectionId(1)],
conversation_id,
);
let item = build_hook_prompt_message(&[
HookPromptFragment::from_single_hook("Retry with tests.", "hook-run-1"),
HookPromptFragment::from_single_hook("Then summarize cleanly.", "hook-run-2"),
])
.expect("hook prompt message");
maybe_emit_hook_prompt_item_completed(conversation_id, "turn-1", &item, &outgoing).await;
let msg = recv_broadcast_message(&mut rx).await?;
match msg {
OutgoingMessage::AppServerNotification(ServerNotification::ItemCompleted(
notification,
)) => {
assert_eq!(notification.thread_id, conversation_id.to_string());
assert_eq!(notification.turn_id, "turn-1");
assert_eq!(
notification.item,
ThreadItem::HookPrompt {
id: notification.item.id().to_string(),
fragments: vec![
codex_app_server_protocol::HookPromptFragment {
text: "Retry with tests.".into(),
hook_run_id: "hook-run-1".into(),
},
codex_app_server_protocol::HookPromptFragment {
text: "Then summarize cleanly.".into(),
hook_run_id: "hook-run-2".into(),
},
],
}
);
}
other => bail!("unexpected message: {other:?}"),
}
assert!(rx.try_recv().is_err(), "no extra messages expected");
Ok(())
}
}
@@ -0,0 +1,31 @@
//! Cargo entry point for the minimal exec-server integration-test fixture.
//!
//! This mirrors `//codex-rs/exec-server/testing:exec-server` so Cargo-backed
//! app-server integration tests can receive `CARGO_BIN_EXE_exec-server`. It
//! also handles the filesystem-helper argv mode because exec-server re-execs
//! `codex_self_exe` for sandboxed filesystem requests.
use codex_exec_server::ExecServerRuntimePaths;
use std::ffi::OsStr;
const CODEX_LINUX_SANDBOX_EXE_ENV_VAR: &str = "CODEX_TEST_LINUX_SANDBOX_EXE";
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut args = std::env::args_os();
let _ = args.next();
if args.next().as_deref() == Some(OsStr::new(codex_exec_server::CODEX_FS_HELPER_ARG1)) {
codex_exec_server::run_fs_helper_main();
}
let current_exe = std::env::current_exe()?;
let codex_linux_sandbox_exe =
std::env::var_os(CODEX_LINUX_SANDBOX_EXE_ENV_VAR).map(std::path::PathBuf::from);
let runtime_paths = ExecServerRuntimePaths::new(current_exe, codex_linux_sandbox_exe)?;
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?
.block_on(codex_exec_server::run_main(
"ws://127.0.0.1:0",
runtime_paths,
))
}
+2 -1
View File
@@ -299,7 +299,8 @@ impl MessageProcessor {
)
});
let models_manager = thread_manager.get_models_manager();
let models_refresh_worker = crate::models_refresh_worker::spawn(&models_manager);
let models_refresh_worker =
crate::models_refresh_worker::spawn(&models_manager, config.http_client_factory());
thread_manager
.plugins_manager()
.set_analytics_events_client(analytics_events_client.clone());
+3 -1
View File
@@ -5,6 +5,7 @@ use codex_app_server_protocol::ModelServiceTier;
use codex_app_server_protocol::ModelUpgradeInfo;
use codex_app_server_protocol::ReasoningEffortOption;
use codex_core::ThreadManager;
use codex_http_client::HttpClientFactory;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::openai_models::ReasoningEffortPreset;
@@ -12,9 +13,10 @@ use codex_protocol::openai_models::ReasoningEffortPreset;
pub async fn supported_models(
thread_manager: Arc<ThreadManager>,
include_hidden: bool,
http_client_factory: HttpClientFactory,
) -> Vec<Model> {
thread_manager
.list_models(RefreshStrategy::OnlineIfUncached)
.list_models(RefreshStrategy::OnlineIfUncached, http_client_factory)
.await
.into_iter()
.filter(|preset| include_hidden || preset.show_in_picker)
@@ -1,6 +1,7 @@
use std::sync::Arc;
use std::time::Duration;
use codex_http_client::HttpClientFactory;
use codex_models_manager::manager::RefreshStrategy;
use codex_models_manager::manager::SharedModelsManager;
use tokio::task::JoinHandle;
@@ -26,12 +27,16 @@ impl Drop for ModelsRefreshWorker {
}
}
pub(crate) fn spawn(models_manager: &SharedModelsManager) -> ModelsRefreshWorker {
spawn_with_interval(models_manager, MODELS_REFRESH_INTERVAL)
pub(crate) fn spawn(
models_manager: &SharedModelsManager,
http_client_factory: HttpClientFactory,
) -> ModelsRefreshWorker {
spawn_with_interval(models_manager, http_client_factory, MODELS_REFRESH_INTERVAL)
}
fn spawn_with_interval(
models_manager: &SharedModelsManager,
http_client_factory: HttpClientFactory,
refresh_interval: Duration,
) -> ModelsRefreshWorker {
let models_manager = Arc::downgrade(models_manager);
@@ -45,7 +50,9 @@ fn spawn_with_interval(
let Some(models_manager) = models_manager.upgrade() else {
break;
};
models_manager.list_models(RefreshStrategy::Online).await;
models_manager
.list_models(RefreshStrategy::Online, http_client_factory.clone())
.await;
drop(models_manager);
tokio::select! {
@@ -3,6 +3,8 @@ use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_models_manager::manager::ModelsEndpointClient;
use codex_models_manager::manager::ModelsEndpointFuture;
use codex_models_manager::manager::OpenAiModelsManager;
@@ -55,6 +57,7 @@ impl ModelsEndpointClient for TestModelsEndpoint {
fn list_models<'a>(
&'a self,
_client_version: &'a str,
_http_client_factory: HttpClientFactory,
) -> ModelsEndpointFuture<'a, CoreResult<(Vec<ModelInfo>, Option<String>)>> {
Box::pin(async move {
let fetch_index = self.fetch_count.fetch_add(1, Ordering::SeqCst);
@@ -79,7 +82,11 @@ async fn refreshes_immediately_periodically_and_stops_when_dropped() {
endpoint.clone(),
/*auth_manager*/ None,
));
let worker = spawn_with_interval(&models_manager, Duration::from_millis(10));
let worker = spawn_with_interval(
&models_manager,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Duration::from_millis(10),
);
endpoint.wait_for_fetch_count(/*expected*/ 2).await;
drop(worker);
@@ -1,5 +1,4 @@
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed;
use crate::command_exec::CommandExecManager;
use crate::command_exec::StartCommandExecParams;
use crate::config_manager::ConfigManager;
@@ -439,8 +438,8 @@ use codex_protocol::protocol::SessionConfiguredEvent;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::TurnEnvironmentSelections;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::protocol::strip_user_message_prefix;
use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
use codex_protocol::user_input::UserInput as CoreInputItem;
use codex_rmcp_client::perform_oauth_login_return_url_with_http_client;
@@ -626,10 +625,10 @@ pub(crate) use self::thread_summary::summary_to_thread;
pub(crate) use self::thread_summary::thread_settings_from_config_snapshot;
pub(crate) use self::thread_summary::thread_settings_from_core_snapshot;
pub(crate) fn build_api_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
pub(crate) fn build_legacy_api_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
let mut builder = ThreadHistoryBuilder::new();
for item in items {
if is_persisted_rollout_item(item) {
if is_persisted_rollout_item(item, codex_protocol::protocol::ThreadHistoryMode::Legacy) {
builder.handle_rollout_item(item);
}
}
@@ -157,9 +157,13 @@ impl CatalogRequestProcessor {
&self,
params: ModelListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
Self::list_models(self.thread_manager.clone(), params)
.await
.map(|response| Some(response.into()))
Self::list_models(
self.thread_manager.clone(),
self.config.http_client_factory(),
params,
)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn experimental_feature_list(
@@ -247,6 +251,7 @@ impl CatalogRequestProcessor {
async fn list_models(
thread_manager: Arc<ThreadManager>,
http_client_factory: codex_http_client::HttpClientFactory,
params: ModelListParams,
) -> Result<ModelListResponse, JSONRPCErrorError> {
let ModelListParams {
@@ -254,7 +259,12 @@ impl CatalogRequestProcessor {
cursor,
include_hidden,
} = params;
let models = supported_models(thread_manager, include_hidden.unwrap_or(false)).await;
let models = supported_models(
thread_manager,
include_hidden.unwrap_or(false),
http_client_factory,
)
.await;
let total = models.len();
if total == 0 {
@@ -189,6 +189,7 @@ impl ExternalAgentSessionImporter {
&config.model,
/*allow_provider_model_fallback*/ false,
RefreshStrategy::Offline,
config.http_client_factory(),
)
.await;
let model_info = models_manager
@@ -230,7 +231,7 @@ impl ExternalAgentSessionImporter {
memory_mode,
},
};
rollout_items.retain(is_persisted_rollout_item);
rollout_items.retain(|item| is_persisted_rollout_item(item, ThreadHistoryMode::Legacy));
let title = title
.as_deref()
.and_then(codex_core::util::normalize_thread_name);
@@ -316,6 +316,9 @@ pub(super) async fn ensure_listener_task_running(
thread_state.track_current_turn_event(&event.id, &event.msg);
thread_state.experimental_raw_events
};
if matches!(&event.msg, EventMsg::RawResponseItem(_)) && !raw_events_enabled {
continue;
}
let subscribed_connection_ids = thread_state_manager
.subscribed_connection_ids(conversation_id)
.await;
@@ -325,19 +328,6 @@ pub(super) async fn ensure_listener_task_running(
conversation_id,
);
if let EventMsg::RawResponseItem(raw_response_item_event) = &event.msg
&& !raw_events_enabled
{
maybe_emit_hook_prompt_item_completed(
conversation_id,
&event.id,
&raw_response_item_event.item,
&thread_outgoing,
)
.await;
continue;
}
apply_bespoke_event_handling(
event.clone(),
conversation_id,
@@ -748,7 +738,7 @@ pub(crate) fn populate_thread_turns_from_history(
items: &[RolloutItem],
active_turn: Option<&Turn>,
) {
let mut turns = build_api_turns_from_rollout_items(items);
let mut turns = build_legacy_api_turns_from_rollout_items(items);
if let Some(active_turn) = active_turn {
merge_turn_history_with_active_turn(&mut turns, active_turn.clone());
}
@@ -164,6 +164,34 @@ fn merge_persisted_resume_metadata(
}
}
fn merge_persisted_approvals_reviewer(
thread_history: &InitialHistory,
request_overrides: Option<&HashMap<String, serde_json::Value>>,
typesafe_overrides: &mut ConfigOverrides,
) {
if typesafe_overrides.approvals_reviewer.is_some()
|| request_overrides.is_some_and(|overrides| overrides.contains_key("approvals_reviewer"))
{
return;
}
let InitialHistory::Resumed(resumed_history) = thread_history else {
return;
};
typesafe_overrides.approvals_reviewer =
resumed_history
.history
.iter()
.rev()
.find_map(|item| match item {
RolloutItem::TurnContext(turn_context) => turn_context.approvals_reviewer,
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => {
Some(event.thread_settings.approvals_reviewer)
}
_ => None,
});
}
fn normalize_thread_list_cwd_filters(
cwd: Option<ThreadListCwdFilter>,
) -> Result<Option<Vec<PathBuf>>, JSONRPCErrorError> {
@@ -2311,7 +2339,7 @@ impl ThreadRequestProcessor {
let (mut thread, history) =
thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd);
if include_turns && let Some(history) = history {
thread.turns = build_api_turns_from_rollout_items(&history.items);
thread.turns = build_legacy_api_turns_from_rollout_items(&history.items);
}
Ok(Some(thread))
}
@@ -2380,7 +2408,7 @@ impl ThreadRequestProcessor {
.load_history(/*include_archived*/ true)
.await
.map_err(|err| thread_read_history_load_error(thread_id, err))?;
thread.turns = build_api_turns_from_rollout_items(&history.items);
thread.turns = build_legacy_api_turns_from_rollout_items(&history.items);
}
Ok(())
@@ -2957,6 +2985,11 @@ impl ThreadRequestProcessor {
request_overrides: &mut Option<HashMap<String, serde_json::Value>>,
typesafe_overrides: &mut ConfigOverrides,
) -> Option<ThreadMetadata> {
merge_persisted_approvals_reviewer(
thread_history,
request_overrides.as_ref(),
typesafe_overrides,
);
let InitialHistory::Resumed(resumed_history) = thread_history else {
return None;
};
@@ -4074,7 +4107,7 @@ fn reconstruct_thread_turns_for_turns_list(
|| active_turn
.as_ref()
.is_some_and(|turn| matches!(turn.status, TurnStatus::InProgress));
let mut turns = build_api_turns_from_rollout_items(items);
let mut turns = build_legacy_api_turns_from_rollout_items(items);
normalize_thread_turns_status(&mut turns, loaded_status, has_live_in_progress_turn);
if let Some(active_turn) = active_turn {
merge_turn_history_with_active_turn(&mut turns, active_turn);
@@ -4447,10 +4480,7 @@ fn preview_from_rollout_items(items: &[RolloutItem]) -> String {
},
_ => None,
})
.map(|preview| match preview.find(USER_MESSAGE_BEGIN) {
Some(idx) => preview[idx + USER_MESSAGE_BEGIN.len()..].trim().to_string(),
None => preview,
})
.map(|preview| strip_user_message_prefix(preview.as_str()).to_string())
.unwrap_or_default()
}
@@ -97,10 +97,7 @@ fn extract_conversation_summary(
_ => None,
})?;
let preview = match preview.find(USER_MESSAGE_BEGIN) {
Some(idx) => preview[idx + USER_MESSAGE_BEGIN.len()..].trim(),
None => preview.as_str(),
};
let preview = strip_user_message_prefix(preview.as_str());
let timestamp = if session_meta.timestamp.is_empty() {
None
@@ -1,6 +1,7 @@
use super::*;
use anyhow::Result;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::PathBuf;
+10 -1
View File
@@ -6,7 +6,6 @@ license.workspace = true
[lib]
path = "lib.rs"
test = false
doctest = false
[lints]
@@ -29,12 +28,22 @@ serde = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"io-util",
"io-std",
"macros",
"net",
"process",
"rt-multi-thread",
"sync",
"test-util",
"time",
] }
tokio-util = { workspace = true }
url = { workspace = true }
uuid = { workspace = true }
wiremock = { workspace = true }
core_test_support = { path = "../../../core/tests/common" }
shlex = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
+2
View File
@@ -4,10 +4,12 @@ mod analytics_server;
mod auth_fixtures;
mod config;
mod json_logging;
mod local_websocket_exec_server;
mod mock_model_server;
mod models_cache;
mod responses;
mod rollout;
mod rpc_delay;
mod test_app_server;
pub use analytics_server::start_analytics_events_server;
@@ -0,0 +1,90 @@
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Child;
use tokio::process::Command;
const START_TIMEOUT: Duration = Duration::from_secs(10);
#[cfg(target_os = "linux")]
const CODEX_LINUX_SANDBOX_EXE_ENV_VAR: &str = "CODEX_TEST_LINUX_SANDBOX_EXE";
/// Host-local exec-server fixture that exposes a WebSocket URL.
///
/// This is distinct from the ordinary local stdio executor: callers use it
/// when they need a socket transport they can interpose.
pub(crate) struct LocalWebsocketExecServer {
child: Child,
websocket_url: String,
}
impl LocalWebsocketExecServer {
pub(crate) async fn start(codex_home: &Path, exec_server_program: &Path) -> Result<Self> {
let mut command = Command::new(exec_server_program);
command.stdin(Stdio::null());
command.stdout(Stdio::piped());
command.stderr(Stdio::inherit());
command.current_dir(codex_home);
command.env("CODEX_HOME", codex_home);
#[cfg(target_os = "linux")]
command.env(
CODEX_LINUX_SANDBOX_EXE_ENV_VAR,
core_test_support::find_codex_linux_sandbox_exe()
.context("should find binary for delayed exec-server Linux sandbox helper")?,
);
command.kill_on_drop(true);
let child = command.spawn().context("start local exec-server fixture")?;
let mut exec_server = Self {
child,
websocket_url: String::new(),
};
let stdout = exec_server
.child
.stdout
.take()
.ok_or_else(|| anyhow!("local exec-server fixture stdout was not captured"))?;
let mut lines = BufReader::new(stdout).lines();
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
exec_server.websocket_url = loop {
let remaining = deadline
.checked_duration_since(tokio::time::Instant::now())
.ok_or_else(|| anyhow!("timed out waiting for local exec-server listen URL"))?;
let line = tokio::time::timeout(remaining, lines.next_line())
.await
.map_err(|_| anyhow!("timed out waiting for local exec-server listen URL"))??
.ok_or_else(|| {
anyhow!("local exec-server exited before emitting its listen URL")
})?;
let listen_url = line.trim();
if listen_url.starts_with("ws://") {
break listen_url.to_string();
}
};
Ok(exec_server)
}
pub(crate) fn websocket_url(&self) -> &str {
&self.websocket_url
}
}
impl Drop for LocalWebsocketExecServer {
fn drop(&mut self) {
let _ = self.child.start_kill();
let start = std::time::Instant::now();
let timeout = Duration::from_secs(5);
while start.elapsed() < timeout {
match self.child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => return,
}
}
}
}
+3 -2
View File
@@ -9,6 +9,7 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use core_test_support::test_path_buf;
use serde_json::json;
use std::fs;
use std::fs::FileTimes;
@@ -189,7 +190,7 @@ fn create_fake_rollout_with_source_and_parent_thread_id(
forked_from_id: None,
parent_thread_id,
timestamp: meta_rfc3339.to_string(),
cwd: PathBuf::from("/"),
cwd: test_path_buf("/"),
originator: "codex".to_string(),
cli_version: "0.0.0".to_string(),
source,
@@ -279,7 +280,7 @@ pub fn create_fake_rollout_with_text_elements(
forked_from_id: None,
parent_thread_id: None,
timestamp: meta_rfc3339.to_string(),
cwd: PathBuf::from("/"),
cwd: test_path_buf("/"),
originator: "codex".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
@@ -0,0 +1,157 @@
use std::io;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::task::JoinSet;
use tokio::time::Instant;
use tokio::time::sleep_until;
use tokio_util::task::AbortOnDropHandle;
use url::Host;
use url::Url;
const FORWARD_BUFFER_BYTES: usize = 64 * 1024;
const FORWARD_QUEUE_CHUNKS: usize = 16;
pub(crate) struct WebsocketDelayInterposer {
websocket_url: String,
accept_task: JoinHandle<()>,
}
impl WebsocketDelayInterposer {
pub(crate) async fn start(upstream_url: &str, added_delay: Duration) -> Result<Self> {
let upstream = websocket_authority(upstream_url)?;
let listener = TcpListener::bind("127.0.0.1:0")
.await
.context("bind RPC delay interposer")?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let accept_task = tokio::spawn(async move {
let mut connections = JoinSet::new();
loop {
tokio::select! {
accepted = listener.accept() => {
let Ok((downstream, _peer)) = accepted else {
break;
};
let upstream = upstream.clone();
connections.spawn(async move {
let Ok(upstream) = TcpStream::connect(upstream).await else {
return;
};
let _ = proxy_connection(downstream, upstream, added_delay).await;
});
}
_ = connections.join_next(), if !connections.is_empty() => {}
}
}
});
Ok(Self {
websocket_url,
accept_task,
})
}
pub(crate) fn websocket_url(&self) -> &str {
&self.websocket_url
}
}
impl Drop for WebsocketDelayInterposer {
fn drop(&mut self) {
self.accept_task.abort();
}
}
fn websocket_authority(websocket_url: &str) -> Result<String> {
let websocket_url = Url::parse(websocket_url).context("parse RPC delay upstream URL")?;
if websocket_url.scheme() != "ws" {
return Err(anyhow!("RPC delay requires a ws:// exec-server URL"));
}
let host = websocket_url
.host()
.ok_or_else(|| anyhow!("RPC delay exec-server URL has no host"))?;
let port = websocket_url
.port_or_known_default()
.ok_or_else(|| anyhow!("RPC delay exec-server URL has no port"))?;
let host = match host {
Host::Domain(host) => host.to_string(),
Host::Ipv4(host) => host.to_string(),
Host::Ipv6(host) => format!("[{host}]"),
};
Ok(format!("{host}:{port}"))
}
async fn proxy_connection(
downstream: TcpStream,
upstream: TcpStream,
added_delay: Duration,
) -> io::Result<()> {
let (downstream_read, downstream_write) = downstream.into_split();
let (upstream_read, upstream_write) = upstream.into_split();
let client_to_server = forward_direction(downstream_read, upstream_write, added_delay);
let server_to_client = forward_direction(upstream_read, downstream_write, added_delay);
tokio::try_join!(client_to_server, server_to_client)?;
Ok(())
}
async fn forward_direction<R, W>(
mut reader: R,
mut writer: W,
added_delay: Duration,
) -> io::Result<()>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
// tokio::io::copy would wait before reading the next chunk, turning a
// fixed propagation delay into a bandwidth limit. Timestamping reads into
// a bounded queue lets close-together chunks emerge close together after
// the same delay while still applying backpressure.
let (tx, mut rx) = mpsc::channel::<DelayedChunk>(FORWARD_QUEUE_CHUNKS);
let reader_task = AbortOnDropHandle::new(tokio::spawn(async move {
loop {
let mut bytes = vec![0; FORWARD_BUFFER_BYTES];
let read = reader.read(&mut bytes).await?;
if read == 0 {
break;
}
bytes.truncate(read);
let chunk = DelayedChunk {
deliver_at: Instant::now() + added_delay,
bytes,
};
if tx.send(chunk).await.is_err() {
break;
}
}
Ok::<(), io::Error>(())
}));
while let Some(chunk) = rx.recv().await {
sleep_until(chunk.deliver_at).await;
writer.write_all(&chunk.bytes).await?;
}
writer.shutdown().await?;
reader_task
.await
.map_err(|err| io::Error::other(format!("RPC delay reader task failed: {err}")))??;
Ok(())
}
struct DelayedChunk {
deliver_at: Instant,
bytes: Vec<u8>,
}
#[cfg(test)]
#[path = "rpc_delay_tests.rs"]
mod tests;
@@ -0,0 +1,181 @@
use std::collections::VecDeque;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
use std::time::Duration;
use pretty_assertions::assert_eq;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::ReadBuf;
use tokio::io::duplex;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::time::advance;
use tokio::time::timeout;
use super::WebsocketDelayInterposer;
use super::forward_direction;
use super::websocket_authority;
#[tokio::test(start_paused = true)]
async fn delays_then_flushes_eof() -> anyhow::Result<()> {
let delay = Duration::from_millis(15);
let (mut input_writer, input_reader) = duplex(/*max_buf_size*/ 64);
let (output_writer, mut output_reader) = duplex(/*max_buf_size*/ 64);
let forward_task = tokio::spawn(forward_direction(input_reader, output_writer, delay));
input_writer.write_all(b"payload").await?;
input_writer.shutdown().await?;
tokio::task::yield_now().await;
let mut before_delay = [0; 1];
assert!(
timeout(Duration::ZERO, output_reader.read(&mut before_delay))
.await
.is_err()
);
advance(delay).await;
let mut output = Vec::new();
output_reader.read_to_end(&mut output).await?;
assert_eq!(output, b"payload");
forward_task.await??;
Ok(())
}
#[tokio::test(start_paused = true)]
async fn burst_chunks_share_one_deadline() -> anyhow::Result<()> {
let delay = Duration::from_millis(15);
let (mut input_writer, input_reader) = duplex(/*max_buf_size*/ 1);
let (output_writer, mut output_reader) = duplex(/*max_buf_size*/ 64);
let forward_task = tokio::spawn(forward_direction(input_reader, output_writer, delay));
input_writer.write_all(b"ab").await?;
input_writer.shutdown().await?;
tokio::task::yield_now().await;
advance(delay).await;
tokio::task::yield_now().await;
let mut output = [0; 2];
timeout(Duration::ZERO, output_reader.read_exact(&mut output)).await??;
assert_eq!(output, *b"ab");
forward_task.await??;
Ok(())
}
#[tokio::test]
async fn write_error_cancels_reader() {
let reader_dropped = Arc::new(AtomicBool::new(false));
let reader = PendingAfterChunkReader::new(Arc::clone(&reader_dropped));
let error = forward_direction(reader, FailingWriter, Duration::ZERO)
.await
.expect_err("failing writer should fail forwarding");
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
for _ in 0..10 {
if reader_dropped.load(Ordering::Acquire) {
break;
}
tokio::task::yield_now().await;
}
assert!(reader_dropped.load(Ordering::Acquire));
}
#[tokio::test]
async fn zero_delay_loopback_forwards_and_closes_active_sockets() -> anyhow::Result<()> {
let upstream_listener = TcpListener::bind("127.0.0.1:0").await?;
let upstream_url = format!("ws://{}", upstream_listener.local_addr()?);
let upstream_task = tokio::spawn(async move {
let (mut upstream, _) = upstream_listener.accept().await?;
let mut request = [0; 5];
upstream.read_exact(&mut request).await?;
assert_eq!(request, *b"hello");
upstream.write_all(b"world").await?;
let mut after_drop = [0; 1];
let read = timeout(Duration::from_secs(1), upstream.read(&mut after_drop)).await??;
Ok::<usize, anyhow::Error>(read)
});
let interposer = WebsocketDelayInterposer::start(&upstream_url, Duration::ZERO).await?;
let mut downstream =
TcpStream::connect(websocket_authority(interposer.websocket_url())?).await?;
downstream.write_all(b"hello").await?;
let mut response = [0; 5];
downstream.read_exact(&mut response).await?;
assert_eq!(response, *b"world");
drop(interposer);
tokio::task::yield_now().await;
let mut after_drop = [0; 1];
let read = timeout(Duration::from_secs(1), downstream.read(&mut after_drop)).await??;
assert_eq!(read, 0);
assert_eq!(upstream_task.await??, 0);
Ok(())
}
struct PendingAfterChunkReader {
chunks: VecDeque<Vec<u8>>,
dropped: Arc<AtomicBool>,
}
impl PendingAfterChunkReader {
fn new(dropped: Arc<AtomicBool>) -> Self {
Self {
chunks: VecDeque::from([b"x".to_vec()]),
dropped,
}
}
}
impl AsyncRead for PendingAfterChunkReader {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let Some(chunk) = self.chunks.pop_front() else {
return Poll::Pending;
};
buf.put_slice(&chunk);
Poll::Ready(Ok(()))
}
}
impl Drop for PendingAfterChunkReader {
fn drop(&mut self) {
self.dropped.store(true, Ordering::Release);
}
}
struct FailingWriter;
impl AsyncWrite for FailingWriter {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &[u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"synthetic write failure",
)))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
@@ -5,6 +5,7 @@ use std::process::ExitStatus;
use std::process::Stdio;
use std::sync::atomic::AtomicI64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
@@ -121,12 +122,15 @@ use codex_exec_server::CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR;
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR;
use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR;
use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR;
use core_test_support::is_remote_test_environment;
use core_test_support::test_codex::TestEnv;
use core_test_support::test_codex::test_env;
use tempfile::TempDir;
use tokio::process::Command;
use crate::json_logging::JsonLogCapture;
use crate::local_websocket_exec_server::LocalWebsocketExecServer;
use crate::rpc_delay::WebsocketDelayInterposer;
pub struct TestAppServer {
next_request_id: AtomicI64,
@@ -141,12 +145,16 @@ pub struct TestAppServer {
auto_env: Option<TestEnv>,
json_logs: JsonLogCapture,
codex_home: PathBuf,
// Fields drop in declaration order. Tear down the delayed child before
// removing an owned CODEX_HOME that may still be its cwd on Windows.
_delayed_exec_server: Option<(LocalWebsocketExecServer, WebsocketDelayInterposer)>,
_owned_codex_home: Option<TempDir>,
}
pub const DEFAULT_CLIENT_NAME: &str = "codex-app-server-tests";
pub const DISABLE_PLUGIN_STARTUP_TASKS_ARG: &str = "--disable-plugin-startup-tasks-for-tests";
const DISABLE_MANAGED_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_DISABLE_MANAGED_CONFIG";
const CODE_MODE_HOST_PATH_ENV_VAR: &str = "CODEX_CODE_MODE_HOST_PATH";
impl TestAppServer {
/// Starts building a server with a temporary CODEX_HOME and the standard
@@ -158,6 +166,7 @@ impl TestAppServer {
program: None,
env_overrides: Vec::new(),
args: vec![DISABLE_PLUGIN_STARTUP_TASKS_ARG.to_string()],
exec_server_delay: None,
}
}
@@ -165,55 +174,19 @@ impl TestAppServer {
self.process.wait().await
}
pub async fn new(codex_home: &Path) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.build()
.await
}
/// Starts an app server with the standard test environment and retains it
/// for the server's lifetime.
///
/// Local test runs explicitly remove `CODEX_EXEC_SERVER_URL`; Docker- and
/// Wine-backed runs set it to the remote fixture URL. Use
/// [`Self::auto_env_params`] or
/// [`Self::send_thread_start_request_with_auto_env`] to select the matching
/// target-native cwd in a thread. Because `environments.toml` overrides the
/// URL-based configuration, this helper rejects a `codex_home` containing
/// that file.
pub async fn new_with_auto_env(codex_home: &Path) -> anyhow::Result<Self> {
Self::builder().with_codex_home(codex_home).build().await
}
/// Starts an auto-environment app server that emits JSON logs.
///
/// `rust_log` is the value to use for the `RUST_LOG` environment variable.
pub async fn new_with_auto_env_and_json_logging(
codex_home: &Path,
rust_log: impl Into<String>,
) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.with_json_logging(rust_log)
.build()
.await
}
/// Returns the automatically selected test environment retained by this server.
///
/// Tests can use the environment to arrange target-native filesystem fixtures before starting
/// a thread. Returns an error unless this server was created with [`Self::new_with_auto_env`].
/// a thread. Returns an error unless the builder's automatic environment is enabled.
pub fn auto_env(&self) -> anyhow::Result<&TestEnv> {
self.auto_env
.as_ref()
.context("auto environment is unavailable; use TestAppServer::new_with_auto_env")
.context("auto environment is unavailable; enable it on TestAppServer::builder")
}
/// Returns app-server protocol parameters for the automatically selected
/// test environment. Returns an error unless this server was created with
/// [`Self::new_with_auto_env`].
/// test environment. Returns an error unless the builder's automatic
/// environment is enabled.
pub fn auto_env_params(&self) -> anyhow::Result<TurnEnvironmentParams> {
let selection = self.auto_env()?.selection();
Ok(TurnEnvironmentParams {
@@ -249,90 +222,6 @@ impl TestAppServer {
self.json_logs.events()
}
pub async fn new_without_managed_config(codex_home: &Path) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.without_managed_config()
.build()
.await
}
pub async fn new_without_managed_config_with_env(
codex_home: &Path,
env_overrides: &[(&str, Option<&str>)],
) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.without_managed_config()
.with_env_overrides(env_overrides)
.build()
.await
}
pub async fn new_with_plugin_startup_tasks(codex_home: &Path) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_plugin_startup_tasks()
.build()
.await
}
pub async fn new_with_env_and_plugin_startup_tasks(
codex_home: &Path,
env_overrides: &[(&str, Option<&str>)],
) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_plugin_startup_tasks()
.with_env_overrides(env_overrides)
.build()
.await
}
pub async fn new_with_args(codex_home: &Path, args: &[&str]) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_args(args)
.build()
.await
}
/// Creates a new MCP process, allowing tests to override or remove
/// specific environment variables for the child process only.
///
/// Pass a tuple of (key, Some(value)) to set/override, or (key, None) to
/// remove a variable from the child's environment.
pub async fn new_with_env(
codex_home: &Path,
env_overrides: &[(&str, Option<&str>)],
) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_env_overrides(env_overrides)
.build()
.await
}
pub async fn new_with_program_and_env(
codex_home: &Path,
program: &Path,
env_overrides: &[(&str, Option<&str>)],
) -> anyhow::Result<Self> {
Self::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_program(program)
.with_env_overrides(env_overrides)
.build()
.await
}
async fn new_with_program_env_and_args(
codex_home: &Path,
program: &Path,
@@ -402,6 +291,7 @@ impl TestAppServer {
auto_env: None,
json_logs,
codex_home: codex_home.to_path_buf(),
_delayed_exec_server: None,
_owned_codex_home: None,
})
}
@@ -579,9 +469,9 @@ impl TestAppServer {
self.send_request("thread/start", params).await
}
/// Sends a `thread/start` request selecting the environment provisioned by
/// [`Self::new_with_auto_env`]. Returns an error if `params` already select
/// environments so the caller cannot accidentally override the fixture.
/// Sends a `thread/start` request selecting the builder's automatic
/// environment. Returns an error if `params` already select environments
/// so the caller cannot accidentally override the fixture.
pub async fn send_thread_start_request_with_auto_env(
&mut self,
mut params: ThreadStartParams,
@@ -1811,6 +1701,7 @@ pub struct TestAppServerBuilder {
program: Option<PathBuf>,
env_overrides: Vec<(String, Option<String>)>,
args: Vec<String>,
exec_server_delay: Option<Duration>,
}
enum TestAppServerEnvironment {
@@ -1880,6 +1771,13 @@ impl TestAppServerBuilder {
builder
}
/// Adds this fixed one-way delay to the app-server/exec-server RPC stream.
/// A 15ms delay contributes roughly 30ms to a round trip.
pub fn with_exec_server_delay(mut self, exec_server_delay: Duration) -> Self {
self.exec_server_delay = Some(exec_server_delay);
self
}
/// Builds a server with a temporary CODEX_HOME and automatic environment
/// by default.
pub async fn build(self) -> anyhow::Result<TestAppServer> {
@@ -1889,6 +1787,7 @@ impl TestAppServerBuilder {
program,
mut env_overrides,
args,
exec_server_delay,
} = self;
let (codex_home, owned_codex_home) = match codex_home {
Some(codex_home) => (codex_home, None),
@@ -1900,7 +1799,7 @@ impl TestAppServerBuilder {
)
}
};
let auto_env = match environment {
let (auto_env, delayed_exec_server) = match environment {
TestAppServerEnvironment::Auto => {
let environments_toml = codex_home.join("environments.toml");
ensure!(
@@ -1911,7 +1810,34 @@ impl TestAppServerBuilder {
"automatic environment cannot be used when {} exists",
environments_toml.display()
);
let auto_env = test_env().await?;
let (auto_env, delayed_exec_server) = match exec_server_delay {
Some(added_delay) => {
ensure!(
!is_remote_test_environment(),
"TestAppServer exec-server delay only supports the local test environment"
);
let exec_server_program =
codex_utils_cargo_bin::cargo_bin("exec-server")
.context("should find binary for delayed exec-server fixture")?;
// Local auto environments normally use stdio. Start a
// host-local WebSocket fixture so the delay interposer has a
// socket stream to wrap.
let local_websocket_exec_server =
LocalWebsocketExecServer::start(&codex_home, &exec_server_program)
.await?;
let interposer = WebsocketDelayInterposer::start(
local_websocket_exec_server.websocket_url(),
added_delay,
)
.await?;
let auto_env = TestEnv::local_with_exec_server_url(Some(
interposer.websocket_url().to_string(),
))
.await?;
(auto_env, Some((local_websocket_exec_server, interposer)))
}
None => (test_env().await?, None),
};
// Noise registry configuration takes precedence over the URL-based
// provider, so clear inherited values to keep the selection hermetic.
let mut auto_env_overrides = vec![
@@ -1935,10 +1861,30 @@ impl TestAppServerBuilder {
];
auto_env_overrides.append(&mut env_overrides);
env_overrides = auto_env_overrides;
Some(auto_env)
(Some(auto_env), delayed_exec_server)
}
TestAppServerEnvironment::None => {
ensure!(
exec_server_delay.is_none(),
"exec-server delay requires the automatic test environment"
);
(None, None)
}
TestAppServerEnvironment::None => None,
};
if !env_overrides
.iter()
.any(|(key, _)| key == CODE_MODE_HOST_PATH_ENV_VAR)
&& let Ok(code_mode_host_program) =
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")
{
env_overrides.insert(
0,
(
CODE_MODE_HOST_PATH_ENV_VAR.to_string(),
Some(code_mode_host_program.to_string_lossy().into_owned()),
),
);
}
let program = match program {
Some(program) => program,
None => codex_utils_cargo_bin::cargo_bin("codex-app-server")
@@ -1958,6 +1904,7 @@ impl TestAppServerBuilder {
.await?;
app_server.auto_env = auto_env;
app_server._owned_codex_home = owned_codex_home;
app_server._delayed_exec_server = delayed_exec_server;
Ok(app_server)
}
}
@@ -29,6 +29,7 @@ use codex_thread_store::InMemoryThreadStore;
use codex_thread_store::ThreadPersistenceMetadata;
use codex_thread_store::ThreadStore;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::test_path_buf;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::path::PathBuf;
@@ -53,7 +54,7 @@ fn expected_summary(conversation_id: ThreadId, path: PathBuf) -> ConversationSum
timestamp: Some(CREATED_AT_RFC3339.to_string()),
updated_at: Some(UPDATED_AT_RFC3339.to_string()),
model_provider: MODEL_PROVIDER.to_string(),
cwd: PathBuf::from("/"),
cwd: test_path_buf("/"),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
git_info: None,
@@ -511,7 +511,6 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -538,7 +537,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
.await??;
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
.send_thread_start_request_with_auto_env(codex_app_server_protocol::ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -623,7 +622,6 @@ async fn external_auth_refresh_error_fails_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -650,7 +648,7 @@ async fn external_auth_refresh_error_fails_turn() -> Result<()> {
.await??;
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
.send_thread_start_request_with_auto_env(codex_app_server_protocol::ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -751,7 +749,6 @@ async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -778,7 +775,7 @@ async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> {
.await??;
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
.send_thread_start_request_with_auto_env(codex_app_server_protocol::ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -872,7 +869,6 @@ async fn external_auth_refresh_invalid_access_token_fails_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -899,7 +895,7 @@ async fn external_auth_refresh_invalid_access_token_fails_turn() -> Result<()> {
.await??;
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
.send_thread_start_request_with_auto_env(codex_app_server_protocol::ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -206,7 +206,11 @@ async fn list_apps_uses_external_chatgpt_auth() -> Result<()> {
let codex_home = TempDir::new()?;
write_connectors_config(codex_home.path(), &server_url)?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let login_id = mcp
.send_chatgpt_auth_tokens_login_request(
@@ -69,7 +69,6 @@ async fn attestation_generate_round_trip_adds_header_to_responses_websocket_hand
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -95,7 +94,7 @@ async fn attestation_generate_round_trip_adds_header_to_responses_websocket_hand
};
let thread_request_id = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
@@ -10,14 +10,53 @@ use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput as V2UserInput;
use core_test_support::responses;
use core_test_support::skip_if_host_windows;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::time::Duration;
use std::time::Instant;
use tempfile::TempDir;
use tokio::time::timeout;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
#[tokio::test]
async fn builder_interposes_fixed_delay_for_auto_env() -> Result<()> {
skip_if_host_windows!(Ok(()));
skip_if_remote!(Ok(()), "the fixed-delay fixture is local-only");
let codex_home = TempDir::new()?;
let requested_delay = Duration::from_secs(1);
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_exec_server_delay(requested_delay)
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
assert_eq!(
mcp.auto_env_params()?.environment_id,
codex_exec_server::REMOTE_ENVIRONMENT_ID
);
let thread_start = Instant::now();
let request_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let _: JSONRPCResponse = timeout(
Duration::from_secs(60),
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let elapsed = thread_start.elapsed();
assert!(
elapsed >= requested_delay,
"thread/start completed in {elapsed:?}, below the requested {requested_delay:?} delay"
);
Ok(())
}
#[tokio::test]
async fn thread_start_with_auto_env_exposes_fixture_cwd_to_model() -> Result<()> {
let server = responses::start_mock_server().await;
@@ -83,7 +83,6 @@ async fn auto_compaction_local_emits_started_and_completed_items() -> Result<()>
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -170,7 +169,6 @@ async fn auto_compaction_remote_emits_started_and_completed_items() -> Result<()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -281,7 +279,6 @@ async fn thread_compact_start_triggers_compaction_and_returns_empty_response() -
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -335,7 +332,6 @@ async fn thread_compact_start_rejects_invalid_thread_id() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -375,7 +371,6 @@ async fn thread_compact_start_rejects_unknown_thread_id() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -399,7 +394,7 @@ async fn thread_compact_start_rejects_unknown_thread_id() -> Result<()> {
async fn start_thread(mcp: &mut TestAppServer) -> Result<String> {
let thread_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -178,6 +178,7 @@ HTTP_PROXY = {http_proxy}
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
// This suite owns environments.toml to exercise explicit executor selection.
.without_auto_env()
.build()
.await?;
@@ -13,6 +13,7 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
use codex_utils_path_uri::PathUri;
use core_test_support::responses;
use core_test_support::skip_if_remote;
use tempfile::TempDir;
use tokio::time::timeout;
@@ -23,6 +24,12 @@ const LOCAL_SKILL_MARKER: &str = "LOCAL_SKILL_BODY_MARKER";
#[tokio::test]
async fn selected_executor_root_exposes_plugin_skill() -> Result<()> {
// TODO(anp): Remove after selected capability-root fixtures can be materialized in remote exec.
skip_if_remote!(
Ok(()),
"selected capability root fixture is only materialized on the host"
);
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
@@ -83,13 +90,12 @@ stream_max_retries = 0
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
selected_capability_roots: Some(vec![SelectedCapabilityRoot {
id: "demo-plugin@1".to_string(),
@@ -253,7 +253,6 @@ async fn thread_start_mock_field_requires_experimental_api_capability() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
let init = mcp
@@ -296,7 +295,6 @@ async fn thread_start_without_dynamic_tools_allows_without_experimental_api_capa
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
let init = mcp
@@ -338,7 +336,6 @@ async fn thread_start_granular_approval_policy_requires_experimental_api_capabil
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
let init = mcp
@@ -206,14 +206,13 @@ memories = true
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
..Default::default()
})
@@ -615,6 +615,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
let control_request = "<ide_selection>src/auth.rs:1-5</ide_selection>";
let first_request = "Fix auth flow";
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
std::fs::write(
@@ -624,7 +626,14 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
"type": "user",
"cwd": &project_root,
"timestamp": &recent_timestamp,
"message": { "content": "first request" },
"message": { "content": control_request },
})
.to_string(),
serde_json::json!({
"type": "user",
"cwd": &project_root,
"timestamp": &recent_timestamp,
"message": { "content": first_request },
})
.to_string(),
serde_json::json!({
@@ -634,11 +643,6 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
"message": { "content": "first answer" },
})
.to_string(),
serde_json::json!({
"type": "custom-title",
"customTitle": "source session title",
})
.to_string(),
]
.join("\n"),
)?;
@@ -667,6 +671,14 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
.await??;
let detected: ExternalAgentConfigDetectResponse = to_response(response)?;
assert_eq!(detected.items.len(), 1);
assert_eq!(
detected.items[0]
.details
.as_ref()
.and_then(|details| details.sessions.first())
.and_then(|session| session.title.as_deref()),
Some("Fix auth flow")
);
let request_id = mcp
.send_raw_request(
@@ -743,8 +755,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
.expect("expected imported thread")
.clone();
assert_eq!(imported_thread_id, thread.id.to_string());
assert_eq!(thread.preview, "first request");
assert_eq!(thread.name.as_deref(), Some("source session title"));
assert_eq!(thread.preview, control_request);
assert_eq!(thread.name.as_deref(), Some("Fix auth flow"));
let request_id = mcp
.send_thread_read_request(ThreadReadParams {
@@ -758,13 +770,39 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
)
.await??;
let response: ThreadReadResponse = to_response(response)?;
assert_eq!(response.thread.turns.len(), 1);
let items = &response.thread.turns[0].items;
assert_eq!(items.len(), 3);
assert_eq!(response.thread.turns.len(), 2);
let control_items = &response.thread.turns[0].items;
assert_eq!(control_items.len(), 1);
match &control_items[0] {
ThreadItem::UserMessage { content, .. } => {
assert_eq!(
content,
&vec![UserInput::Text {
text: control_request.to_string(),
text_elements: Vec::new(),
}]
);
}
other => panic!("expected user message item, got {other:?}"),
}
let imported_items = &response.thread.turns[1].items;
assert_eq!(imported_items.len(), 3);
match &imported_items[0] {
ThreadItem::UserMessage { content, .. } => {
assert_eq!(
content,
&vec![UserInput::Text {
text: first_request.to_string(),
text_elements: Vec::new(),
}]
);
}
other => panic!("expected user message item, got {other:?}"),
}
assert_eq!(
items.last(),
imported_items.last(),
Some(&ThreadItem::AgentMessage {
id: "item-3".into(),
id: "item-4".into(),
text: "<EXTERNAL SESSION IMPORTED>".into(),
phase: None,
memory_citation: None,
@@ -818,8 +856,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
)
.await??;
let response: ThreadReadResponse = to_response(response)?;
assert_eq!(response.thread.turns.len(), 2);
match &response.thread.turns[1].items[1] {
assert_eq!(response.thread.turns.len(), 3);
match &response.thread.turns[2].items[1] {
ThreadItem::AgentMessage { text, .. } => assert_eq!(text, "follow-up answer"),
other => panic!("expected agent message item, got {other:?}"),
}
@@ -26,6 +26,7 @@ use codex_core::config::set_project_trust_level;
use codex_protocol::config_types::TrustLevel;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::skip_if_host_windows;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use serde::Serialize;
use tempfile::TempDir;
@@ -137,7 +138,6 @@ async fn hooks_list_shows_discovered_hook() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -309,7 +309,6 @@ async fn hooks_list_warms_plugin_capabilities_for_thread_start() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -328,7 +327,7 @@ async fn hooks_list_warms_plugin_capabilities_for_thread_start() -> Result<()> {
std::fs::remove_file(plugin_mcp_path)?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let _: ThreadStartResponse = to_response(
timeout(
@@ -680,6 +679,8 @@ async fn config_batch_write_toggles_user_hook() -> Result<()> {
#[tokio::test]
async fn config_batch_write_updates_hook_trust_for_loaded_session() -> Result<()> {
skip_if_host_windows!(Ok(()));
// TODO(anp): Teach command-hook fixtures to run in selected remote environments.
skip_if_remote!(Ok(()), "command hooks use host-local script and log paths");
let responses = vec![
create_final_assistant_message_sse_response("Warmup")?,
@@ -737,7 +738,6 @@ command = "python3 {hook_script_path}"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -757,7 +757,7 @@ command = "python3 {hook_script_path}"
assert_eq!(hook.trust_status, HookTrustStatus::Untrusted);
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -935,6 +935,8 @@ command = "python3 {hook_script_path}"
#[tokio::test]
async fn config_batch_write_disables_hook_for_loaded_session() -> Result<()> {
skip_if_host_windows!(Ok(()));
// TODO(anp): Teach command-hook fixtures to run in selected remote environments.
skip_if_remote!(Ok(()), "command hooks use host-local script and log paths");
let responses = vec![
create_final_assistant_message_sse_response("Warmup")?,
@@ -991,7 +993,6 @@ command = "python3 {hook_script_path}"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -1034,7 +1035,7 @@ command = "python3 {hook_script_path}"
let _: codex_app_server_protocol::ConfigWriteResponse = to_response(response)?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -19,6 +19,7 @@ use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use core_test_support::responses;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
@@ -90,7 +91,6 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -192,7 +192,6 @@ async fn standalone_image_generation_failure_emits_terminal_item() -> Result<()>
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -236,6 +235,11 @@ async fn standalone_image_generation_failure_emits_terminal_item() -> Result<()>
#[tokio::test]
async fn standalone_image_edit_uses_attached_model_visible_image() -> Result<()> {
skip_if_remote!(
Ok(()),
"remote executors use different imagegen storage approaches, so host-local image paths are unavailable"
);
let edit_request = run_image_edit_test(|codex_home| {
let image_path = codex_home.join("attached.png");
std::fs::write(&image_path, TINY_PNG_BYTES)?;
@@ -317,7 +321,6 @@ async fn standalone_image_generation_is_exposed_in_code_mode_only() -> Result<()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -384,7 +387,6 @@ generatedImage(result);
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -468,7 +470,6 @@ async fn run_image_edit_test(
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -499,7 +500,7 @@ async fn run_image_edit_test(
async fn start_turn(mcp: &mut TestAppServer, input: Vec<V2UserInput>) -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
@@ -588,7 +589,6 @@ model_provider = "openai-custom"
chatgpt_base_url = "{server_uri}"
[features]
imagegenext = true
{code_mode_only}
[model_providers.openai-custom]
@@ -89,11 +89,15 @@ async fn mcp_resource_read_returns_resource_contents() -> Result<()> {
let (apps_server_url, _apps_server_calls, apps_server_handle) =
start_resource_apps_mcp_server().await?;
let responses_server_uri = responses_server.uri();
let (_codex_home, mut mcp) =
start_resource_test_app_server(&apps_server_url, &responses_server_uri).await?;
let (_codex_home, mut mcp) = start_resource_test_app_server(
&apps_server_url,
&responses_server_uri,
ResourceTestEnvironment::Auto,
)
.await?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -133,8 +137,12 @@ async fn orchestrator_skill_can_read_referenced_resource_without_an_executor() -
let (apps_server_url, apps_server_calls, apps_server_handle) =
start_resource_apps_mcp_server().await?;
let responses_server_uri = responses_server.uri();
let (_codex_home, mut mcp) =
start_resource_test_app_server(&apps_server_url, &responses_server_uri).await?;
let (_codex_home, mut mcp) = start_resource_test_app_server(
&apps_server_url,
&responses_server_uri,
ResourceTestEnvironment::Auto,
)
.await?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -369,8 +377,13 @@ async fn local_executor_does_not_expose_orchestrator_skills() -> Result<()> {
let (apps_server_url, _apps_server_calls, apps_server_handle) =
start_resource_apps_mcp_server().await?;
let responses_server_uri = responses_server.uri();
let (_codex_home, mut mcp) =
start_resource_test_app_server(&apps_server_url, &responses_server_uri).await?;
let (_codex_home, mut mcp) = start_resource_test_app_server(
&apps_server_url,
&responses_server_uri,
// This test exercises the implicit local executor.
ResourceTestEnvironment::Local,
)
.await?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -449,13 +462,13 @@ async fn disabled_orchestrator_skills_do_not_expose_skills_namespace() -> Result
[orchestrator.skills]
enabled = false
"#,
ResourceTestEnvironment::Auto,
)
.await?;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
environments: Some(Vec::new()),
..Default::default()
})
.await?;
@@ -648,15 +661,22 @@ async fn mcp_resource_read_returns_error_for_unknown_thread() -> Result<()> {
async fn start_resource_test_app_server(
apps_server_url: &str,
responses_server_uri: &str,
environment: ResourceTestEnvironment,
) -> Result<(TempDir, TestAppServer)> {
start_resource_test_app_server_with_extra_config(apps_server_url, responses_server_uri, "")
.await
start_resource_test_app_server_with_extra_config(
apps_server_url,
responses_server_uri,
"",
environment,
)
.await
}
async fn start_resource_test_app_server_with_extra_config(
apps_server_url: &str,
responses_server_uri: &str,
extra_config: &str,
environment: ResourceTestEnvironment,
) -> Result<(TempDir, TestAppServer)> {
let codex_home = TempDir::new()?;
std::fs::write(
@@ -696,15 +716,22 @@ stream_max_retries = 0
AuthCredentialsStoreMode::File,
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
let builder = TestAppServer::builder().with_codex_home(codex_home.path());
let builder = match environment {
ResourceTestEnvironment::Auto => builder,
// The Local caller explicitly exercises the implicit local executor.
ResourceTestEnvironment::Local => builder.without_auto_env(),
};
let mut mcp = builder.build().await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
Ok((codex_home, mcp))
}
enum ResourceTestEnvironment {
Auto,
Local,
}
async fn start_resource_apps_mcp_server()
-> Result<(String, Arc<ResourceAppsMcpCalls>, JoinHandle<()>)> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
@@ -138,13 +138,12 @@ async fn mcp_server_status_list_uses_thread_project_local_config() -> Result<()>
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().to_string_lossy().into_owned()),
..Default::default()
})
@@ -348,6 +348,7 @@ url = "{mcp_server_url}/mcp"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// This test adds and refreshes an explicitly selected runtime environment.
.without_auto_env()
.build()
.await?;
@@ -56,6 +56,7 @@ use core_test_support::responses::WebSocketTestServer;
use core_test_support::responses::start_websocket_server;
use core_test_support::responses::start_websocket_server_with_headers;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use serde::de::DeserializeOwned;
use serde_json::Value;
@@ -293,14 +294,13 @@ impl RealtimeE2eHarness {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
login_with_api_key(&mut mcp, "sk-test-key").await?;
let thread_start_request_id = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread_start_response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
@@ -1173,7 +1173,6 @@ async fn realtime_list_voices_returns_supported_names() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -2520,6 +2519,11 @@ async fn websocket_v2_background_agent_progress_is_sent_before_function_output()
#[tokio::test]
async fn websocket_v2_tool_call_delegated_turn_can_execute_shell_tool() -> Result<()> {
// TODO(anp): Remove after delegated shell commands resolve target-native cwd in remote environments.
skip_if_remote!(
Ok(()),
"delegated shell command cwd is only materialized on the host"
);
skip_if_no_network!(Ok(()));
// Phase 1: keep the two mocked OpenAI conversations explicit. The realtime sideband only
@@ -74,7 +74,6 @@ async fn first_turn_after_external_login_waits_for_recommended_plugins() -> Resu
let sqlite_home = codex_home.path().to_string_lossy();
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.with_env_overrides(&[("CODEX_SQLITE_HOME", Some(sqlite_home.as_ref()))])
.build()
@@ -105,7 +104,7 @@ async fn first_turn_after_external_login_waits_for_recommended_plugins() -> Resu
);
let thread_id = app_server
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
+4 -4
View File
@@ -113,8 +113,8 @@ async fn review_start_runs_review_turn_and_emits_code_review_item() -> Result<()
let started: ItemStartedNotification =
serde_json::from_value(item_started.params.expect("params must be present"))?;
match started.item {
ThreadItem::EnteredReviewMode { id, review } => {
assert_eq!(id, turn_id);
ThreadItem::EnteredReviewMode { review, .. } => {
assert_eq!(started.turn_id, turn_id);
assert_eq!(review, "commit 1234567: Tidy UI colors");
saw_entered_review_mode = true;
break;
@@ -139,8 +139,8 @@ async fn review_start_runs_review_turn_and_emits_code_review_item() -> Result<()
let completed: ItemCompletedNotification =
serde_json::from_value(review_notif.params.expect("params must be present"))?;
match completed.item {
ThreadItem::ExitedReviewMode { id, review } => {
assert_eq!(id, turn_id);
ThreadItem::ExitedReviewMode { review, .. } => {
assert_eq!(completed.turn_id, turn_id);
review_body = Some(review);
break;
}
@@ -142,6 +142,7 @@ async fn selected_capability_stack_tracks_environment_availability_and_resume()
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
// This fixture owns environments.toml and selects its environments explicitly.
.without_auto_env()
.build()
.await?;
@@ -192,6 +193,7 @@ async fn selected_capability_stack_tracks_environment_availability_and_resume()
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
// This fixture owns environments.toml and selects its environments explicitly.
.without_auto_env()
.build()
.await?;
@@ -343,6 +345,7 @@ async fn selected_capabilities_become_available_between_samples_in_one_turn() ->
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
// This fixture owns environments.toml and selects its environments explicitly.
.without_auto_env()
.build()
.await?;
@@ -24,6 +24,7 @@ use codex_app_server_protocol::ThreadStartParams;
use codex_config::types::AuthCredentialsStoreMode;
use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::time::timeout;
@@ -874,6 +875,12 @@ async fn skills_extra_roots_set_updates_process_runtime_roots() -> Result<()> {
#[tokio::test]
async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<()> {
// TODO(anp): Remove after skill watching can bridge host-local storage into remote exec.
skip_if_remote!(
Ok(()),
"host-local skill changes are not visible to remote executors"
);
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
write_mock_responses_config_toml_with_chatgpt_base_url(
@@ -885,8 +892,6 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[(CODEX_EXEC_SERVER_URL_ENV_VAR, None)])
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -911,7 +916,7 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
);
let thread_start_request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: None,
model_provider: None,
allow_provider_model_fallback: false,
@@ -120,7 +120,6 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -263,13 +262,12 @@ async fn thread_fork_at_last_turn_id_keeps_only_terminal_prefix() -> Result<()>
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
@@ -52,7 +52,6 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs
async fn init_mcp(codex_home: &Path) -> Result<TestAppServer> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -261,7 +260,7 @@ async fn thread_list_reports_system_error_idle_flag_after_failed_turn() -> Resul
let mut mcp = init_mcp(codex_home.path()).await?;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -14,6 +14,7 @@ use app_test_support::test_absolute_path;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use chrono::Utc;
use codex_app_server_protocol::ApprovalsReviewer;
use codex_app_server_protocol::AskForApproval;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::CommandExecutionApprovalDecision;
@@ -42,6 +43,8 @@ use codex_app_server_protocol::ThreadReadResponse;
use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadSettingsUpdateParams;
use codex_app_server_protocol::ThreadSettingsUpdateResponse;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
@@ -85,6 +88,8 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::LegacyAppPathString;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
use core_test_support::skip_if_wine_exec;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::fs::FileTimes;
@@ -269,6 +274,11 @@ async fn thread_resume_with_empty_path_uses_running_thread_id() -> Result<()> {
#[tokio::test]
async fn thread_resume_running_thread_uses_cached_instruction_sources() -> Result<()> {
skip_if_remote!(
Ok(()),
"cached instruction-source fixture is outside the selected remote cwd"
);
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
@@ -278,6 +288,7 @@ async fn thread_resume_running_thread_uses_cached_instruction_sources() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// TODO(anp): Move the cached instruction-source fixture into the auto environment cwd.
.without_auto_env()
.build()
.await?;
@@ -360,13 +371,12 @@ async fn turn_start_updates_runtime_workspace_roots_for_loaded_thread() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -429,6 +439,192 @@ async fn turn_start_updates_runtime_workspace_roots_for_loaded_thread() -> Resul
Ok(())
}
#[tokio::test]
async fn thread_resume_preserves_persisted_approvals_reviewer() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let thread_id = {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "materialize this thread".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
thread.id
};
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
config.replace(
"approval_policy = \"never\"\n",
"approval_policy = \"never\"\napprovals_reviewer = \"user\"\n",
),
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id,
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let ThreadResumeResponse {
approvals_reviewer, ..
} = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(approvals_reviewer, ApprovalsReviewer::AutoReview);
Ok(())
}
#[tokio::test]
async fn thread_resume_preserves_acknowledged_approvals_reviewer_update() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let thread_id = {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "materialize this thread".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let update_id = mcp
.send_thread_settings_update_request(ThreadSettingsUpdateParams {
thread_id: thread.id.clone(),
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
..Default::default()
})
.await?;
let update_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(update_id)),
)
.await??;
let _: ThreadSettingsUpdateResponse = to_response(update_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/settings/updated"),
)
.await??;
thread.id
};
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id,
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let ThreadResumeResponse {
approvals_reviewer, ..
} = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(approvals_reviewer, ApprovalsReviewer::AutoReview);
Ok(())
}
#[tokio::test]
async fn thread_goal_get_rejects_unmaterialized_thread() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -443,14 +639,13 @@ async fn thread_goal_get_rejects_unmaterialized_thread() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
ephemeral: Some(true),
..Default::default()
@@ -507,7 +702,6 @@ async fn goal_first_live_thread_appears_in_state_db_thread_list() -> Result<()>
.expect("test codex home should be utf-8");
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home_path)
.without_auto_env()
.without_managed_config()
.with_env_overrides(&[("CODEX_SQLITE_HOME", Some(sqlite_home))])
.build()
@@ -515,7 +709,7 @@ async fn goal_first_live_thread_appears_in_state_db_thread_list() -> Result<()>
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -605,7 +799,6 @@ async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
@@ -636,7 +829,7 @@ async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> {
&thread.id,
&thread.session_id,
"codex_work_desktop",
"gpt-5.3-codex",
"gpt-5.4",
"resumed",
"user",
);
@@ -654,14 +847,13 @@ async fn thread_resume_running_thread_tracks_thread_originator_in_analytics() ->
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
thread_source: Some(ThreadSource::User),
service_name: Some("codex_work_desktop".to_string()),
@@ -778,7 +970,6 @@ async fn thread_resume_returns_rollout_history() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -977,7 +1168,6 @@ async fn resume_redaction_fixture(client_name: Option<&str>) -> Result<ThreadRes
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
if let Some(client_name) = client_name {
@@ -1091,7 +1281,6 @@ async fn thread_resume_can_skip_turns_for_metadata_only_resume() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -1142,7 +1331,6 @@ async fn thread_resume_rejects_archived_session_by_id() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -1185,14 +1373,13 @@ async fn thread_resume_keeps_paused_goal_paused() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1295,14 +1482,13 @@ async fn thread_goal_set_preserves_budget_limited_same_objective() -> Result<()>
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1399,14 +1585,13 @@ async fn thread_goal_set_persists_resumable_stopped_statuses() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1499,7 +1684,6 @@ async fn thread_goal_set_edits_objective_without_resetting_usage() -> Result<()>
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
@@ -1616,14 +1800,13 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT.saturating_mul(2), mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1806,7 +1989,6 @@ async fn thread_resume_emits_restored_token_usage_before_next_turn() -> Result<(
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -1863,7 +2045,6 @@ async fn thread_resume_skips_restored_token_usage_when_turns_are_excluded() -> R
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -1975,7 +2156,6 @@ async fn thread_resume_token_usage_replay_ignores_stale_interrupted_tail_turn()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -2103,7 +2283,6 @@ async fn thread_resume_token_usage_replay_can_belong_to_interrupted_turn() -> Re
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -2153,7 +2332,7 @@ async fn thread_resume_prefers_persisted_git_metadata_for_local_threads() -> Res
&config_toml,
format!(
r#"
model = "gpt-5.3-codex"
model = "gpt-5.4"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -2301,7 +2480,6 @@ stream_max_retries = 0
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -2399,7 +2577,6 @@ async fn thread_resume_and_read_interrupt_incomplete_rollout_turn_when_thread_is
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -2477,7 +2654,6 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -2603,13 +2779,12 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> {
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -2646,7 +2821,6 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> {
let mut secondary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??;
@@ -2720,13 +2894,12 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> {
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -2843,13 +3016,12 @@ async fn thread_resume_rejects_mismatched_path_for_running_thread_id() -> Result
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -3016,13 +3188,12 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -3151,13 +3322,12 @@ async fn thread_resume_can_skip_turns_when_thread_is_running() -> Result<()> {
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -3193,7 +3363,6 @@ async fn thread_resume_can_skip_turns_when_thread_is_running() -> Result<()> {
let mut secondary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??;
@@ -3223,6 +3392,12 @@ async fn thread_resume_can_skip_turns_when_thread_is_running() -> Result<()> {
#[tokio::test]
async fn thread_resume_replays_pending_command_execution_request_approval() -> Result<()> {
// TODO(anp): Remove after shell approval replay can route target-native cwd across host OSes.
skip_if_wine_exec!(
Ok(()),
"shell approval replay rejects the Windows cwd on the Linux host"
);
let responses = vec![
create_final_assistant_message_sse_response("seeded")?,
create_shell_command_sse_response(
@@ -3243,13 +3418,12 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -3365,6 +3539,12 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
#[tokio::test]
async fn thread_resume_replays_pending_file_change_request_approval() -> Result<()> {
// TODO(anp): Remove after apply-patch approval fixtures use a target-native workspace.
skip_if_remote!(
Ok(()),
"apply-patch approval fixture is only materialized on the host"
);
let tmp = TempDir::new()?;
let codex_home = tmp.path().join("codex_home");
std::fs::create_dir(&codex_home)?;
@@ -3386,13 +3566,12 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result<
let mut primary = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -3611,7 +3790,6 @@ async fn thread_resume_fails_when_required_mcp_server_fails_to_initialize() -> R
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -3694,7 +3872,6 @@ async fn thread_resume_surfaces_cloud_config_bundle_load_errors() -> Result<()>
let refresh_token_url = format!("{}/oauth/token", server.uri());
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(
@@ -3789,7 +3966,6 @@ async fn thread_resume_can_load_source_by_external_path() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -3883,13 +4059,12 @@ async fn start_materialized_thread_and_restart(
) -> Result<RestartedThreadFixture> {
let mut first_mcp = TestAppServer::builder()
.with_codex_home(codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, first_mcp.initialize()).await??;
let start_id = first_mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
@@ -3946,7 +4121,6 @@ async fn start_materialized_thread_and_restart(
let mut second_mcp = TestAppServer::builder()
.with_codex_home(codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, second_mcp.initialize()).await??;
@@ -3981,14 +4155,13 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let mut primary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -4023,7 +4196,6 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let mut secondary = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??;
@@ -4031,7 +4203,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id,
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
personality: Some(Personality::Friendly),
..Default::default()
})
@@ -4094,7 +4266,7 @@ fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io
config_toml,
format!(
r#"
model = "gpt-5.3-codex"
model = "gpt-5.4"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -4124,7 +4296,7 @@ fn create_config_toml_with_chatgpt_base_url(
config_toml,
format!(
r#"
model = "gpt-5.3-codex"
model = "gpt-5.4"
approval_policy = "never"
sandbox_mode = "read-only"
chatgpt_base_url = "{chatgpt_base_url}"
@@ -4154,7 +4326,7 @@ fn create_config_toml_with_required_broken_mcp(
config_toml,
format!(
r#"
model = "gpt-5.3-codex"
model = "gpt-5.4"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -46,7 +46,6 @@ async fn thread_settings_update_emits_notification_and_updates_future_turns() ->
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -113,7 +112,6 @@ async fn thread_settings_update_cwd_retargets_default_environment() -> Result<()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -167,7 +165,6 @@ async fn thread_settings_update_while_turn_is_active_emits_notification() -> Res
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -214,7 +211,6 @@ async fn thread_settings_update_null_service_tier_uses_default() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -284,7 +280,6 @@ async fn thread_settings_update_rejects_sandbox_policy_with_permissions() -> Res
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -322,7 +317,6 @@ async fn turn_start_settings_override_emits_thread_settings_updated() -> Result<
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
@@ -402,7 +396,7 @@ async fn start_text_turn(mcp: &mut TestAppServer, thread_id: String) -> Result<(
async fn start_thread(mcp: &mut TestAppServer) -> Result<ThreadStartResponse> {
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -62,6 +62,7 @@ async fn thread_shell_command_history_responses_exclude_persisted_command_execut
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.as_path())
// thread/shellCommand intentionally executes on the app-server host.
.without_auto_env()
.build()
.await?;
@@ -199,6 +200,7 @@ async fn thread_shell_command_returns_error_when_local_environment_is_disabled()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.as_path())
// This test intentionally exercises thread/shellCommand without a local host environment.
.without_auto_env()
.with_env_overrides(&[(CODEX_EXEC_SERVER_URL_ENV_VAR, Some("none"))])
.build()
@@ -259,6 +261,7 @@ async fn thread_shell_command_uses_existing_active_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.as_path())
// thread/shellCommand intentionally joins the app-server's host-local active turn.
.without_auto_env()
.build()
.await?;
@@ -525,13 +525,12 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(cwd.to_string_lossy().to_string()),
runtime_workspace_roots: Some(vec![extra_root.abs()]),
..Default::default()
@@ -570,13 +569,12 @@ async fn thread_start_excludes_profile_workspace_roots_from_runtime_workspace_ro
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(cwd.path().to_string_lossy().to_string()),
..Default::default()
})
@@ -609,7 +607,6 @@ async fn thread_start_rejects_unknown_environment_as_invalid_request() -> Result
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -648,15 +645,15 @@ async fn thread_start_rejects_relative_environment_cwd_as_invalid_request() -> R
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let environment_id = mcp.auto_env_params()?.environment_id;
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
environments: Some(vec![TurnEnvironmentParams {
environment_id: "local".to_string(),
environment_id: environment_id.clone(),
cwd: serde_json::from_value(json!("relative"))?,
}]),
..Default::default()
@@ -672,7 +669,9 @@ async fn thread_start_rejects_relative_environment_cwd_as_invalid_request() -> R
assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(
error.error.message,
"invalid cwd for environment `local`: path `relative` does not use absolute POSIX or Windows path syntax"
format!(
"invalid cwd for environment `{environment_id}`: path `relative` does not use absolute POSIX or Windows path syntax"
)
);
Ok(())
@@ -691,6 +690,7 @@ async fn thread_start_response_includes_loaded_instruction_sources() -> Result<(
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// TODO(anp): Move the instruction-source fixture into the auto environment cwd.
.without_auto_env()
.build()
.await?;
@@ -742,6 +742,7 @@ async fn thread_start_response_excludes_empty_project_instruction_source() -> Re
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// TODO(anp): Move the instruction-source fixture into the auto environment cwd.
.without_auto_env()
.build()
.await?;
@@ -789,7 +790,6 @@ async fn thread_start_without_selected_environment_includes_only_global_instruct
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
@@ -883,14 +883,13 @@ async fn thread_start_tracks_thread_initialized_analytics() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
thread_source: Some(ThreadSource::User),
service_name: Some("codex_work_desktop".to_string()),
..Default::default()
@@ -938,13 +937,12 @@ model_reasoning_effort = "high"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().to_string_lossy().into_owned()),
..Default::default()
})
@@ -1294,7 +1292,6 @@ async fn thread_start_surfaces_cloud_config_bundle_load_errors() -> Result<()> {
let refresh_token_url = format!("{}/oauth/token", server.uri());
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(
@@ -1307,7 +1304,7 @@ async fn thread_start_surfaces_cloud_config_bundle_load_errors() -> Result<()> {
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let err: JSONRPCError = timeout(
@@ -1355,13 +1352,12 @@ model_reasoning_effort = "high"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let first_request = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
@@ -1374,7 +1370,7 @@ model_reasoning_effort = "high"
.await??;
let second_request = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
..Default::default()
})
@@ -1419,13 +1415,12 @@ async fn thread_start_with_nested_git_cwd_trusts_repo_root() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(nested.display().to_string()),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
@@ -1461,13 +1456,12 @@ async fn thread_start_with_read_only_sandbox_does_not_persist_project_trust() ->
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
..Default::default()
})
@@ -1503,13 +1497,12 @@ async fn thread_start_preserves_untrusted_project_trust() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
@@ -1548,13 +1541,12 @@ model_reasoning_effort = "high"
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
@@ -30,14 +30,13 @@ async fn thread_status_changed_emits_runtime_updates() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("RUST_LOG", Some("info"))])
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -44,12 +44,23 @@ async fn thread_unsubscribe_keeps_thread_loaded_until_idle_timeout() -> Result<(
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_id = start_thread(&mut mcp).await?;
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(thread_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(thread_resp)?;
let thread_id = thread.id;
let unsubscribe_id = mcp
.send_thread_unsubscribe_request(ThreadUnsubscribeParams {
@@ -99,8 +110,6 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running() -> Result<()> {
let tmp = TempDir::new()?;
let codex_home = tmp.path().join("codex_home");
std::fs::create_dir(&codex_home)?;
let working_directory = tmp.path().join("workdir");
std::fs::create_dir(&working_directory)?;
let (server, mut completions) = start_streaming_sse_server(vec![
vec![StreamingSseChunk {
@@ -127,13 +136,12 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
dynamic_tools: Some(vec![DynamicToolSpec::Function(DynamicToolFunctionSpec {
name: tool_name.to_string(),
@@ -164,7 +172,6 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running() -> Result<()> {
text: "run deterministic tool".to_string(),
text_elements: Vec::new(),
}],
cwd: Some(working_directory),
..Default::default()
})
.await?;
@@ -263,12 +270,23 @@ async fn thread_unsubscribe_preserves_cached_status_before_idle_unload() -> Resu
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_id = start_thread(&mut mcp).await?;
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(thread_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(thread_resp)?;
let thread_id = thread.id;
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
@@ -354,12 +372,23 @@ async fn thread_unsubscribe_reports_not_subscribed_before_idle_unload() -> Resul
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_id = start_thread(&mut mcp).await?;
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(thread_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(thread_resp)?;
let thread_id = thread.id;
let first_unsubscribe_id = mcp
.send_thread_unsubscribe_request(ThreadUnsubscribeParams {
@@ -434,19 +463,3 @@ stream_max_retries = 0
),
)
}
async fn start_thread(mcp: &mut TestAppServer) -> Result<String> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(req_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(resp)?;
Ok(thread.id)
}
@@ -22,6 +22,7 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput as V2UserInput;
use core_test_support::skip_if_remote;
use tempfile::TempDir;
use tokio::time::timeout;
@@ -30,6 +31,12 @@ const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
#[tokio::test]
async fn turn_interrupt_aborts_running_turn() -> Result<()> {
// TODO(anp): Remove after the long-running command fixture can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"uses a host-local command and cwd fixture unavailable to remote executors"
);
// Use a portable sleep command to keep the turn running.
#[cfg(target_os = "windows")]
let shell_command = vec![
@@ -59,14 +66,13 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
// Start a v2 thread and capture its id.
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -215,6 +221,12 @@ async fn turn_interrupt_rejects_completed_turn() -> Result<()> {
#[tokio::test]
async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<()> {
// TODO(anp): Remove after the approval command fixture can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"uses a host-local command and cwd fixture unavailable to remote executors"
);
#[cfg(target_os = "windows")]
let shell_command = vec![
"powershell".to_string(),
@@ -245,13 +257,12 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<()
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -80,6 +80,8 @@ use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
use codex_utils_absolute_path::test_support::PathExt;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
use core_test_support::skip_if_wine_exec;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
@@ -618,7 +620,6 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills(
let isolated_home = codex_home.path().to_string_lossy();
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[
("HOME", Some(isolated_home.as_ref())),
("USERPROFILE", Some(isolated_home.as_ref())),
@@ -628,7 +629,7 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills(
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
@@ -891,14 +892,13 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
thread_source: Some(ThreadSource::User),
service_name: Some("codex_work_desktop".to_string()),
@@ -1021,14 +1021,13 @@ async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<()
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1348,13 +1347,12 @@ async fn turn_start_rejects_unknown_environment_before_starting_turn() -> Result
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1581,7 +1579,7 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1670,7 +1668,7 @@ async fn turn_start_uses_thread_feature_overrides_for_request_user_input_tool_de
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
config: Some(HashMap::from([(
"features.default_mode_request_user_input".to_string(),
json!(true),
@@ -2140,7 +2138,7 @@ async fn turn_start_uses_migrated_pragmatic_personality_without_override_v2() ->
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -2214,6 +2212,11 @@ async fn turn_start_forwards_custom_local_image_detail() -> Result<()> {
#[tokio::test]
async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
// TODO(anp): Remove after shell-command approval routing supports target-native Windows cwd.
skip_if_wine_exec!(
Ok(()),
"shell-command approval routing requires a host-native cwd under Wine-exec"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -2256,14 +2259,14 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.as_path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let expected_environment_id = mcp.auto_env_params()?.environment_id;
// thread/start
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -2304,7 +2307,10 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
panic!("expected CommandExecutionRequestApproval request");
};
assert_eq!(params.item_id, "call1");
assert_eq!(params.environment_id.as_deref(), Some("local"));
assert_eq!(
params.environment_id.as_deref(),
Some(expected_environment_id.as_str())
);
let resolved_request_id = request_id.clone();
// Approve and wait for task completion
@@ -2376,12 +2382,15 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_exec_approval_decline_v2() -> Result<()> {
// TODO(anp): Remove after command approval routing accepts target-native Windows cwd.
skip_if_wine_exec!(
Ok(()),
"command approval routing rejects the selected Windows cwd on the Linux host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
let codex_home = tmp.path().to_path_buf();
let workspace = tmp.path().join("workspace");
std::fs::create_dir(&workspace)?;
let responses = vec![
create_shell_command_sse_response(
@@ -2406,13 +2415,12 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.as_path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -2432,7 +2440,6 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> {
text: "run python".to_string(),
text_elements: Vec::new(),
}],
cwd: Some(workspace.clone()),
..Default::default()
})
.await?;
@@ -2525,6 +2532,8 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> {
// TODO(anp): Materialize cwd and shell-display fixtures in the selected remote environment.
skip_if_remote!(Ok(()), "cwd fixtures are only materialized on the host");
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -2563,14 +2572,13 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
// thread/start
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -2761,13 +2769,12 @@ stream_max_retries = 0
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -2876,6 +2883,8 @@ url = "ws://127.0.0.1:1"
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
// This test owns environments.toml and explicitly compares local selections
// with a configured remote environment, so auto env would change its subject.
.without_auto_env()
.build()
.await?;
@@ -3008,6 +3017,11 @@ fn environment_params(ids: Option<&[&str]>, cwd: &Path) -> Option<Vec<TurnEnviro
#[tokio::test]
async fn turn_start_file_change_approval_v2() -> Result<()> {
// TODO(anp): Materialize apply-patch workspaces in the selected remote environment.
skip_if_remote!(
Ok(()),
"apply-patch workspace fixture is only materialized on the host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -3035,13 +3049,12 @@ async fn turn_start_file_change_approval_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -3181,6 +3194,11 @@ async fn turn_start_file_change_approval_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v2() -> Result<()> {
// TODO(anp): Materialize apply-patch workspaces in the selected remote environment.
skip_if_remote!(
Ok(()),
"apply-patch workspace fixture is only materialized on the host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -3230,13 +3248,12 @@ async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -3283,6 +3300,11 @@ async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v
#[tokio::test]
async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> {
// TODO(anp): Materialize apply-patch workspaces in the selected remote environment.
skip_if_remote!(
Ok(()),
"apply-patch workspace fixture is only materialized on the host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -3372,13 +3394,12 @@ async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -3514,7 +3535,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -3735,7 +3756,7 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -3916,7 +3937,7 @@ config_file = "./custom-role.toml"
let thread_req = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -4020,6 +4041,11 @@ config_file = "./custom-role.toml"
#[tokio::test]
async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Result<()> {
// TODO(anp): Materialize apply-patch workspaces in the selected remote environment.
skip_if_remote!(
Ok(()),
"apply-patch workspace fixture is only materialized on the host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -4057,13 +4083,12 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -4207,6 +4232,11 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res
#[tokio::test]
async fn turn_start_file_change_approval_decline_v2() -> Result<()> {
// TODO(anp): Materialize apply-patch workspaces in the selected remote environment.
skip_if_remote!(
Ok(()),
"apply-patch workspace fixture is only materialized on the host"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -4234,13 +4264,12 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -4367,6 +4396,11 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> {
#[tokio::test]
#[cfg_attr(windows, ignore = "process id reporting differs on Windows")]
async fn command_execution_notifications_include_process_id() -> Result<()> {
// TODO(anp): Add target-Windows process-id expectations for remote executors.
skip_if_wine_exec!(
Ok(()),
"process id reporting differs for a Windows executor"
);
skip_if_no_network!(Ok(()));
let responses = vec![
@@ -4385,13 +4419,12 @@ async fn command_execution_notifications_include_process_id() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -4523,13 +4556,12 @@ async fn turn_start_with_elevated_override_does_not_persist_project_trust() -> R
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_request = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
cwd: Some(workspace.path().display().to_string()),
..Default::default()
})
@@ -34,6 +34,7 @@ use codex_features::FEATURES;
use codex_features::Feature;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::path::Path;
@@ -48,6 +49,11 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs
#[tokio::test]
async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> {
// TODO(anp): Remove after zsh-fork fixtures can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"zsh-fork fixtures use host-local zsh and workspace paths"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -101,7 +107,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> {
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -177,6 +183,11 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
// TODO(anp): Remove after zsh-fork fixtures can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"zsh-fork fixtures use host-local zsh and workspace paths"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -220,7 +231,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -313,6 +324,11 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
// TODO(anp): Remove after zsh-fork fixtures can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"zsh-fork fixtures use host-local zsh and workspace paths"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -353,7 +369,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -444,6 +460,11 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
#[tokio::test]
async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() -> Result<()> {
// TODO(anp): Remove after zsh-fork fixtures can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"zsh-fork fixtures use host-local zsh and workspace paths"
);
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
@@ -512,7 +533,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -748,7 +769,6 @@ async fn create_zsh_test_mcp_process(
let zdotdir = zdotdir.to_string_lossy().into_owned();
TestAppServer::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_program(&app_server)
.with_env_overrides(&[("ZDOTDIR", Some(zdotdir.as_str()))])
.build()
@@ -26,6 +26,7 @@ use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::TurnSteerResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
use core_test_support::skip_if_remote;
use serde_json::Value;
use std::collections::HashMap;
use tempfile::TempDir;
@@ -52,14 +53,13 @@ async fn turn_steer_requires_active_turn() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -111,6 +111,12 @@ async fn turn_steer_requires_active_turn() -> Result<()> {
#[tokio::test]
async fn turn_steer_rejects_oversized_text_input() -> Result<()> {
// TODO(anp): Remove after the active-turn fixture can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"uses a host-local command and cwd fixture unavailable to remote executors"
);
#[cfg(target_os = "windows")]
let shell_command = vec![
"powershell".to_string(),
@@ -143,14 +149,13 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -228,6 +233,12 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> {
#[tokio::test]
async fn turn_steer_returns_active_turn_id() -> Result<()> {
// TODO(anp): Remove after the active-turn fixture can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"uses a host-local command and cwd fixture unavailable to remote executors"
);
#[cfg(target_os = "windows")]
let shell_command = vec![
"powershell".to_string(),
@@ -262,14 +273,13 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -379,6 +389,12 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> {
#[tokio::test]
async fn turn_steer_rejects_context_only_input_without_merging_context() -> Result<()> {
// TODO(anp): Remove after the active-turn fixture can run in the selected remote environment.
skip_if_remote!(
Ok(()),
"uses a host-local command and cwd fixture unavailable to remote executors"
);
let tmp = TempDir::new()?;
let codex_home = tmp.path().join("codex_home");
std::fs::create_dir(&codex_home)?;
@@ -404,14 +420,13 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.without_auto_env()
.without_managed_config()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -20,6 +20,7 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_app_server_protocol::WebSearchAction;
use codex_app_server_protocol::WebSearchItem;
use codex_config::types::AuthCredentialsStoreMode;
use core_test_support::responses;
use pretty_assertions::assert_eq;
@@ -80,14 +81,13 @@ async fn standalone_web_search_round_trips_output() -> Result<()> {
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
@@ -183,26 +183,25 @@ async fn standalone_web_search_round_trips_output() -> Result<()> {
);
assert_eq!(
started.item,
ThreadItem::WebSearch {
ThreadItem::WebSearch(WebSearchItem {
id: call_id.to_string(),
query: String::new(),
action: Some(WebSearchAction::Other),
}
action: None,
})
);
let expected_completed_item = ThreadItem::WebSearch {
let expected_completed_item = ThreadItem::WebSearch(WebSearchItem {
id: call_id.to_string(),
query: "standalone web search".to_string(),
action: Some(WebSearchAction::Search {
query: Some("standalone web search".to_string()),
queries: None,
}),
};
});
assert_eq!(completed.item, expected_completed_item);
drop(mcp);
let mut reloaded_mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build()
.await?;
@@ -223,7 +222,7 @@ async fn standalone_web_search_round_trips_output() -> Result<()> {
.turns
.iter()
.flat_map(|turn| &turn.items)
.filter(|item| matches!(item, ThreadItem::WebSearch { .. }))
.filter(|item| matches!(item, ThreadItem::WebSearch(_)))
.collect();
assert_eq!(persisted_web_searches, vec![&expected_completed_item]);
@@ -240,7 +239,7 @@ async fn wait_for_web_search_started(mcp: &mut TestAppServer) -> Result<ItemStar
.params
.context("item/started notification should include params")?,
)?;
if matches!(&started.item, ThreadItem::WebSearch { .. }) {
if matches!(&started.item, ThreadItem::WebSearch(_)) {
return Ok(started);
}
}
@@ -258,7 +257,7 @@ async fn wait_for_web_search_completed(
.params
.context("item/completed notification should include params")?,
)?;
if matches!(&completed.item, ThreadItem::WebSearch { .. }) {
if matches!(&completed.item, ThreadItem::WebSearch(_)) {
return Ok(completed);
}
}
+10
View File
@@ -797,6 +797,10 @@ fn installation_check(show_details: bool) -> DoctorCheck {
"managed by bun: {}",
env::var_os("CODEX_MANAGED_BY_BUN").is_some()
));
details.push(format!(
"managed by pnpm: {}",
env::var_os("CODEX_MANAGED_BY_PNPM").is_some()
));
push_env_path_detail(
&mut details,
"managed package root",
@@ -885,6 +889,7 @@ fn doctor_managed_by_npm(current_exe: Option<&Path>) -> bool {
fn inherited_managed_env_for_cargo_binary(current_exe: Option<&Path>) -> bool {
if env::var_os("CODEX_MANAGED_BY_NPM").is_none()
&& env::var_os("CODEX_MANAGED_BY_BUN").is_none()
&& env::var_os("CODEX_MANAGED_BY_PNPM").is_none()
{
return false;
}
@@ -937,6 +942,9 @@ fn describe_install_context(context: &InstallContext) -> String {
InstallMethod::Bun => {
describe_method_with_package_layout("bun", context.package_layout.as_ref())
}
InstallMethod::Pnpm => {
describe_method_with_package_layout("pnpm", context.package_layout.as_ref())
}
InstallMethod::Brew => {
describe_method_with_package_layout("brew", context.package_layout.as_ref())
}
@@ -2375,9 +2383,11 @@ async fn websocket_reachability_check(
HeaderValue::from_static(RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE),
);
let client = ResponsesWebsocketClient::new(api_provider, api_auth);
let http_client_factory = config.http_client_factory();
match tokio::time::timeout(
provider.websocket_connect_timeout(),
client.probe_handshake(
&http_client_factory,
extra_headers,
default_headers(),
WEBSOCKET_IMMEDIATE_CLOSE_GRACE,
+1 -1
View File
@@ -1260,7 +1260,7 @@ Environment
LESS -FRX
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · package root —
managed by npm: no · bun: no · pnpm: no · package root —
✓ search search is OK (bundled)
✓ git git version 2.54.0
selected git /usr/bin/git
+4 -1
View File
@@ -211,13 +211,15 @@ fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<
let managed_by_npm = value(parsed, "managed by npm").unwrap_or("false");
let managed_by_bun = value(parsed, "managed by bun").unwrap_or("false");
let managed_by_pnpm = value(parsed, "managed by pnpm").unwrap_or("false");
let package_root = value(parsed, "managed package root").unwrap_or("not set");
out.push(HumanDetail::Row {
label: "managed by".to_string(),
value: format!(
"npm: {} · bun: {} · package root {}",
"npm: {} · bun: {} · pnpm: {} · package root {}",
yes_no(managed_by_npm),
yes_no(managed_by_bun),
yes_no(managed_by_pnpm),
if is_falsy(package_root) {
"—".to_string()
} else {
@@ -263,6 +265,7 @@ fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<
"install context",
"managed by npm",
"managed by bun",
"managed by pnpm",
"managed package root",
"PATH codex entries",
],
+1
View File
@@ -121,6 +121,7 @@ fn install_method_name(context: &InstallContext) -> &'static str {
InstallMethod::Standalone { .. } => "standalone",
InstallMethod::Npm => "npm",
InstallMethod::Bun => "bun",
InstallMethod::Pnpm => "pnpm",
InstallMethod::Brew => "brew",
InstallMethod::Other => "local build",
}
@@ -21,7 +21,7 @@ Environment
LESS -FRX
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · package root —
managed by npm: no · bun: no · pnpm: no · package root —
✓ search search is OK (bundled)
✓ git git version 2.54.0
selected git /usr/bin/git
+9
View File
@@ -133,6 +133,7 @@ fn update_action_label(context: &InstallContext) -> &'static str {
match &context.method {
InstallMethod::Npm => "npm install -g @openai/codex",
InstallMethod::Bun => "bun install -g @openai/codex",
InstallMethod::Pnpm => "pnpm add -g @openai/codex",
InstallMethod::Brew => "brew upgrade --cask codex",
InstallMethod::Standalone { .. } => "standalone installer",
InstallMethod::Other => "manual or unknown",
@@ -144,6 +145,7 @@ fn fetch_latest_version(context: &InstallContext) -> Result<String, String> {
InstallMethod::Brew => fetch_homebrew_cask_version(),
InstallMethod::Npm
| InstallMethod::Bun
| InstallMethod::Pnpm
| InstallMethod::Standalone { .. }
| InstallMethod::Other => fetch_latest_github_release_version(),
}
@@ -223,6 +225,13 @@ mod tests {
}),
"npm install -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Pnpm,
package_layout: None,
}),
"pnpm add -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Other,
+4 -1
View File
@@ -2003,7 +2003,10 @@ async fn run_debug_models_command(
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ true).await;
let models_manager = build_models_manager(&config, auth_manager);
models_manager
.raw_model_catalog(RefreshStrategy::OnlineIfUncached)
.raw_model_catalog(
RefreshStrategy::OnlineIfUncached,
config.http_client_factory(),
)
.await
};
+1
View File
@@ -13,6 +13,7 @@ codex-client = { workspace = true }
codex-http-client = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
codex-websocket-client = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
reqwest = { workspace = true, features = ["json", "stream"] }
+21 -21
View File
@@ -37,9 +37,15 @@ impl<T: HttpTransport> ModelsClient<T> {
req.url = format!("{}{}client_version={client_version}", req.url, separator);
}
pub fn request_url(provider: &Provider, client_version: &str) -> String {
let mut request = provider.build_request(Method::GET, Self::path());
Self::append_client_version_query(&mut request, client_version);
request.url
}
pub async fn list_models(
&self,
client_version: &str,
request_url: String,
extra_headers: HeaderMap,
) -> Result<(Vec<ModelInfo>, Option<String>), ApiError> {
let resp = self
@@ -49,8 +55,8 @@ impl<T: HttpTransport> ModelsClient<T> {
Self::path(),
extra_headers,
/*body*/ None,
|req| {
Self::append_client_version_query(req, client_version);
move |req| {
req.url.clone_from(&request_url);
},
)
.await?;
@@ -161,14 +167,12 @@ mod tests {
etag: None,
};
let client = ModelsClient::new(
transport.clone(),
provider("https://example.com/api/codex"),
Arc::new(DummyAuth),
);
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport.clone(), provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models("0.99.0", HeaderMap::new())
.list_models(request_url, HeaderMap::new())
.await
.expect("request should succeed");
@@ -225,14 +229,12 @@ mod tests {
etag: None,
};
let client = ModelsClient::new(
transport,
provider("https://example.com/api/codex"),
Arc::new(DummyAuth),
);
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models("0.99.0", HeaderMap::new())
.list_models(request_url, HeaderMap::new())
.await
.expect("request should succeed");
@@ -252,14 +254,12 @@ mod tests {
etag: Some("\"abc\"".to_string()),
};
let client = ModelsClient::new(
transport,
provider("https://example.com/api/codex"),
Arc::new(DummyAuth),
);
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.1.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, etag) = client
.list_models("0.1.0", HeaderMap::new())
.list_models(request_url, HeaderMap::new())
.await
.expect("request should succeed");
@@ -11,8 +11,9 @@ use crate::sse::ResponsesStreamEvent;
use crate::sse::process_responses_event;
use crate::telemetry::WebsocketTelemetry;
use codex_client::TransportError;
use codex_http_client::maybe_build_rustls_client_config_with_custom_ca;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use codex_http_client::HttpClientFactory;
use codex_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderMap;
@@ -25,14 +26,10 @@ use serde_json::map::Map as JsonMap;
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::Instant;
use tokio_tungstenite::MaybeTlsStream;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::connect_async_tls_with_config;
use tokio_tungstenite::tungstenite::Error as WsError;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
@@ -62,7 +59,7 @@ enum WsCommand {
}
impl WsStream {
fn new(inner: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
fn new(inner: WebSocketConnection) -> Self {
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
let (tx_message, rx_message) = mpsc::unbounded_channel::<Result<Message, WsError>>();
@@ -334,6 +331,7 @@ impl ResponsesWebsocketClient {
)]
pub async fn connect(
&self,
http_client_factory: &HttpClientFactory,
extra_headers: HeaderMap,
default_headers: HeaderMap,
turn_state: Option<Arc<OnceLock<String>>>,
@@ -349,7 +347,7 @@ impl ResponsesWebsocketClient {
self.auth.add_auth_headers(&mut headers);
let (stream, _status, server_reasoning_included, models_etag, server_model) =
connect_websocket(ws_url, headers, turn_state.clone()).await?;
connect_websocket(ws_url, headers, http_client_factory, turn_state.clone()).await?;
Ok(ResponsesWebsocketConnection::new(
stream,
self.provider.stream_idle_timeout,
@@ -369,6 +367,7 @@ impl ResponsesWebsocketClient {
/// a usable connection from a policy rejection that closes right away.
pub async fn probe_handshake(
&self,
http_client_factory: &HttpClientFactory,
extra_headers: HeaderMap,
default_headers: HeaderMap,
immediate_close_timeout: Duration,
@@ -383,7 +382,13 @@ impl ResponsesWebsocketClient {
self.auth.add_auth_headers(&mut headers);
let (mut stream, status, reasoning_included, models_etag, server_model) =
connect_websocket(ws_url.clone(), headers, /*turn_state*/ None).await?;
connect_websocket(
ws_url.clone(),
headers,
http_client_factory,
/*turn_state*/ None,
)
.await?;
let immediate_close = tokio::time::timeout(immediate_close_timeout, stream.next())
.await
.ok()
@@ -437,9 +442,9 @@ fn merge_request_headers(
async fn connect_websocket(
url: Url,
headers: HeaderMap,
http_client_factory: &HttpClientFactory,
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<(WsStream, StatusCode, bool, Option<String>, Option<String>), ApiError> {
ensure_rustls_crypto_provider();
info!("connecting to websocket: {url}");
let mut request = url
@@ -448,20 +453,9 @@ async fn connect_websocket(
.map_err(|err| ApiError::Stream(format!("failed to build websocket request: {err}")))?;
request.headers_mut().extend(headers);
// Secure websocket traffic needs the same custom-CA policy as reqwest-based HTTPS traffic.
// If a Codex-specific CA bundle is configured, build an explicit rustls connector so this
// websocket path does not fall back to tungstenite's default native-roots-only behavior.
let connector = maybe_build_rustls_client_config_with_custom_ca()
.map_err(|err| ApiError::Stream(format!("failed to configure websocket TLS: {err}")))?
.map(tokio_tungstenite::Connector::Rustls);
let response = connect_async_tls_with_config(
request,
Some(websocket_config()),
false, // `false` means "do not disable Nagle", which is tungstenite's recommended default.
connector,
)
.await;
let connector = WebSocketConnector::new(http_client_factory)
.map_err(|err| ApiError::Stream(format!("failed to configure websocket TLS: {err}")))?;
let response = connector.connect(request, websocket_config()).await;
let (stream, response) = match response {
Ok((stream, response)) => {
@@ -118,10 +118,12 @@ async fn models_client_hits_models_endpoint() {
.await;
let transport = ReqwestTransport::new(reqwest::Client::new());
let client = ModelsClient::new(transport, provider(&base_url), Arc::new(DummyAuth));
let provider = provider(&base_url);
let request_url = ModelsClient::<ReqwestTransport>::request_url(&provider, "0.1.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models("0.1.0", HeaderMap::new())
.list_models(request_url, HeaderMap::new())
.await
.expect("models request should succeed");
+20 -2
View File
@@ -47,6 +47,7 @@ use codex_config::McpServerAuth;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::McpServerInfo;
@@ -141,6 +142,7 @@ impl McpConnectionManager {
supports_openai_form_elicitation: bool,
tool_plugin_provenance: ToolPluginProvenance,
auth: Option<&CodexAuth>,
codex_apps_auth_manager: Option<Arc<AuthManager>>,
elicitation_reviewer: Option<ElicitationReviewerHandle>,
elicitation_lifecycle: Option<crate::ElicitationLifecycle>,
elicitation_router: ElicitationRequestRouter,
@@ -163,9 +165,14 @@ impl McpConnectionManager {
);
let tool_plugin_provenance = Arc::new(tool_plugin_provenance);
let startup_submit_id = submit_id.clone();
let chatgpt_auth_provider = auth
let static_chatgpt_auth_provider = auth
.filter(|auth| auth.uses_codex_backend())
.map(codex_model_provider::auth_provider_from_auth);
let codex_apps_auth_provider = codex_apps_auth_manager.and_then(|auth_manager| {
auth.filter(|auth| auth.uses_codex_backend()).map(|auth| {
codex_model_provider::auth_provider_from_auth_manager(auth_manager, auth)
})
});
let mcp_servers = mcp_servers.clone();
for (server_name, server) in mcp_servers
.into_iter()
@@ -200,13 +207,24 @@ impl McpConnectionManager {
codex_apps_tools_cache
.context(codex_home.clone(), codex_apps_tools_cache_key.clone())
});
// The reserved Codex Apps registration follows the shared
// AuthManager across refreshes. In the hosted-plugin path, this
// is the ChatGPT /ps/mcp connection. User-configured MCP
// registrations keep their existing configured auth path.
let chatgpt_auth_provider = if server_name == CODEX_APPS_MCP_SERVER_NAME {
codex_apps_auth_provider
.clone()
.or_else(|| static_chatgpt_auth_provider.clone())
} else {
static_chatgpt_auth_provider.clone()
};
// If Codex Apps has an env bearer token, that is its auth path. Do
// not also attach the ambient CodexAuth provider.
let runtime_auth_provider =
if server_name == CODEX_APPS_MCP_SERVER_NAME && uses_env_bearer_token {
None
} else {
chatgpt_auth_provider_for_server(&server, chatgpt_auth_provider.clone())
chatgpt_auth_provider_for_server(&server, chatgpt_auth_provider)
};
let async_managed_client = AsyncManagedClient::new(
server_name.clone(),
@@ -1561,6 +1561,7 @@ async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
/*supports_openai_form_elicitation*/ false,
ToolPluginProvenance::default(),
/*auth*/ None,
/*codex_apps_auth_manager*/ None,
/*elicitation_reviewer*/ None,
/*elicitation_lifecycle*/ None,
ElicitationRequestRouter::default(),
+2
View File
@@ -338,6 +338,7 @@ pub async fn read_mcp_resource(
/*supports_openai_form_elicitation*/ false,
tool_plugin_provenance(config),
auth,
/*codex_apps_auth_manager*/ None,
/*elicitation_reviewer*/ None,
/*elicitation_lifecycle*/ None,
crate::elicitation::ElicitationRequestRouter::default(),
@@ -416,6 +417,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
/*supports_openai_form_elicitation*/ false,
tool_plugin_provenance,
auth,
/*codex_apps_auth_manager*/ None,
/*elicitation_reviewer*/ None,
/*elicitation_lifecycle*/ None,
crate::elicitation::ElicitationRequestRouter::default(),
+1
View File
@@ -21,6 +21,7 @@ codex-config = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-home = { workspace = true }
codex-image-generation-extension = { workspace = true }
codex-exec-server = { workspace = true }
codex-features = { workspace = true }
codex-login = { workspace = true }
+2
View File
@@ -61,6 +61,7 @@ pub use codex_exec_server::NoiseChannelIdentity;
pub use codex_exec_server::NoiseChannelPublicKey;
pub use codex_exec_server::NoiseRendezvousConnectBundle;
pub use codex_exec_server::NoiseRendezvousConnectProvider;
pub use codex_extension_api::ExtensionRegistryBuilder;
pub use codex_extension_api::LoadUserInstructionsFuture;
pub use codex_extension_api::LoadedUserInstructions;
pub use codex_extension_api::UserInstructions;
@@ -69,6 +70,7 @@ pub use codex_extension_api::empty_extension_registry;
pub use codex_features::Feature;
pub use codex_features::Features;
pub use codex_home::CodexHomeUserInstructionsProvider;
pub use codex_image_generation_extension::install as install_image_generation_extension;
pub use codex_login::AuthHeaders;
pub use codex_login::AuthManager;
pub use codex_login::CodexAuth;
+3
View File
@@ -50,6 +50,9 @@ tracing = { workspace = true }
url = { workspace = true }
zip = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
which = { workspace = true }
[dev-dependencies]
libc = { workspace = true }
pretty_assertions = { workspace = true }
+52 -14
View File
@@ -93,9 +93,17 @@ fn curated_plugins_sha_path(codex_home: &Path) -> PathBuf {
}
pub fn sync_openai_plugins_repo(codex_home: &Path) -> Result<String, String> {
#[cfg(target_os = "macos")]
let git_binary = match which::which("git") {
Ok(git_path) => macos_git_binary_from_path(git_path, apple_developer_tools_available()),
Err(_) => None,
};
#[cfg(not(target_os = "macos"))]
let git_binary = Some(PathBuf::from("git"));
sync_openai_plugins_repo_with_transport_overrides(
codex_home,
"git",
git_binary.as_deref(),
GITHUB_API_BASE_URL,
CURATED_PLUGINS_BACKUP_ARCHIVE_API_URL,
)
@@ -103,13 +111,18 @@ pub fn sync_openai_plugins_repo(codex_home: &Path) -> Result<String, String> {
fn sync_openai_plugins_repo_with_transport_overrides(
codex_home: &Path,
git_binary: &str,
git_binary: Option<&Path>,
api_base_url: &str,
backup_archive_api_url: &str,
) -> Result<String, String> {
let _file_guard = lock_curated_plugins_startup_sync(codex_home)?;
match sync_openai_plugins_repo_via_git(codex_home, git_binary) {
let git_sync_result = match git_binary {
Some(git_binary) => sync_openai_plugins_repo_via_git(codex_home, git_binary),
None => Err("git executable is unavailable".to_string()),
};
match git_sync_result {
Ok(remote_sha) => {
emit_curated_plugins_startup_sync_metric("git", "success");
emit_curated_plugins_startup_sync_final_metric("git", "success");
@@ -119,7 +132,6 @@ fn sync_openai_plugins_repo_with_transport_overrides(
emit_curated_plugins_startup_sync_metric("git", "failure");
warn!(
error = %err,
git_binary,
"git sync failed for curated plugin sync; falling back to GitHub HTTP"
);
match sync_openai_plugins_repo_via_http(codex_home, api_base_url) {
@@ -182,7 +194,10 @@ fn lock_curated_plugins_startup_sync(codex_home: &Path) -> Result<File, String>
Ok(lock_file)
}
fn sync_openai_plugins_repo_via_git(codex_home: &Path, git_binary: &str) -> Result<String, String> {
fn sync_openai_plugins_repo_via_git(
codex_home: &Path,
git_binary: &Path,
) -> Result<String, String> {
let repo_path = curated_plugins_repo_path(codex_home);
let sha_path = codex_home.join(CURATED_PLUGINS_SHA_FILE);
let remote_sha = git_ls_remote_head_sha(git_binary)?;
@@ -229,7 +244,7 @@ fn sync_openai_plugins_repo_via_git(codex_home: &Path, git_binary: &str) -> Resu
fn fetch_curated_plugins_commit(
repo_path: &Path,
remote_sha: &str,
git_binary: &str,
git_binary: &Path,
) -> Result<(), String> {
fetch_curated_plugins_commit_from(
repo_path,
@@ -244,7 +259,7 @@ fn fetch_curated_plugins_commit_from_source(
repo_path: &Path,
source_repo_path: &Path,
remote_sha: &str,
git_binary: &str,
git_binary: &Path,
) -> Result<(), String> {
fetch_curated_plugins_commit_from(
repo_path,
@@ -259,7 +274,7 @@ fn fetch_curated_plugins_commit_from(
repo_path: &Path,
source: &Path,
source_revision: &str,
git_binary: &str,
git_binary: &Path,
context: &str,
) -> Result<(), String> {
let fetch_refspec = format!("+{source_revision}:{CURATED_PLUGINS_FETCH_REF}");
@@ -274,7 +289,7 @@ fn fetch_curated_plugins_commit_from(
ensure_git_success(&output, context)
}
fn reset_curated_plugins_checkout(repo_path: &Path, git_binary: &str) -> Result<(), String> {
fn reset_curated_plugins_checkout(repo_path: &Path, git_binary: &Path) -> Result<(), String> {
run_git_in_repo(
repo_path,
git_binary,
@@ -291,7 +306,7 @@ fn reset_curated_plugins_checkout(repo_path: &Path, git_binary: &str) -> Result<
fn run_git_in_repo(
repo_path: &Path,
git_binary: &str,
git_binary: &Path,
args: &[&str],
context: &str,
) -> Result<(), String> {
@@ -583,7 +598,7 @@ fn write_curated_plugins_sha(sha_path: &Path, remote_sha: &str) -> Result<(), St
fn read_local_git_or_sha_file(
repo_path: &Path,
sha_path: &Path,
git_binary: &str,
git_binary: &Path,
) -> Option<String> {
if repo_path.join(".git").is_dir()
&& let Ok(sha) = git_head_sha(repo_path, git_binary)
@@ -594,7 +609,7 @@ fn read_local_git_or_sha_file(
read_sha_file(sha_path)
}
fn git_ls_remote_head_sha(git_binary: &str) -> Result<String, String> {
fn git_ls_remote_head_sha(git_binary: &Path) -> Result<String, String> {
let mut command = git_command(git_binary);
command
.arg("ls-remote")
@@ -622,7 +637,7 @@ fn git_ls_remote_head_sha(git_binary: &str) -> Result<String, String> {
Ok(sha.to_string())
}
fn git_head_sha(repo_path: &Path, git_binary: &str) -> Result<String, String> {
fn git_head_sha(repo_path: &Path, git_binary: &Path) -> Result<String, String> {
let output = git_command(git_binary)
.arg("-C")
.arg(repo_path)
@@ -647,7 +662,7 @@ fn git_head_sha(repo_path: &Path, git_binary: &str) -> Result<String, String> {
Ok(sha)
}
fn git_command(git_binary: &str) -> Command {
fn git_command(git_binary: &Path) -> Command {
let mut command = Command::new(git_binary);
command.env("GIT_OPTIONAL_LOCKS", "0");
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
@@ -656,6 +671,29 @@ fn git_command(git_binary: &str) -> Command {
command
}
#[cfg(any(target_os = "macos", test))]
fn macos_git_binary_from_path(
git_path: PathBuf,
apple_developer_tools_available: bool,
) -> Option<PathBuf> {
if git_path == Path::new("/usr/bin/git") && !apple_developer_tools_available {
None
} else {
Some(git_path)
}
}
#[cfg(target_os = "macos")]
fn apple_developer_tools_available() -> bool {
Command::new("/usr/bin/xcode-select")
.arg("-p")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
fn run_git_command_with_timeout(
command: &mut Command,
context: &str,
+78 -15
View File
@@ -19,7 +19,7 @@ const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"
#[test]
fn git_command_sanitizes_ambient_repository_environment() {
let command = git_command("git");
let command = git_command(Path::new("git"));
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
assert_eq!(
@@ -190,9 +190,29 @@ async fn run_sync_with_transport_overrides(
let api_base_url = api_base_url.into();
let backup_archive_api_url = backup_archive_api_url.into();
tokio::task::spawn_blocking(move || {
let git_binary = PathBuf::from(git_binary);
sync_openai_plugins_repo_with_transport_overrides(
codex_home.as_path(),
&git_binary,
Some(git_binary.as_path()),
&api_base_url,
&backup_archive_api_url,
)
})
.await
.expect("sync task should join")
}
async fn run_sync_without_git(
codex_home: PathBuf,
api_base_url: impl Into<String>,
backup_archive_api_url: impl Into<String>,
) -> Result<String, String> {
let api_base_url = api_base_url.into();
let backup_archive_api_url = backup_archive_api_url.into();
tokio::task::spawn_blocking(move || {
sync_openai_plugins_repo_with_transport_overrides(
codex_home.as_path(),
/*git_binary*/ None,
&api_base_url,
&backup_archive_api_url,
)
@@ -343,7 +363,7 @@ exit 1
barrier.wait();
sync_openai_plugins_repo_with_transport_overrides(
tmp.path(),
git_path.to_str().expect("utf8 path"),
Some(git_path.as_path()),
"http://127.0.0.1:9",
"http://127.0.0.1:9/backend-api/plugins/export/curated",
)
@@ -463,9 +483,8 @@ fn sync_openai_plugins_repo_via_git_succeeds_with_local_rewritten_remote() {
),
);
let synced_sha =
sync_openai_plugins_repo_via_git(tmp.path(), git_wrapper.to_str().expect("utf8 path"))
.expect("git sync should succeed");
let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper)
.expect("git sync should succeed");
assert_eq!(synced_sha, sha);
assert_curated_gmail_repo(&curated_plugins_repo_path(tmp.path()));
@@ -517,9 +536,8 @@ fn sync_openai_plugins_repo_via_git_succeeds_with_local_rewritten_remote() {
.trim()
.to_string();
let synced_sha =
sync_openai_plugins_repo_via_git(tmp.path(), git_wrapper.to_str().expect("utf8 path"))
.expect("incremental git sync should succeed");
let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper)
.expect("incremental git sync should succeed");
assert_eq!(synced_sha, updated_sha);
assert!(
@@ -573,9 +591,8 @@ fn sync_openai_plugins_repo_via_git_succeeds_with_local_rewritten_remote() {
assert!(!has_plugins_clone_dirs(tmp.path()));
let unchanged_sync_invocation_count = invocation_log_contents.lines().count();
let synced_sha =
sync_openai_plugins_repo_via_git(tmp.path(), git_wrapper.to_str().expect("utf8 path"))
.expect("unchanged git sync should succeed");
let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper)
.expect("unchanged git sync should succeed");
assert_eq!(synced_sha, updated_sha);
let invocation_log = std::fs::read_to_string(&invocation_log).expect("read sync invocations");
@@ -619,6 +636,52 @@ async fn sync_openai_plugins_repo_falls_back_to_http_when_git_is_unavailable() {
assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha));
}
#[test]
fn apple_git_without_developer_tools_is_unavailable() {
assert_eq!(
macos_git_binary_from_path(
PathBuf::from("/usr/bin/git"),
/*apple_developer_tools_available*/ false,
),
None
);
assert_eq!(
macos_git_binary_from_path(
PathBuf::from("/usr/bin/git"),
/*apple_developer_tools_available*/ true,
),
Some(PathBuf::from("/usr/bin/git"))
);
assert_eq!(
macos_git_binary_from_path(
PathBuf::from("/opt/homebrew/bin/git"),
/*apple_developer_tools_available*/ false,
),
Some(PathBuf::from("/opt/homebrew/bin/git"))
);
}
#[tokio::test]
async fn sync_openai_plugins_repo_uses_http_without_git_transport() {
let tmp = tempdir().expect("tempdir");
let server = MockServer::start().await;
let sha = "0123456789abcdef0123456789abcdef01234567";
mount_github_repo_and_ref(&server, sha).await;
mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await;
let synced_sha = run_sync_without_git(
tmp.path().to_path_buf(),
server.uri(),
"http://127.0.0.1:9/backend-api/plugins/export/curated",
)
.await
.expect("HTTP sync should succeed");
assert_eq!(synced_sha, sha);
assert_curated_gmail_repo(&curated_plugins_repo_path(tmp.path()));
}
#[cfg(unix)]
#[tokio::test]
async fn sync_openai_plugins_repo_falls_back_to_http_when_git_sync_fails() {
@@ -690,8 +753,8 @@ exit 1
),
);
let err = sync_openai_plugins_repo_via_git(tmp.path(), git_path.to_str().expect("utf8 path"))
.expect_err("git sync should fail");
let err =
sync_openai_plugins_repo_via_git(tmp.path(), &git_path).expect_err("git sync should fail");
assert!(err.contains("fatal: early EOF"));
assert!(!has_plugins_clone_dirs(tmp.path()));
@@ -755,7 +818,7 @@ exit 1
),
);
let err = sync_openai_plugins_repo_via_git(tmp.path(), git_path.to_str().expect("utf8 path"))
let err = sync_openai_plugins_repo_via_git(tmp.path(), &git_path)
.expect_err("invalid staged checkout should fail");
assert!(err.contains("curated plugins archive missing marketplace manifest"));

Some files were not shown because too many files have changed in this diff Show More