From 9e249964727c2aaf5327d1a4f52030ce4b61228a Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Mon, 6 Jul 2026 16:12:07 -0700 Subject: [PATCH 01/79] chore: use .worktreeinclude for user Bazel config (#31271) ## Why Codex worktrees need to inherit the ignored `user.bazelrc` file so Bazel keeps using local developer settings. `.worktreeinclude` expresses that copy declaratively, so the dedicated setup script is no longer needed. ## What - add `user.bazelrc` to `.worktreeinclude` - remove the Python copy script and its environment setup hook ## Validation - `git diff --check` - confirmed `git check-ignore -v user.bazelrc` matches `.gitignore` --- .codex/environments/environment.toml | 3 -- .codex/environments/setup.py | 65 ---------------------------- .worktreeinclude | 1 + 3 files changed, 1 insertion(+), 68 deletions(-) delete mode 100644 .codex/environments/setup.py create mode 100644 .worktreeinclude diff --git a/.codex/environments/environment.toml b/.codex/environments/environment.toml index 39c40eb07f..b3c5910fbc 100644 --- a/.codex/environments/environment.toml +++ b/.codex/environments/environment.toml @@ -2,9 +2,6 @@ version = 1 name = "codex" -[setup] -script = "python ./.codex/environments/setup.py" - [[actions]] name = "Run" icon = "run" diff --git a/.codex/environments/setup.py b/.codex/environments/setup.py deleted file mode 100644 index a9d78c9405..0000000000 --- a/.codex/environments/setup.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 - -"""Set up ignored files that should be shared with Codex worktrees.""" - -import shutil -import subprocess -from functools import cache -from pathlib import Path - - -@cache -def worktree_paths() -> tuple[Path, Path]: - script_dir = Path(__file__).resolve().parent - worktree_root = git_path(script_dir / "../..", "--show-toplevel") - common_git_dir = git_path(worktree_root, "--git-common-dir") - return worktree_root, common_git_dir.parent - - -def git_path(working_directory: Path, argument: str) -> Path: - output = subprocess.check_output( - [ - "git", - "-C", - str(working_directory), - "rev-parse", - "--path-format=absolute", - argument, - ], - text=True, - ) - return Path(output.strip()) - - -def copy_from_main_worktree_to_worktree(repo_relative_path: str) -> None: - relative_path = Path(repo_relative_path) - if relative_path.is_absolute() or ".." in relative_path.parts: - raise ValueError(f"path must be repository-relative: {repo_relative_path}") - - worktree_root, main_worktree = worktree_paths() - source_path = main_worktree / relative_path - destination_path = worktree_root / relative_path - - print(f" source: {source_path}") - print(f" destination: {destination_path}") - - if source_path == destination_path: - print(" result: running in the main worktree; nothing to copy") - elif destination_path.exists(): - print(" result: destination already exists; nothing to copy") - elif not source_path.is_file(): - print(" result: source does not exist; nothing to copy") - else: - destination_path.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(source_path, destination_path) - print(f" result: copied {repo_relative_path}") - - -def main() -> None: - print("Codex environment setup:") - # See codex-rs/docs/bazel.md for the repository's Bazel workflow. - copy_from_main_worktree_to_worktree("user.bazelrc") - - -if __name__ == "__main__": - main() diff --git a/.worktreeinclude b/.worktreeinclude new file mode 100644 index 0000000000..74824b01f9 --- /dev/null +++ b/.worktreeinclude @@ -0,0 +1 @@ +user.bazelrc From 9732b406e7976ed05d170623bc6ac4b4498a68e9 Mon Sep 17 00:00:00 2001 From: Channing Conger Date: Mon, 6 Jul 2026 16:26:56 -0700 Subject: [PATCH 02/79] fix: update crossbeam-epoch for RUSTSEC-2026-0204 (#31308) Bump our crossbeam-epoch dep to fix cargo-deny. --- MODULE.bazel.lock | 2 +- codex-rs/Cargo.lock | 5 +++-- codex-rs/code-mode-host/Cargo.toml | 1 + codex-rs/code-mode-host/tests/stdio.rs | 25 ++++++++++++------------- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index d572f68f21..3356b66c14 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -804,7 +804,7 @@ "critical-section_1.2.0": "{\"dependencies\":[],\"features\":{\"restore-state-bool\":[],\"restore-state-none\":[],\"restore-state-u16\":[],\"restore-state-u32\":[],\"restore-state-u64\":[],\"restore-state-u8\":[],\"restore-state-usize\":[],\"std\":[\"restore-state-bool\"]}}", "crossbeam-channel_0.5.15": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.13.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"signal-hook\",\"req\":\"^0.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-utils/std\"]}}", "crossbeam-deque_0.8.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-epoch\",\"req\":\"^0.9.17\"},{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-epoch/std\",\"crossbeam-utils/std\"]}}", - "crossbeam-epoch_0.9.18": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"name\":\"loom-crate\",\"optional\":true,\"package\":\"loom\",\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"loom\":[\"loom-crate\",\"crossbeam-utils/loom\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", + "crossbeam-epoch_0.9.20": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"name\":\"loom-crate\",\"optional\":true,\"package\":\"loom\",\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"loom\":[\"loom-crate\",\"crossbeam-utils/loom\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", "crossbeam-queue_0.3.12": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", "crossbeam-utils_0.8.21": "{\"dependencies\":[{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", "crossterm_winapi_0.9.1": "{\"dependencies\":[{\"features\":[\"winbase\",\"consoleapi\",\"processenv\",\"handleapi\",\"synchapi\",\"impl-default\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 89d27d0ec0..c0ff4a585a 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2526,6 +2526,7 @@ dependencies = [ "codex-utils-cargo-bin", "pretty_assertions", "serde_json", + "tempfile", "tokio", "tokio-util", ] @@ -4822,9 +4823,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] diff --git a/codex-rs/code-mode-host/Cargo.toml b/codex-rs/code-mode-host/Cargo.toml index 90b043b097..86a36d2a27 100644 --- a/codex-rs/code-mode-host/Cargo.toml +++ b/codex-rs/code-mode-host/Cargo.toml @@ -28,3 +28,4 @@ codex-protocol = { workspace = true } codex-utils-cargo-bin = { workspace = true } pretty_assertions = { workspace = true } serde_json = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/code-mode-host/tests/stdio.rs b/codex-rs/code-mode-host/tests/stdio.rs index e7b7506163..8edcbcaa8d 100644 --- a/codex-rs/code-mode-host/tests/stdio.rs +++ b/codex-rs/code-mode-host/tests/stdio.rs @@ -504,13 +504,17 @@ return; next_callback_event(&mut events_rx).await, CallbackEvent::Started("tool_call_slow".to_string()) ); - assert_eq!( + let mut closure_events = vec![ next_callback_event(&mut events_rx).await, - CallbackEvent::Cancelled("tool_call_slow".to_string()) - ); - assert_eq!( next_callback_event(&mut events_rx).await, - CallbackEvent::CellClosed(running_cell_id.clone()) + ]; + closure_events.sort_by(|left, right| format!("{left:?}").cmp(&format!("{right:?}"))); + assert_eq!( + closure_events, + vec![ + CallbackEvent::Cancelled("tool_call_slow".to_string()), + CallbackEvent::CellClosed(running_cell_id.clone()), + ] ); assert_eq!( wait_task @@ -677,12 +681,9 @@ async fn oversized_initial_response_does_not_close_the_shared_host() { async fn child_process_loss_cleans_up_and_rebuilds_the_shared_host() { let host_program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host").expect("host binary"); - let proxy_dir = - std::env::temp_dir().join(format!("codex-code-mode-host-loss-{}", std::process::id())); - let proxy_program = proxy_dir.join("host-proxy.sh"); - let pid_path = proxy_dir.join("host.pid"); - let _ = std::fs::remove_dir_all(&proxy_dir); - std::fs::create_dir_all(&proxy_dir).expect("create host proxy directory"); + let proxy_dir = tempfile::tempdir().expect("create host proxy directory"); + let proxy_program = proxy_dir.path().join("host-proxy.sh"); + let pid_path = proxy_dir.path().join("host.pid"); std::fs::write( &proxy_program, format!( @@ -869,6 +870,4 @@ async fn child_process_loss_cleans_up_and_rebuilds_the_shared_host() { events_a.try_recv(), Err(mpsc::error::TryRecvError::Empty) )); - - std::fs::remove_dir_all(proxy_dir).expect("remove host proxy directory"); } From 3f6157004419e21547962670026c6f6001d06fe8 Mon Sep 17 00:00:00 2001 From: Channing Conger Date: Mon, 6 Jul 2026 16:58:05 -0700 Subject: [PATCH 03/79] [codex] bundle code mode host in release packages (#30202) ## Summary - build, strip, sign, and publish `codex-code-mode-host` with the primary Codex release binaries on Linux, macOS, and Windows - place the host beside `codex[.exe]` in canonical package archives, macOS DMGs, and the legacy Linux bundle so the runtime's sibling lookup succeeds - preserve and validate the host through standalone installers and Python runtime wheel staging - add package-builder coverage for source selection and the resulting package layout ## Why The process-owned code-mode client launches `codex-code-mode-host` as a sibling of the running Codex executable. Release artifacts currently build and bundle `codex` without that host, so code mode cannot start from installed packages. --- .../scripts/build-codex-package-archive.sh | 12 ++++ .github/workflows/rust-release-windows.yml | 10 +-- .github/workflows/rust-release.yml | 65 ++++++++++++------- scripts/codex_package/README.md | 7 +- scripts/codex_package/cargo.py | 14 +++- scripts/codex_package/cli.py | 14 ++++ scripts/codex_package/layout.py | 6 ++ scripts/codex_package/targets.py | 1 + scripts/codex_package/test_cargo.py | 21 ++++++ scripts/codex_package/test_layout.py | 56 ++++++++++++++++ scripts/install/install.ps1 | 1 + scripts/install/install.sh | 6 +- sdk/python/scripts/update_sdk_artifacts.py | 7 ++ .../test_artifact_workflow_and_binaries.py | 3 + 14 files changed, 193 insertions(+), 30 deletions(-) create mode 100644 scripts/codex_package/test_layout.py diff --git a/.github/scripts/build-codex-package-archive.sh b/.github/scripts/build-codex-package-archive.sh index 229213cc53..4592e78ce5 100644 --- a/.github/scripts/build-codex-package-archive.sh +++ b/.github/scripts/build-codex-package-archive.sh @@ -9,6 +9,7 @@ Usage: build-codex-package-archive.sh \ --entrypoint-dir \ --archive-dir \ [--bwrap-bin ] \ + [--code-mode-host-bin ] \ [--zsh-manifest ] \ [--codex-command-runner-bin ] \ [--codex-windows-sandbox-setup-bin ] \ @@ -23,6 +24,7 @@ archive_dir="" target_suffixed_entrypoint="false" resource_args=() bwrap_bin_provided="false" +code_mode_host_bin_provided="false" command_runner_bin_provided="false" sandbox_setup_bin_provided="false" @@ -49,6 +51,11 @@ while [[ $# -gt 0 ]]; do bwrap_bin_provided="true" shift 2 ;; + --code-mode-host-bin) + resource_args+=(--code-mode-host-bin "${2:?--code-mode-host-bin requires a value}") + code_mode_host_bin_provided="true" + shift 2 + ;; --zsh-manifest) resource_args+=(--zsh-manifest "${2:?--zsh-manifest requires a value}") shift 2 @@ -114,6 +121,11 @@ case "$target" in ;; esac +code_mode_host_bin="${entrypoint_dir%/}/codex-code-mode-host${exe_suffix}" +if [[ "$code_mode_host_bin_provided" == "false" && -f "$code_mode_host_bin" ]]; then + resource_args+=(--code-mode-host-bin "$code_mode_host_bin") +fi + entrypoint_name="$entrypoint" if [[ "$target_suffixed_entrypoint" == "true" ]]; then entrypoint_name="${entrypoint_name}-${target}" diff --git a/.github/workflows/rust-release-windows.yml b/.github/workflows/rust-release-windows.yml index 7069b6ca8f..31d832fcbe 100644 --- a/.github/workflows/rust-release-windows.yml +++ b/.github/workflows/rust-release-windows.yml @@ -7,7 +7,7 @@ on: # nested submodules. Prefer the system git CLI across every Cargo invocation. env: CARGO_NET_GIT_FETCH_WITH_CLI: "true" - WINDOWS_BINARIES: "codex codex-responses-api-proxy codex-windows-sandbox-setup codex-command-runner codex-app-server" + WINDOWS_BINARIES: "codex codex-code-mode-host codex-responses-api-proxy codex-windows-sandbox-setup codex-command-runner codex-app-server" jobs: build-windows-binaries: @@ -28,14 +28,14 @@ jobs: - runner: windows-x64 target: x86_64-pc-windows-msvc bundle: primary - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" runs_on: group: ${{ github.event.repository.name }}-runners labels: ${{ github.event.repository.name }}-windows-x64 - runner: windows-arm64 target: aarch64-pc-windows-msvc bundle: primary - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" runs_on: group: ${{ github.event.repository.name }}-runners labels: ${{ github.event.repository.name }}-windows-arm64 @@ -56,14 +56,14 @@ jobs: - runner: windows-x64 target: x86_64-pc-windows-msvc bundle: app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" runs_on: group: ${{ github.event.repository.name }}-runners labels: ${{ github.event.repository.name }}-windows-x64 - runner: windows-arm64 target: aarch64-pc-windows-msvc bundle: app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" runs_on: group: ${{ github.event.repository.name }}-runners labels: ${{ github.event.repository.name }}-windows-arm64 diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 49d24abc18..93f03e63d1 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -83,50 +83,50 @@ jobs: target: aarch64-apple-darwin bundle: primary artifact_name: aarch64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" build_dmg: "true" - runner: macos-15-xlarge target: aarch64-apple-darwin bundle: app-server artifact_name: aarch64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" - runner: macos-15-xlarge target: x86_64-apple-darwin bundle: primary artifact_name: x86_64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" build_dmg: "true" - runner: macos-15-xlarge target: x86_64-apple-darwin bundle: app-server artifact_name: x86_64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" # Release artifacts intentionally ship MUSL-linked Linux binaries. - runner: ${{ github.event.repository.name }}-linux-x64-xl target: x86_64-unknown-linux-musl bundle: primary artifact_name: x86_64-unknown-linux-musl - binaries: "codex codex-responses-api-proxy bwrap" + binaries: "codex codex-code-mode-host codex-responses-api-proxy bwrap" build_dmg: "false" - runner: ${{ github.event.repository.name }}-linux-x64-xl target: x86_64-unknown-linux-musl bundle: app-server artifact_name: x86_64-unknown-linux-musl-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" - runner: ${{ github.event.repository.name }}-linux-arm64 target: aarch64-unknown-linux-musl bundle: primary artifact_name: aarch64-unknown-linux-musl - binaries: "codex codex-responses-api-proxy bwrap" + binaries: "codex codex-code-mode-host codex-responses-api-proxy bwrap" build_dmg: "false" - runner: ${{ github.event.repository.name }}-linux-arm64 target: aarch64-unknown-linux-musl bundle: app-server artifact_name: aarch64-unknown-linux-musl-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" steps: @@ -335,6 +335,11 @@ jobs: mkdir -p "$dest" for binary in ${{ matrix.binaries }}; do + # Both variants package the host, but only the primary bundle publishes + # standalone binary archives to avoid duplicate release asset names. + if [[ "${{ matrix.bundle }}" == "app-server" && "$binary" == "codex-code-mode-host" ]]; then + continue + fi cp "target/${{ matrix.target }}/release/${binary}" "$dest/${binary}-${{ matrix.target }}" if [[ "${{ matrix.target }}" == *linux* ]]; then cp "target/${{ matrix.target }}/release/${binary}.sigstore" \ @@ -347,9 +352,13 @@ jobs: rm -rf "$bundle_root" mkdir -p "$bundle_root/codex-resources" cp "$dest/codex-${{ matrix.target }}" "$bundle_root/codex" + cp "$dest/codex-code-mode-host-${{ matrix.target }}" "$bundle_root/codex-code-mode-host" cp "$dest/bwrap-${{ matrix.target }}" "$bundle_root/codex-resources/bwrap" - chmod 0755 "$bundle_root/codex" "$bundle_root/codex-resources/bwrap" - tar -C "$bundle_root" -cf - codex codex-resources/bwrap | + chmod 0755 \ + "$bundle_root/codex" \ + "$bundle_root/codex-code-mode-host" \ + "$bundle_root/codex-resources/bwrap" + tar -C "$bundle_root" -cf - codex codex-code-mode-host codex-resources/bwrap | zstd -T0 -19 -o "$dest/codex-${{ matrix.target }}-bundle.tar.zst" fi @@ -497,19 +506,19 @@ jobs: - target: aarch64-apple-darwin bundle: primary artifact_name: aarch64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" - target: aarch64-apple-darwin bundle: app-server artifact_name: aarch64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" - target: x86_64-apple-darwin bundle: primary artifact_name: x86_64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" - target: x86_64-apple-darwin bundle: app-server artifact_name: x86_64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -615,22 +624,22 @@ jobs: - target: aarch64-apple-darwin bundle: primary artifact_name: aarch64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" build_dmg: "true" - target: aarch64-apple-darwin bundle: app-server artifact_name: aarch64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" - target: x86_64-apple-darwin bundle: primary artifact_name: x86_64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" build_dmg: "true" - target: x86_64-apple-darwin bundle: app-server artifact_name: x86_64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" build_dmg: "false" steps: @@ -707,6 +716,11 @@ jobs: mkdir -p "$dest" for binary in ${{ matrix.binaries }}; do + # Both variants package the host, but only the primary bundle publishes + # standalone binary archives to avoid duplicate release asset names. + if [[ "${{ matrix.bundle }}" == "app-server" && "$binary" == "codex-code-mode-host" ]]; then + continue + fi cp "target/${{ matrix.target }}/release/${binary}" "$dest/${binary}-${{ matrix.target }}" done @@ -911,22 +925,22 @@ jobs: - target: aarch64-apple-darwin bundle: primary artifact_name: aarch64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" verify_dmg: "true" - target: aarch64-apple-darwin bundle: app-server artifact_name: aarch64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" verify_dmg: "false" - target: x86_64-apple-darwin bundle: primary artifact_name: x86_64-apple-darwin - binaries: "codex codex-responses-api-proxy" + binaries: "codex codex-code-mode-host codex-responses-api-proxy" verify_dmg: "true" - target: x86_64-apple-darwin bundle: app-server artifact_name: x86_64-apple-darwin-app-server - binaries: "codex-app-server" + binaries: "codex-app-server codex-code-mode-host" verify_dmg: "false" steps: @@ -983,6 +997,12 @@ jobs: binary_path="${RUNNER_TEMP}/signed-binaries/${binary}" verify_signed_binary "$binary_path" + # The app-server package contains the host, but its standalone archives + # are omitted above to avoid duplicate release asset names. + if [[ "${{ matrix.bundle }}" == "app-server" && "$binary" == "codex-code-mode-host" ]]; then + continue + fi + direct_archive_dir="${RUNNER_TEMP}/direct-archive-${binary}-${target}" rm -rf "$direct_archive_dir" mkdir -p "$direct_archive_dir" @@ -1014,6 +1034,7 @@ jobs: mkdir -p "$package_dir" tar -xzf "${packaged_dir}/${package_stem}-${target}.tar.gz" -C "$package_dir" verify_signed_binary "${package_dir}/bin/${package_entrypoint}" + verify_signed_binary "${package_dir}/bin/codex-code-mode-host" if [[ "${{ matrix.verify_dmg }}" != "true" ]]; then exit 0 diff --git a/scripts/codex_package/README.md b/scripts/codex_package/README.md index b76c18c3c2..7850bbd354 100644 --- a/scripts/codex_package/README.md +++ b/scripts/codex_package/README.md @@ -10,7 +10,8 @@ The builder creates a canonical Codex package directory: . ├── codex-package.json ├── bin -│ └── [.exe] +│ ├── [.exe] +│ └── codex-code-mode-host[.exe] ├── codex-resources │ ├── bwrap # Linux only │ ├── zsh/bin/zsh # supported Unix targets only @@ -40,6 +41,7 @@ grouped `cargo build` command per package when they are needed and no prebuilt override was provided: - all targets: the selected entrypoint, unless `--entrypoint-bin` is provided +- all targets: `codex-code-mode-host`, unless `--code-mode-host-bin` is provided - Linux targets: `bwrap`, unless `--bwrap-bin` is provided - Windows targets: `codex-command-runner` and `codex-windows-sandbox-setup`, unless the corresponding prebuilt helper flags are provided @@ -50,6 +52,9 @@ explicit target. Release jobs that already built and signed/notarized the entrypoint should pass `--entrypoint-bin` so the package contains that exact binary instead of rebuilding it. +Release jobs should likewise pass `--code-mode-host-bin` so the package contains +the signed host executable beside the signed entrypoint. + Release jobs that already built package resource binaries should also pass the corresponding resource flags: `--bwrap-bin` for Linux packages, and `--codex-command-runner-bin` plus `--codex-windows-sandbox-setup-bin` for diff --git a/scripts/codex_package/cargo.py b/scripts/codex_package/cargo.py index 208d85d174..f759e44762 100644 --- a/scripts/codex_package/cargo.py +++ b/scripts/codex_package/cargo.py @@ -17,6 +17,7 @@ CODEX_RS_ROOT = REPO_ROOT / "codex-rs" @dataclass(frozen=True) class SourceBuildOutputs: entrypoint_bin: Path + code_mode_host_bin: Path bwrap_bin: Path | None codex_command_runner_bin: Path | None codex_windows_sandbox_setup_bin: Path | None @@ -29,6 +30,7 @@ def build_source_binaries( cargo: str, profile: str, entrypoint_bin: Path | None, + code_mode_host_bin: Path | None, bwrap_bin: Path | None, codex_command_runner_bin: Path | None, codex_windows_sandbox_setup_bin: Path | None, @@ -43,6 +45,7 @@ def build_source_binaries( spec, variant, build_entrypoint=entrypoint_bin is None, + build_code_mode_host=code_mode_host_bin is None, build_bwrap=spec.is_linux and bwrap_bin is None, build_codex_command_runner=spec.is_windows and codex_command_runner_bin is None, build_codex_windows_sandbox_setup=spec.is_windows @@ -61,7 +64,7 @@ def build_source_binaries( cmd.extend(["--bin", binary]) cargo_env = None - if entrypoint_bin is None: + if entrypoint_bin is None or code_mode_host_bin is None: codex_v8_env = resolve_codex_v8_cargo_env(spec) if codex_v8_env: cargo_env = {**os.environ, **codex_v8_env} @@ -80,6 +83,11 @@ def build_source_binaries( entrypoint_bin, output_dir / variant.entrypoint_name(spec), ), + code_mode_host_bin=( + code_mode_host_bin.resolve() + if code_mode_host_bin is not None + else output_dir / f"codex-code-mode-host{spec.exe_suffix}" + ), bwrap_bin=resolve_output_path( bwrap_bin, output_dir / "bwrap" if spec.is_linux else None, @@ -102,6 +110,7 @@ def source_binaries_for_target( variant: PackageVariant, *, build_entrypoint: bool, + build_code_mode_host: bool, build_bwrap: bool, build_codex_command_runner: bool, build_codex_windows_sandbox_setup: bool, @@ -109,6 +118,8 @@ def source_binaries_for_target( binaries = [] if build_entrypoint: binaries.append(variant.cargo_bin) + if build_code_mode_host: + binaries.append("codex-code-mode-host") if build_bwrap: binaries.append("bwrap") if build_codex_command_runner: @@ -174,6 +185,7 @@ def cargo_profile_dirname(profile: str) -> str: def validate_source_outputs(outputs: SourceBuildOutputs) -> None: for path in [ outputs.entrypoint_bin, + outputs.code_mode_host_bin, outputs.bwrap_bin, outputs.codex_command_runner_bin, outputs.codex_windows_sandbox_setup_bin, diff --git a/scripts/codex_package/cli.py b/scripts/codex_package/cli.py index 1dd276827e..f461d0df43 100644 --- a/scripts/codex_package/cli.py +++ b/scripts/codex_package/cli.py @@ -82,6 +82,14 @@ def parse_args() -> argparse.Namespace: "variant. If omitted, the entrypoint is built with Cargo." ), ) + parser.add_argument( + "--code-mode-host-bin", + type=Path, + help=( + "Optional prebuilt codex-code-mode-host executable. If omitted, " + "the host is built with Cargo." + ), + ) parser.add_argument( "--bwrap-bin", type=Path, @@ -148,6 +156,11 @@ def main() -> int: "prebuilt entrypoint executable", "--entrypoint-bin", ), + code_mode_host_bin=resolve_optional_input_path( + args.code_mode_host_bin, + "prebuilt code-mode host executable", + "--code-mode-host-bin", + ), bwrap_bin=resolve_optional_input_path( args.bwrap_bin, "prebuilt Linux bwrap executable", @@ -167,6 +180,7 @@ def main() -> int: version = read_workspace_version() inputs = PackageInputs( entrypoint_bin=source_outputs.entrypoint_bin, + code_mode_host_bin=source_outputs.code_mode_host_bin, rg_bin=resolve_rg_bin(spec, args.rg_bin), zsh_bin=resolve_zsh_bin(spec, args.zsh_manifest), bwrap_bin=source_outputs.bwrap_bin, diff --git a/scripts/codex_package/layout.py b/scripts/codex_package/layout.py index 63598672ea..f4fef6912c 100644 --- a/scripts/codex_package/layout.py +++ b/scripts/codex_package/layout.py @@ -51,6 +51,11 @@ def build_package_dir( bin_dir / entrypoint_name, is_windows=spec.is_windows, ) + copy_executable( + inputs.code_mode_host_bin, + bin_dir / f"codex-code-mode-host{spec.exe_suffix}", + is_windows=spec.is_windows, + ) copy_executable(inputs.rg_bin, path_dir / spec.rg_name, is_windows=spec.is_windows) if inputs.zsh_bin is not None: @@ -130,6 +135,7 @@ def validate_package_dir( required_files = [ Path("bin") / variant.entrypoint_name(spec), + Path("bin") / f"codex-code-mode-host{spec.exe_suffix}", Path("codex-path") / spec.rg_name, ] executable_files = list(required_files) diff --git a/scripts/codex_package/targets.py b/scripts/codex_package/targets.py index 8307a3e630..016202cf5f 100644 --- a/scripts/codex_package/targets.py +++ b/scripts/codex_package/targets.py @@ -39,6 +39,7 @@ class PackageVariant: @dataclass(frozen=True) class PackageInputs: entrypoint_bin: Path + code_mode_host_bin: Path rg_bin: Path zsh_bin: Path | None bwrap_bin: Path | None diff --git a/scripts/codex_package/test_cargo.py b/scripts/codex_package/test_cargo.py index 6185f8b8b3..1a4a572b9b 100644 --- a/scripts/codex_package/test_cargo.py +++ b/scripts/codex_package/test_cargo.py @@ -20,6 +20,7 @@ class SourceBinariesForTargetTest(unittest.TestCase): TARGET_SPECS["aarch64-apple-darwin"], PACKAGE_VARIANTS["codex"], build_entrypoint=False, + build_code_mode_host=False, build_bwrap=False, build_codex_command_runner=False, build_codex_windows_sandbox_setup=False, @@ -35,6 +36,7 @@ class SourceBinariesForTargetTest(unittest.TestCase): TARGET_SPECS["x86_64-unknown-linux-musl"], PACKAGE_VARIANTS["codex"], build_entrypoint=False, + build_code_mode_host=False, build_bwrap=False, build_codex_command_runner=False, build_codex_windows_sandbox_setup=False, @@ -50,6 +52,7 @@ class SourceBinariesForTargetTest(unittest.TestCase): TARGET_SPECS["x86_64-pc-windows-msvc"], PACKAGE_VARIANTS["codex"], build_entrypoint=False, + build_code_mode_host=False, build_bwrap=False, build_codex_command_runner=False, build_codex_windows_sandbox_setup=False, @@ -63,6 +66,7 @@ class SourceBinariesForTargetTest(unittest.TestCase): TARGET_SPECS["x86_64-pc-windows-msvc"], PACKAGE_VARIANTS["codex"], build_entrypoint=False, + build_code_mode_host=False, build_bwrap=False, build_codex_command_runner=True, build_codex_windows_sandbox_setup=True, @@ -70,10 +74,25 @@ class SourceBinariesForTargetTest(unittest.TestCase): ["codex-command-runner", "codex-windows-sandbox-setup"], ) + def test_missing_code_mode_host_is_built_for_app_server(self) -> None: + self.assertEqual( + source_binaries_for_target( + TARGET_SPECS["aarch64-apple-darwin"], + PACKAGE_VARIANTS["codex-app-server"], + build_entrypoint=False, + build_code_mode_host=True, + build_bwrap=False, + build_codex_command_runner=False, + build_codex_windows_sandbox_setup=False, + ), + ["codex-code-mode-host"], + ) + def test_build_uses_prebuilt_windows_helpers_without_running_cargo(self) -> None: with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) entrypoint = touch_file(root / "codex.exe") + code_mode_host = touch_file(root / "codex-code-mode-host.exe") command_runner = touch_file(root / "codex-command-runner.exe") sandbox_setup = touch_file(root / "codex-windows-sandbox-setup.exe") @@ -83,12 +102,14 @@ class SourceBinariesForTargetTest(unittest.TestCase): cargo=str(root / "cargo-that-should-not-run"), profile="release", entrypoint_bin=entrypoint, + code_mode_host_bin=code_mode_host, bwrap_bin=None, codex_command_runner_bin=command_runner, codex_windows_sandbox_setup_bin=sandbox_setup, ) self.assertEqual(outputs.entrypoint_bin, entrypoint) + self.assertEqual(outputs.code_mode_host_bin, code_mode_host) self.assertEqual(outputs.codex_command_runner_bin, command_runner) self.assertEqual(outputs.codex_windows_sandbox_setup_bin, sandbox_setup) diff --git a/scripts/codex_package/test_layout.py b/scripts/codex_package/test_layout.py new file mode 100644 index 0000000000..157bce5e9c --- /dev/null +++ b/scripts/codex_package/test_layout.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 + +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from codex_package.layout import build_package_dir +from codex_package.layout import validate_package_dir +from codex_package.targets import PACKAGE_VARIANTS +from codex_package.targets import PackageInputs +from codex_package.targets import TARGET_SPECS + + +class PackageLayoutTest(unittest.TestCase): + def test_app_server_package_places_code_mode_host_beside_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + package_dir = root / "package" + package_dir.mkdir() + inputs = PackageInputs( + entrypoint_bin=touch_executable(root / "codex-app-server"), + code_mode_host_bin=touch_executable(root / "codex-code-mode-host"), + rg_bin=touch_executable(root / "rg"), + zsh_bin=None, + bwrap_bin=touch_executable(root / "bwrap"), + codex_command_runner_bin=None, + codex_windows_sandbox_setup_bin=None, + ) + + build_package_dir( + package_dir, + "1.2.3", + PACKAGE_VARIANTS["codex-app-server"], + TARGET_SPECS["x86_64-unknown-linux-musl"], + inputs, + ) + validate_package_dir( + package_dir, + PACKAGE_VARIANTS["codex-app-server"], + TARGET_SPECS["x86_64-unknown-linux-musl"], + include_zsh=False, + ) + + self.assertTrue((package_dir / "bin" / "codex-code-mode-host").is_file()) + + +def touch_executable(path: Path) -> Path: + path.touch(mode=0o755) + return path + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1 index 986f6c6566..e27d34b223 100644 --- a/scripts/install/install.ps1 +++ b/scripts/install/install.ps1 @@ -538,6 +538,7 @@ function Test-PackageContentsAreComplete { $expectedFiles = @( "codex-package.json", "bin\codex.exe", + "bin\codex-code-mode-host.exe", "codex-path\rg.exe", "codex-resources\codex-command-runner.exe", "codex-resources\codex-windows-sandbox-setup.exe" diff --git a/scripts/install/install.sh b/scripts/install/install.sh index d44b353860..12b66f958a 100755 --- a/scripts/install/install.sh +++ b/scripts/install/install.sh @@ -680,7 +680,10 @@ install_package_release() { rm -rf "$stage_release" mkdir -p "$stage_release" tar -xzf "$archive_path" -C "$stage_release" - chmod 0755 "$stage_release/bin/codex" "$stage_release/codex-path/rg" + chmod 0755 \ + "$stage_release/bin/codex" \ + "$stage_release/bin/codex-code-mode-host" \ + "$stage_release/codex-path/rg" if [ -f "$stage_release/codex-resources/bwrap" ]; then chmod 0755 "$stage_release/codex-resources/bwrap" fi @@ -733,6 +736,7 @@ release_dir_is_complete() { package) [ -f "$release_dir/codex-package.json" ] && [ -x "$release_dir/bin/codex" ] && + [ -x "$release_dir/bin/codex-code-mode-host" ] && [ -x "$release_dir/codex" ] && [ -x "$release_dir/codex-path/rg" ] || return 1 diff --git a/sdk/python/scripts/update_sdk_artifacts.py b/sdk/python/scripts/update_sdk_artifacts.py index f3b97c6b6f..1c6ec59402 100755 --- a/sdk/python/scripts/update_sdk_artifacts.py +++ b/sdk/python/scripts/update_sdk_artifacts.py @@ -53,6 +53,10 @@ def runtime_binary_name() -> str: return "codex.exe" if _is_windows() else "codex" +def runtime_code_mode_host_name() -> str: + return "codex-code-mode-host.exe" if _is_windows() else "codex-code-mode-host" + + def staged_runtime_package_root(root: Path) -> Path: return root / RUNTIME_PACKAGE_ROOT @@ -276,6 +280,9 @@ def _validate_codex_package_layout(package_dir: Path, package_archive: Path) -> package_binary = package_dir / "bin" / runtime_binary_name() if not package_binary.is_file(): missing_entries.append(str(Path("bin") / runtime_binary_name())) + code_mode_host = package_dir / "bin" / runtime_code_mode_host_name() + if not code_mode_host.is_file(): + missing_entries.append(str(Path("bin") / runtime_code_mode_host_name())) if missing_entries: missing = ", ".join(missing_entries) raise RuntimeError(f"Missing Codex package layout entries in {package_archive}: {missing}") diff --git a/sdk/python/tests/test_artifact_workflow_and_binaries.py b/sdk/python/tests/test_artifact_workflow_and_binaries.py index 301a75abac..ad1262e836 100644 --- a/sdk/python/tests/test_artifact_workflow_and_binaries.py +++ b/sdk/python/tests/test_artifact_workflow_and_binaries.py @@ -57,6 +57,7 @@ def _write_fake_codex_package(package_dir: Path, script) -> Path: (package_dir / "codex-path").mkdir() (package_dir / "codex-package.json").write_text('{"variant":"codex"}\n') (package_dir / "bin" / script.runtime_binary_name()).write_text("fake codex\n") + (package_dir / "bin" / script.runtime_code_mode_host_name()).write_text("fake code mode host\n") (package_dir / "codex-resources" / "bwrap").write_text("fake bwrap\n") (package_dir / "codex-path" / "rg").write_text("fake rg\n") return package_dir @@ -682,11 +683,13 @@ def test_stage_runtime_release_copies_package_layout_and_sets_version( assert { "metadata": (package_root / "codex-package.json").read_text(), "codex": (package_root / "bin" / script.runtime_binary_name()).read_text(), + "code_mode_host": (package_root / "bin" / script.runtime_code_mode_host_name()).read_text(), "bwrap": (package_root / "codex-resources" / "bwrap").read_text(), "rg": (package_root / "codex-path" / "rg").read_text(), } == { "metadata": '{"variant":"codex"}\n', "codex": "fake codex\n", + "code_mode_host": "fake code mode host\n", "bwrap": "fake bwrap\n", "rg": "fake rg\n", } From c71895f63b44f439e10a0f09dc5dadba3e976de9 Mon Sep 17 00:00:00 2001 From: Eric Ning Date: Mon, 6 Jul 2026 17:12:39 -0700 Subject: [PATCH 04/79] [codex] app-server: expose plugin install policy source (#31293) ## Summary - Add `PluginInstallPolicySource` to the app-server v2 `PluginSummary` payload. - Propagate remote `installation_policy_source` through plugin summaries, details, installed-plugin caching, and app-server responses. - Preserve the supported source values and map unrecognized backend values to `null`. - Return `null` for local plugins and expose the field in generated JSON and TypeScript schemas. - Update app-server API documentation and plugin list/read coverage. ## Testing - `just test -p codex-app-server-protocol` (251 passed) - Targeted `codex-app-server` plugin list, installed, and read tests (4 passed) - Targeted `codex-core-plugins` known and unknown policy source tests (2 passed) - `just fmt` - `git diff --check` --- .../codex_app_server_protocol.schemas.json | 17 +++++ .../codex_app_server_protocol.v2.schemas.json | 17 +++++ .../json/v2/PluginInstalledResponse.json | 17 +++++ .../schema/json/v2/PluginListResponse.json | 17 +++++ .../schema/json/v2/PluginReadResponse.json | 17 +++++ .../json/v2/PluginShareListResponse.json | 17 +++++ .../v2/PluginInstallPolicySource.ts | 5 ++ .../schema/typescript/v2/PluginSummary.ts | 3 +- .../schema/typescript/v2/index.ts | 1 + .../src/protocol/v2/plugin.rs | 12 ++++ .../src/protocol/v2/tests.rs | 2 + codex-rs/app-server/README.md | 4 +- .../src/request_processors/plugins.rs | 3 + .../app-server/tests/suite/v2/plugin_list.rs | 33 +++++++++- .../app-server/tests/suite/v2/plugin_read.rs | 6 ++ .../app-server/tests/suite/v2/plugin_share.rs | 3 + codex-rs/core-plugins/src/manager_tests.rs | 1 + codex-rs/core-plugins/src/remote.rs | 31 +++++++++ .../core-plugins/src/remote/share/tests.rs | 2 + codex-rs/core-plugins/src/remote_tests.rs | 64 +++++++++++++++++++ codex-rs/tui/src/app/plugin_mentions.rs | 1 + codex-rs/tui/src/chatwidget/tests/helpers.rs | 2 + 22 files changed, 269 insertions(+), 6 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/PluginInstallPolicySource.ts diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 0eedef903a..2ffff2f96f 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -13423,6 +13423,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInstallResponse": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -14306,6 +14313,16 @@ "installPolicy": { "$ref": "#/definitions/v2/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/v2/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index b428f25258..dc6e2c9693 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -9827,6 +9827,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInstallResponse": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -10710,6 +10717,16 @@ "installPolicy": { "$ref": "#/definitions/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json index 55ad95be2e..f39b0f19b3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json @@ -63,6 +63,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInterface": { "properties": { "brandColor": { @@ -489,6 +496,16 @@ "installPolicy": { "$ref": "#/definitions/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json index 25d12e50dd..2f0c6e4b40 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json @@ -63,6 +63,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInterface": { "properties": { "brandColor": { @@ -489,6 +496,16 @@ "installPolicy": { "$ref": "#/definitions/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json index b4b917602a..628cb13189 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json @@ -242,6 +242,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInterface": { "properties": { "brandColor": { @@ -629,6 +636,16 @@ "installPolicy": { "$ref": "#/definitions/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json index 751a6c5e7f..32bf946e38 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json @@ -37,6 +37,13 @@ ], "type": "string" }, + "PluginInstallPolicySource": { + "enum": [ + "WORKSPACE_SETTING", + "IMPLICIT_CANONICAL_APP" + ], + "type": "string" + }, "PluginInterface": { "properties": { "brandColor": { @@ -445,6 +452,16 @@ "installPolicy": { "$ref": "#/definitions/PluginInstallPolicy" }, + "installPolicySource": { + "anyOf": [ + { + "$ref": "#/definitions/PluginInstallPolicySource" + }, + { + "type": "null" + } + ] + }, "installed": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PluginInstallPolicySource.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginInstallPolicySource.ts new file mode 100644 index 0000000000..caa39628ac --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginInstallPolicySource.ts @@ -0,0 +1,5 @@ +// 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. + +export type PluginInstallPolicySource = "WORKSPACE_SETTING" | "IMPLICIT_CANONICAL_APP"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts index d12f55b3a3..10fd5aa25f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts @@ -4,6 +4,7 @@ import type { PluginAuthPolicy } from "./PluginAuthPolicy"; import type { PluginAvailability } from "./PluginAvailability"; import type { PluginInstallPolicy } from "./PluginInstallPolicy"; +import type { PluginInstallPolicySource } from "./PluginInstallPolicySource"; import type { PluginInterface } from "./PluginInterface"; import type { PluginShareContext } from "./PluginShareContext"; import type { PluginSource } from "./PluginSource"; @@ -24,7 +25,7 @@ localVersion: string | null, name: string, /** * Remote sharing context associated with this plugin when available. */ -shareContext: PluginShareContext | null, source: PluginSource, installed: boolean, enabled: boolean, installPolicy: PluginInstallPolicy, authPolicy: PluginAuthPolicy, +shareContext: PluginShareContext | null, source: PluginSource, installed: boolean, enabled: boolean, installPolicy: PluginInstallPolicy, installPolicySource: PluginInstallPolicySource | null, authPolicy: PluginAuthPolicy, /** * Availability state for installing and using the plugin. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index c335f144ec..00d39b31e3 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -294,6 +294,7 @@ export type { PluginDetail } from "./PluginDetail"; export type { PluginHookSummary } from "./PluginHookSummary"; export type { PluginInstallParams } from "./PluginInstallParams"; export type { PluginInstallPolicy } from "./PluginInstallPolicy"; +export type { PluginInstallPolicySource } from "./PluginInstallPolicySource"; export type { PluginInstallResponse } from "./PluginInstallResponse"; export type { PluginInstalledParams } from "./PluginInstalledParams"; export type { PluginInstalledResponse } from "./PluginInstalledResponse"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs index 19a4ccd889..9bd53b5d1a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs @@ -567,6 +567,17 @@ pub enum PluginInstallPolicy { InstalledByDefault, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[ts(export_to = "v2/")] +pub enum PluginInstallPolicySource { + #[serde(rename = "WORKSPACE_SETTING")] + #[ts(rename = "WORKSPACE_SETTING")] + WorkspaceSetting, + #[serde(rename = "IMPLICIT_CANONICAL_APP")] + #[ts(rename = "IMPLICIT_CANONICAL_APP")] + ImplicitCanonicalApp, +} + #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] #[ts(export_to = "v2/")] pub enum PluginAuthPolicy { @@ -613,6 +624,7 @@ pub struct PluginSummary { pub installed: bool, pub enabled: bool, pub install_policy: PluginInstallPolicy, + pub install_policy_source: Option, pub auth_policy: PluginAuthPolicy, /// Availability state for installing and using the plugin. #[serde(default)] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index 77d8a1439b..377ecba2c2 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -3650,6 +3650,7 @@ fn plugin_share_list_response_serializes_share_items() { installed: false, enabled: false, install_policy: PluginInstallPolicy::Available, + install_policy_source: Some(PluginInstallPolicySource::WorkspaceSetting), auth_policy: PluginAuthPolicy::OnUse, availability: PluginAvailability::Available, interface: None, @@ -3672,6 +3673,7 @@ fn plugin_share_list_response_serializes_share_items() { "installed": false, "enabled": false, "installPolicy": "AVAILABLE", + "installPolicySource": "WORKSPACE_SETTING", "authPolicy": "ON_USE", "availability": "AVAILABLE", "interface": null, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index a7986753ee..8300c70d94 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -213,8 +213,8 @@ Example with notification opt-out: - `marketplace/add` — add a remote plugin marketplace from an HTTP(S) Git URL, SSH Git URL, or GitHub `owner/repo` shorthand, then persist it into the user marketplace config. Returns the installed root path plus whether the marketplace was already present. - `marketplace/remove` — remove a configured marketplace by name from the user marketplace config, and delete its installed marketplace root when one exists. - `marketplace/upgrade` — upgrade all configured Git plugin marketplaces, or one named marketplace when `marketplaceName` is provided. Returns selected marketplace names, upgraded roots, and per-marketplace errors. -- `plugin/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, the remote marketplace `version` and locally materialized `localVersion` when available, plugin `availability` (`AVAILABLE` by default or `DISABLED_BY_ADMIN` for remote plugins blocked upstream), fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. Clients can explicitly request the remote `workspace-directory`, `shared-with-me`, or `created-by-me-remote` marketplace kinds. `interface.category` uses the marketplace category when present; otherwise it falls back to the plugin manifest category (**under development; do not call from production clients yet**). -- `plugin/installed` — list installed plugin rows plus any explicitly requested local install-suggestion plugin names, without fetching the broader remote catalog. Mention surfaces can use this narrower view when they need plugin mention payloads rather than plugin-page discovery data (**under development; do not call from production clients yet**). +- `plugin/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, nullable remote install-policy provenance in `installPolicySource` (`WORKSPACE_SETTING` or `IMPLICIT_CANONICAL_APP`), the remote marketplace `version` and locally materialized `localVersion` when available, plugin `availability` (`AVAILABLE` by default or `DISABLED_BY_ADMIN` for remote plugins blocked upstream), fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. Clients can explicitly request the remote `workspace-directory`, `shared-with-me`, or `created-by-me-remote` marketplace kinds. `interface.category` uses the marketplace category when present; otherwise it falls back to the plugin manifest category (**under development; do not call from production clients yet**). +- `plugin/installed` — list installed plugin rows plus any explicitly requested local install-suggestion plugin names, without fetching the broader remote catalog. Remote rows include nullable `installPolicySource`; local rows return `null`. Mention surfaces can use this narrower view when they need plugin mention payloads rather than plugin-page discovery data (**under development; do not call from production clients yet**). - `plugin/read` — read one plugin by `marketplacePath` plus `pluginName`, returning marketplace info, a list-style `summary`, manifest descriptions/interface metadata, and bundled skills/hooks/apps/MCP server names. Remote plugin details expose the canonical `shareUrl` supplied by the remote catalog when available; it is `null` for local plugins or when the catalog omits it. This field is separate from `summary.shareContext`, which continues to describe user and workspace sharing state. Returned plugin skills include their current `enabled` state after local config filtering; bundled hooks are returned as lightweight declaration summaries keyed for correlation with `hooks/list`. Use `plugin/install`'s `appsNeedingAuth` to drive post-install authentication and `app/list`'s `isAccessible` to determine current connector accessibility (**under development; do not call from production clients yet**). - `plugin/skill/read` — read remote plugin skill markdown on demand by `remoteMarketplaceName`, `remotePluginId`, and `skillName`. This lets clients preview uninstalled remote plugin skills without downloading the plugin bundle. - `skills/changed` — notification emitted when watched local skill files change. diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index 35c12d49c1..f0d7558526 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -163,6 +163,7 @@ fn convert_configured_marketplace_plugin_to_plugin_summary( share_context, source: marketplace_plugin_source_to_info(plugin.source), install_policy: plugin.policy.installation.into(), + install_policy_source: None, auth_policy: plugin.policy.authentication.into(), availability: PluginAvailability::Available, interface: plugin.interface.map(local_plugin_interface_to_info), @@ -1104,6 +1105,7 @@ impl PluginRequestProcessor { installed: outcome.plugin.installed, enabled: outcome.plugin.enabled, install_policy: outcome.plugin.policy.installation.into(), + install_policy_source: None, auth_policy: outcome.plugin.policy.authentication.into(), availability: PluginAvailability::Available, interface: outcome.plugin.interface.map(local_plugin_interface_to_info), @@ -2180,6 +2182,7 @@ fn remote_plugin_summary_to_info(summary: RemoteCatalogPluginSummary) -> PluginS installed: summary.installed, enabled: summary.enabled, install_policy: summary.install_policy, + install_policy_source: summary.install_policy_source, auth_policy: summary.auth_policy, availability: summary.availability, interface: summary.interface, diff --git a/codex-rs/app-server/tests/suite/v2/plugin_list.rs b/codex-rs/app-server/tests/suite/v2/plugin_list.rs index ae03b3a1a9..0e4bb4a16a 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_list.rs @@ -9,6 +9,7 @@ use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginInstallPolicy; +use codex_app_server_protocol::PluginInstallPolicySource; use codex_app_server_protocol::PluginInstalledParams; use codex_app_server_protocol::PluginInstalledResponse; use codex_app_server_protocol::PluginListMarketplaceKind; @@ -196,6 +197,12 @@ enabled = true ] ); assert_eq!(response.marketplace_load_errors, Vec::new()); + assert!( + response.marketplaces[0] + .plugins + .iter() + .all(|plugin| plugin.install_policy_source.is_none()) + ); Ok(()) } @@ -289,11 +296,17 @@ enabled = true remote_marketplace .plugins .iter() - .map(|plugin| plugin.id.clone()) + .map(|plugin| (plugin.id.clone(), plugin.install_policy_source)) .collect::>(), vec![ - "linear@openai-curated-remote".to_string(), - "remote-only@openai-curated-remote".to_string(), + ( + "linear@openai-curated-remote".to_string(), + Some(PluginInstallPolicySource::WorkspaceSetting), + ), + ( + "remote-only@openai-curated-remote".to_string(), + Some(PluginInstallPolicySource::WorkspaceSetting), + ), ] ); assert_eq!(response.marketplace_load_errors, Vec::new()); @@ -462,6 +475,7 @@ async fn plugin_list_keeps_valid_marketplaces_when_another_marketplace_fails_to_ installed: false, enabled: false, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: codex_app_server_protocol::PluginAvailability::Available, interface: None, @@ -754,6 +768,7 @@ async fn plugin_list_uses_alternate_discoverable_manifest_and_keeps_undiscoverab installed: false, enabled: false, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: codex_app_server_protocol::PluginAvailability::Available, interface: Some(codex_app_server_protocol::PluginInterface { @@ -794,6 +809,7 @@ async fn plugin_list_uses_alternate_discoverable_manifest_and_keeps_undiscoverab installed: false, enabled: false, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: codex_app_server_protocol::PluginAvailability::Available, interface: None, @@ -1683,6 +1699,7 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", + "installation_policy_source": "IMPLICIT_CANONICAL_APP", "authentication_policy": "ON_USE", "status": "ENABLED", "release": { @@ -1722,6 +1739,7 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", + "installation_policy_source": "WORKSPACE_SETTING", "authentication_policy": "ON_USE", "status": "ENABLED", "release": { @@ -1845,6 +1863,10 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - ); assert_eq!(remote_marketplace.plugins[0].installed, true); assert_eq!(remote_marketplace.plugins[0].enabled, true); + assert_eq!( + remote_marketplace.plugins[0].install_policy_source, + Some(PluginInstallPolicySource::ImplicitCanonicalApp) + ); assert_eq!( remote_marketplace.plugins[0].availability, codex_app_server_protocol::PluginAvailability::Available @@ -1880,6 +1902,10 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - let cached_catalog: serde_json::Value = serde_json::from_slice(&std::fs::read(&cache_files[0])?)?; assert_eq!(cached_catalog["schema_version"], serde_json::json!(1)); + assert_eq!( + cached_catalog["plugins"][0]["installation_policy_source"], + serde_json::json!("IMPLICIT_CANONICAL_APP") + ); assert_eq!( cached_catalog["plugins"][0]["release"]["interface"]["default_prompts"], serde_json::json!(["Create a Linear issue", "Review my Linear projects"]) @@ -3938,6 +3964,7 @@ fn remote_installed_plugin_body_with_optional_app_manifest( "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", + "installation_policy_source": "WORKSPACE_SETTING", "authentication_policy": "ON_USE", "release": {{ "version": "{release_version}", diff --git a/codex-rs/app-server/tests/suite/v2/plugin_read.rs b/codex-rs/app-server/tests/suite/v2/plugin_read.rs index 41b7990ec8..e3e83957cd 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_read.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_read.rs @@ -25,6 +25,7 @@ use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginInstallPolicy; +use codex_app_server_protocol::PluginInstallPolicySource; use codex_app_server_protocol::PluginReadParams; use codex_app_server_protocol::PluginReadResponse; use codex_app_server_protocol::PluginShareDiscoverability; @@ -144,6 +145,7 @@ apps = true "name": "example-plugin", "scope": "GLOBAL", "installation_policy": "AVAILABLE", + "installation_policy_source": "IMPLICIT_CANONICAL_APP", "authentication_policy": "ON_USE", "release": { "version": "1.2.1", @@ -267,6 +269,10 @@ apps = true assert_eq!(response.plugin.summary.name, "example-plugin"); assert_eq!(response.plugin.summary.source, PluginSource::Remote); assert_eq!(response.plugin.summary.share_context, None); + assert_eq!( + response.plugin.summary.install_policy_source, + Some(PluginInstallPolicySource::ImplicitCanonicalApp) + ); assert_eq!( response .plugin diff --git a/codex-rs/app-server/tests/suite/v2/plugin_share.rs b/codex-rs/app-server/tests/suite/v2/plugin_share.rs index a82b363806..3f1c2734f2 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_share.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_share.rs @@ -179,6 +179,7 @@ async fn plugin_share_save_uploads_local_plugin() -> Result<()> { installed: true, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnUse, availability: codex_app_server_protocol::PluginAvailability::Available, interface: Some(expected_plugin_interface()), @@ -583,6 +584,7 @@ async fn plugin_share_list_returns_created_workspace_plugins() -> Result<()> { installed: true, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnUse, availability: codex_app_server_protocol::PluginAvailability::Available, interface: Some(expected_plugin_interface()), @@ -1184,6 +1186,7 @@ async fn plugin_share_delete_removes_created_workspace_plugin() -> Result<()> { installed: true, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnUse, availability: codex_app_server_protocol::PluginAvailability::Available, interface: Some(expected_plugin_interface()), diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index 469a9a7fc5..5e743416f2 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -781,6 +781,7 @@ fn remote_installed_plugin_in_marketplace( name: name.to_string(), enabled: true, install_policy: codex_app_server_protocol::PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: codex_app_server_protocol::PluginAuthPolicy::OnUse, availability: codex_app_server_protocol::PluginAvailability::Available, interface: None, diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index 4c9bd2e672..b9b94f4ded 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -6,6 +6,7 @@ use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginInstallPolicy; +use codex_app_server_protocol::PluginInstallPolicySource; use codex_app_server_protocol::PluginInterface; use codex_app_server_protocol::SkillInterface; use codex_login::CodexAuth; @@ -152,6 +153,7 @@ pub struct RemoteInstalledPlugin { pub name: String, pub enabled: bool, pub install_policy: PluginInstallPolicy, + pub install_policy_source: Option, pub auth_policy: PluginAuthPolicy, pub availability: PluginAvailability, pub interface: Option, @@ -169,6 +171,7 @@ pub struct RemotePluginSummary { pub installed: bool, pub enabled: bool, pub install_policy: PluginInstallPolicy, + pub install_policy_source: Option, pub auth_policy: PluginAuthPolicy, pub availability: PluginAvailability, pub interface: Option, @@ -528,6 +531,26 @@ struct RemoteAppTemplateResponse { reason: Option, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +enum RemotePluginInstallPolicySource { + #[serde(rename = "WORKSPACE_SETTING")] + WorkspaceSetting, + #[serde(rename = "IMPLICIT_CANONICAL_APP")] + ImplicitCanonicalApp, + #[serde(other)] + Unknown, +} + +impl RemotePluginInstallPolicySource { + fn into_protocol(self) -> Option { + match self { + Self::WorkspaceSetting => Some(PluginInstallPolicySource::WorkspaceSetting), + Self::ImplicitCanonicalApp => Some(PluginInstallPolicySource::ImplicitCanonicalApp), + Self::Unknown => None, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] struct RemotePluginDirectoryItem { id: String, @@ -544,6 +567,7 @@ struct RemotePluginDirectoryItem { #[serde(default)] share_principals: Option>, installation_policy: PluginInstallPolicy, + installation_policy_source: Option, authentication_policy: PluginAuthPolicy, #[serde(rename = "status", default)] availability: PluginAvailability, @@ -1050,6 +1074,7 @@ pub fn group_remote_installed_plugins_by_marketplaces( installed: true, enabled: plugin.enabled, install_policy: plugin.install_policy, + install_policy_source: plugin.install_policy_source, auth_policy: plugin.auth_policy, availability: plugin.availability, interface: plugin.interface.clone(), @@ -1483,6 +1508,9 @@ fn build_remote_plugin_summary( installed: installed_plugin.is_some(), enabled: installed_plugin.is_some_and(|plugin| plugin.enabled), install_policy: plugin.installation_policy, + install_policy_source: plugin + .installation_policy_source + .and_then(RemotePluginInstallPolicySource::into_protocol), auth_policy: plugin.authentication_policy, availability: plugin.availability, interface: remote_plugin_interface_to_info(plugin), @@ -1562,6 +1590,9 @@ fn remote_installed_plugin_to_cache_entry( name: plugin.name.clone(), enabled: installed_plugin.enabled, install_policy: plugin.installation_policy, + install_policy_source: plugin + .installation_policy_source + .and_then(RemotePluginInstallPolicySource::into_protocol), auth_policy: plugin.authentication_policy, availability: plugin.availability, interface: remote_plugin_interface_to_info(plugin), diff --git a/codex-rs/core-plugins/src/remote/share/tests.rs b/codex-rs/core-plugins/src/remote/share/tests.rs index d7744681b9..e9887370c5 100644 --- a/codex-rs/core-plugins/src/remote/share/tests.rs +++ b/codex-rs/core-plugins/src/remote/share/tests.rs @@ -648,6 +648,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() { installed: false, enabled: false, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnUse, availability: PluginAvailability::Available, interface: Some(expected_plugin_interface()), @@ -687,6 +688,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() { installed: true, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnUse, availability: PluginAvailability::Available, interface: Some(expected_plugin_interface()), diff --git a/codex-rs/core-plugins/src/remote_tests.rs b/codex-rs/core-plugins/src/remote_tests.rs index f1d4478d7f..29fe8add19 100644 --- a/codex-rs/core-plugins/src/remote_tests.rs +++ b/codex-rs/core-plugins/src/remote_tests.rs @@ -33,6 +33,69 @@ fn build_remote_marketplace_preserves_directory_order_and_appends_installed_only ); } +#[test] +fn installation_policy_source_is_preserved_across_remote_summary_paths() { + let mut directory_plugin = directory_plugin("plugin-linear", "linear"); + directory_plugin.installation_policy_source = + Some(RemotePluginInstallPolicySource::ImplicitCanonicalApp); + let installed_plugin = RemotePluginInstalledItem { + plugin: directory_plugin.clone(), + enabled: true, + disabled_skill_names: Vec::new(), + }; + + let marketplace = build_remote_marketplace( + REMOTE_GLOBAL_MARKETPLACE_NAME, + REMOTE_GLOBAL_MARKETPLACE_DISPLAY_NAME, + vec![directory_plugin], + vec![installed_plugin.clone()], + /*include_installed_only*/ false, + ) + .expect("marketplace should be valid") + .expect("marketplace should not be empty"); + assert_eq!( + marketplace + .plugins + .into_iter() + .map(|plugin| plugin.install_policy_source) + .collect::>(), + vec![Some(PluginInstallPolicySource::ImplicitCanonicalApp)] + ); + + let mut installed_plugin = installed_plugin; + installed_plugin.plugin.installation_policy_source = + Some(RemotePluginInstallPolicySource::WorkspaceSetting); + let installed_plugin = remote_installed_plugin_to_cache_entry(&installed_plugin) + .expect("installed plugin should be valid"); + let marketplaces = group_remote_installed_plugins_by_marketplaces( + &[installed_plugin], + &[REMOTE_GLOBAL_MARKETPLACE_NAME], + ); + assert_eq!( + marketplaces + .into_iter() + .flat_map(|marketplace| marketplace.plugins) + .map(|plugin| plugin.install_policy_source) + .collect::>(), + vec![Some(PluginInstallPolicySource::WorkspaceSetting)] + ); +} + +#[test] +fn unknown_installation_policy_source_maps_to_none() { + let plugin = directory_plugin("plugin-linear", "linear"); + let mut plugin_json = serde_json::to_value(plugin).expect("plugin should serialize"); + plugin_json["installation_policy_source"] = + serde_json::Value::String("FUTURE_POLICY_SOURCE".to_string()); + let plugin: RemotePluginDirectoryItem = + serde_json::from_value(plugin_json).expect("unknown source should deserialize"); + + let summary = build_remote_plugin_summary(&plugin, /*installed_plugin*/ None) + .expect("summary should be valid"); + + assert_eq!(summary.install_policy_source, None); +} + fn directory_plugin(id: &str, name: &str) -> RemotePluginDirectoryItem { RemotePluginDirectoryItem { id: id.to_string(), @@ -44,6 +107,7 @@ fn directory_plugin(id: &str, name: &str) -> RemotePluginDirectoryItem { share_url: None, share_principals: None, installation_policy: PluginInstallPolicy::Available, + installation_policy_source: None, authentication_policy: PluginAuthPolicy::OnUse, availability: PluginAvailability::Available, release: RemotePluginReleaseResponse { diff --git a/codex-rs/tui/src/app/plugin_mentions.rs b/codex-rs/tui/src/app/plugin_mentions.rs index ae2d25a4dc..cae0caa8f0 100644 --- a/codex-rs/tui/src/app/plugin_mentions.rs +++ b/codex-rs/tui/src/app/plugin_mentions.rs @@ -173,6 +173,7 @@ mod tests { installed: true, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: PluginAvailability::Available, interface: None, diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 1f9374bbc3..5f890ab000 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -1341,6 +1341,7 @@ pub(super) fn plugins_test_summary( installed, enabled, install_policy, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: PluginAvailability::Available, interface: Some(plugins_test_interface( @@ -1370,6 +1371,7 @@ pub(super) fn plugins_test_remote_summary( installed, enabled: true, install_policy: PluginInstallPolicy::Available, + install_policy_source: None, auth_policy: PluginAuthPolicy::OnInstall, availability: PluginAvailability::Available, interface: Some(plugins_test_interface( From 7226904ed11eac2755a6641fa32af1d573355aff Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Mon, 6 Jul 2026 17:27:44 -0700 Subject: [PATCH 05/79] ci: share common workflow setup (#31318) ## Why CI jobs repeat common bootstrap steps, which makes it harder to keep Bazel and Cargo lanes aligned. Centralizing the lightweight setup gives us one place for future runner-wide optimizations without adding Rust toolchain or component installation to the Windows Bazel long poles. ## What - add zero-input `.github/actions/setup-ci` to set Cargo's git transport, install DotSlash and `just`, expose DotSlash from stable PATH locations, and enable Windows Git long paths - have `setup-bazel-ci` compose the common setup, then remove its DotSlash/test-prerequisite plumbing - migrate Bazel, Cargo CI, V8 canary, repo checks, nextest, and Windows release call sites while keeping Rust toolchain and MSVC setup explicit - preserve the existing nextest Dev Drive setup unchanged ## Validation - `just test-github-scripts` (30 tests) - parsed workflow and composite-action YAML with `yq` --- .github/actions/prepare-bazel-ci/action.yml | 5 --- .../run-argument-comment-lint/action.yml | 1 - .github/actions/setup-bazel-ci/action.yml | 27 +------------ .github/actions/setup-ci/action.yml | 39 +++++++++++++++++++ .github/scripts/test_v8_canary_changes.py | 9 +++++ .github/scripts/v8_canary_changes.py | 15 ++++++- .github/workflows/bazel.yml | 17 +++----- .github/workflows/cargo-deny.yml | 7 +--- .github/workflows/repo-checks.yml | 7 +--- .../rust-ci-full-nextest-platform.yml | 15 ++----- .github/workflows/rust-ci-full.yml | 15 ++----- .github/workflows/rust-ci.yml | 11 ++---- .github/workflows/rust-release-windows.yml | 10 ++--- .github/workflows/v8-canary.yml | 7 +--- 14 files changed, 89 insertions(+), 96 deletions(-) create mode 100644 .github/actions/setup-ci/action.yml diff --git a/.github/actions/prepare-bazel-ci/action.yml b/.github/actions/prepare-bazel-ci/action.yml index b41d80e0bc..a1beece2df 100644 --- a/.github/actions/prepare-bazel-ci/action.yml +++ b/.github/actions/prepare-bazel-ci/action.yml @@ -7,10 +7,6 @@ inputs: cache-scope: description: Logical namespace used to keep concurrent Bazel jobs from reserving the same repository cache key. required: true - install-test-prereqs: - description: Install DotSlash for Bazel-backed test jobs. - required: false - default: "false" outputs: repository-cache-path: description: Filesystem path used for the Bazel repository cache. @@ -30,7 +26,6 @@ runs: uses: ./.github/actions/setup-bazel-ci with: target: ${{ inputs.target }} - install-test-prereqs: ${{ inputs.install-test-prereqs }} - name: Compute bazel repository cache key id: cache_bazel_repository_key diff --git a/.github/actions/run-argument-comment-lint/action.yml b/.github/actions/run-argument-comment-lint/action.yml index 80fb23d417..31c752e86e 100644 --- a/.github/actions/run-argument-comment-lint/action.yml +++ b/.github/actions/run-argument-comment-lint/action.yml @@ -16,7 +16,6 @@ runs: - uses: ./.github/actions/setup-bazel-ci with: target: ${{ inputs.target }} - install-test-prereqs: true - name: Install Linux sandbox build dependencies if: ${{ runner.os == 'Linux' }} diff --git a/.github/actions/setup-bazel-ci/action.yml b/.github/actions/setup-bazel-ci/action.yml index 658dca2aa4..57e71fbc78 100644 --- a/.github/actions/setup-bazel-ci/action.yml +++ b/.github/actions/setup-bazel-ci/action.yml @@ -1,13 +1,9 @@ name: setup-bazel-ci -description: Prepare a Bazel CI runner with shared caches and optional test prerequisites. +description: Prepare a Bazel CI runner with shared caches. inputs: target: description: Target triple used for cache namespacing. required: true - install-test-prereqs: - description: Install DotSlash for Bazel-backed test jobs. - required: false - default: "false" outputs: repository-cache-path: description: Filesystem path used for the Bazel repository cache. @@ -16,21 +12,7 @@ outputs: runs: using: composite steps: - # Some integration tests rely on DotSlash being installed. - # See https://github.com/openai/codex/pull/7617. - - name: Install DotSlash - if: inputs.install-test-prereqs == 'true' - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 - - - name: Make DotSlash available in PATH (Unix) - if: inputs.install-test-prereqs == 'true' && runner.os != 'Windows' - shell: bash - run: cp "$(which dotslash)" /usr/local/bin - - - name: Make DotSlash available in PATH (Windows) - if: inputs.install-test-prereqs == 'true' && runner.os == 'Windows' - shell: pwsh - run: Copy-Item (Get-Command dotslash).Source -Destination "$env:LOCALAPPDATA\Microsoft\WindowsApps\dotslash.exe" + - uses: ./.github/actions/setup-ci - name: Set up Bazel uses: bazel-contrib/setup-bazel@c5acdfb288317d0b5c0bbd7a396a3dc868bb0f86 # 0.19.0 @@ -124,8 +106,3 @@ runs: if: runner.os == 'Windows' shell: pwsh run: ./.github/scripts/compute-bazel-windows-path.ps1 - - - name: Enable Git long paths (Windows) - if: runner.os == 'Windows' - shell: pwsh - run: git config --global core.longpaths true diff --git a/.github/actions/setup-ci/action.yml b/.github/actions/setup-ci/action.yml new file mode 100644 index 0000000000..0924e29616 --- /dev/null +++ b/.github/actions/setup-ci/action.yml @@ -0,0 +1,39 @@ +name: setup-ci +description: Prepare common tools and environment shared by CI jobs. + +runs: + using: composite + steps: + - name: Prefer the Git CLI for Cargo git dependencies + shell: bash + run: echo "CARGO_NET_GIT_FETCH_WITH_CLI=true" >> "$GITHUB_ENV" + + - name: Install DotSlash + uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 + + - name: Install just + uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 + with: + tool: just@1.51.0 + + # Some integration tests spawn DotSlash from a stable system path rather + # than inheriting the action-local PATH entry. + - name: Make DotSlash available in PATH (Unix) + if: runner.os != 'Windows' + shell: bash + run: | + if [[ -w /usr/local/bin ]]; then + cp "$(which dotslash)" /usr/local/bin + else + sudo cp "$(which dotslash)" /usr/local/bin + fi + + - name: Make DotSlash available in PATH (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: Copy-Item (Get-Command dotslash).Source -Destination "$env:LOCALAPPDATA\Microsoft\WindowsApps\dotslash.exe" + + - name: Enable Git long paths (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: git config --global core.longpaths true diff --git a/.github/scripts/test_v8_canary_changes.py b/.github/scripts/test_v8_canary_changes.py index e4ce6424ed..0d8d9a2b32 100644 --- a/.github/scripts/test_v8_canary_changes.py +++ b/.github/scripts/test_v8_canary_changes.py @@ -4,6 +4,7 @@ import unittest from pathlib import Path from v8_canary_changes import changed_files +from v8_canary_changes import canary_required from v8_canary_changes import merge_base from v8_canary_changes import resolved_v8_version from v8_canary_changes import windows_source_required @@ -46,6 +47,14 @@ 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_manual_dispatch_requires_source_build(self) -> None: self.assertTrue( windows_source_required( diff --git a/.github/scripts/v8_canary_changes.py b/.github/scripts/v8_canary_changes.py index 0acc4ec3f6..53a064e384 100644 --- a/.github/scripts/v8_canary_changes.py +++ b/.github/scripts/v8_canary_changes.py @@ -21,6 +21,7 @@ ROOT = Path(__file__).resolve().parents[2] CANARY_PATH_PATTERNS = { ".bazelrc", ".github/actions/setup-bazel-ci/**", + ".github/actions/setup-ci/**", ".github/scripts/run_bazel_with_buildbuddy.py", ".github/scripts/rusty_v8_bazel.py", ".github/scripts/rusty_v8_module_bazel.py", @@ -40,6 +41,7 @@ CANARY_PATH_PATTERNS = { # Windows source builds are a narrower, more expensive subset of the canary. # A V8 version change also requires them even when no path below changed. WINDOWS_SOURCE_BUILD_PATHS = { + ".github/actions/setup-ci/**", ".github/scripts/rusty_v8_bazel.py", ".github/scripts/rusty_v8_module_bazel.py", ".github/scripts/v8_canary_changes.py", @@ -72,6 +74,15 @@ def canary_required( ) +def matching_windows_source_paths(changed_files: set[str]) -> set[str]: + """Return changed paths that require Windows rusty_v8 source builds.""" + return { + path + for path in changed_files + if any(fnmatchcase(path, pattern) for pattern in WINDOWS_SOURCE_BUILD_PATHS) + } + + def resolved_v8_version(cargo_lock: bytes) -> str: versions = sorted( { @@ -96,7 +107,7 @@ def windows_source_required( return ( force or base_v8_version != head_v8_version - or not changed_files.isdisjoint(WINDOWS_SOURCE_BUILD_PATHS) + or bool(matching_windows_source_paths(changed_files)) ) @@ -165,7 +176,7 @@ def main() -> None: if matched_canary_paths else "no relevant changes" ) - matched_windows_paths = sorted(files & WINDOWS_SOURCE_BUILD_PATHS) + matched_windows_paths = sorted(matching_windows_source_paths(files)) windows_source_reason = ( ", ".join(matched_windows_paths) if matched_windows_paths diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index 10dd8670de..3e48b741b7 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -57,10 +57,12 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false - - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 - if: matrix.os == 'ubuntu-24.04' && matrix.target == 'x86_64-unknown-linux-gnu' + - name: Prepare Bazel CI + id: prepare_bazel + uses: ./.github/actions/prepare-bazel-ci with: - tool: just + target: ${{ matrix.target }} + cache-scope: bazel-${{ github.job }} - name: Check rusty_v8 MODULE.bazel checksums if: matrix.os == 'ubuntu-24.04' && matrix.target == 'x86_64-unknown-linux-gnu' @@ -69,13 +71,6 @@ jobs: python3 .github/scripts/rusty_v8_bazel.py check-module-bazel just test-github-scripts - - name: Prepare Bazel CI - id: prepare_bazel - uses: ./.github/actions/prepare-bazel-ci - with: - target: ${{ matrix.target }} - cache-scope: bazel-${{ github.job }} - install-test-prereqs: "true" - name: Check MODULE.bazel.lock is up to date if: matrix.os == 'ubuntu-24.04' && matrix.target == 'x86_64-unknown-linux-gnu' shell: bash @@ -176,7 +171,6 @@ jobs: # not save it from every shard below; duplicate uploads would sit on # the PR-blocking critical path after the useful test work is done. cache-scope: bazel-test - install-test-prereqs: "true" - name: bazel test shard env: @@ -287,7 +281,6 @@ jobs: with: target: x86_64-pc-windows-gnullvm cache-scope: bazel-${{ github.job }} - install-test-prereqs: "true" - name: bazel test //... env: diff --git a/.github/workflows/cargo-deny.yml b/.github/workflows/cargo-deny.yml index be00e1147d..ccbf80e12f 100644 --- a/.github/workflows/cargo-deny.yml +++ b/.github/workflows/cargo-deny.yml @@ -3,11 +3,6 @@ name: cargo-deny on: workflow_call: -# Cargo's libgit2 transport has been flaky when fetching git dependencies with -# nested submodules. Prefer the system git CLI across every Cargo invocation. -env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - jobs: cargo-deny: runs-on: ubuntu-latest @@ -21,6 +16,8 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - uses: ./.github/actions/setup-ci + - name: Install Rust toolchain uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 diff --git a/.github/workflows/repo-checks.yml b/.github/workflows/repo-checks.yml index 3d0504172d..97932c4fd4 100644 --- a/.github/workflows/repo-checks.yml +++ b/.github/workflows/repo-checks.yml @@ -16,6 +16,8 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - uses: ./.github/actions/setup-ci + - name: Verify codex-rs Cargo manifests inherit workspace settings run: python3 .github/scripts/verify_cargo_workspace_manifests.py @@ -76,15 +78,10 @@ jobs: - name: Check root README ToC run: python3 scripts/readme_toc.py README.md - - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 - with: - tool: just@1.51.0 - name: Install uv uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0 with: version: "0.11.3" - - name: Install DotSlash - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 - name: Check formatting (run `just fmt` to fix) run: just fmt-check diff --git a/.github/workflows/rust-ci-full-nextest-platform.yml b/.github/workflows/rust-ci-full-nextest-platform.yml index 65d1fb2be5..825c2d73d6 100644 --- a/.github/workflows/rust-ci-full-nextest-platform.yml +++ b/.github/workflows/rust-ci-full-nextest-platform.yml @@ -48,11 +48,6 @@ on: default: false type: boolean -# Caller workflow-level env does not flow through workflow_call, so keep the -# Cargo git transport hardening on the archive and shard jobs directly here. -env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - jobs: archive: name: Build nextest archive @@ -81,6 +76,8 @@ jobs: shell: pwsh run: ../.github/scripts/setup-dev-drive.ps1 + - uses: ./.github/actions/setup-ci + - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} shell: bash @@ -91,9 +88,6 @@ jobs: sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends pkg-config libcap-dev bubblewrap fi - - name: Install DotSlash - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 - - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: targets: ${{ inputs.target }} @@ -306,6 +300,8 @@ jobs: with: persist-credentials: false + - uses: ./.github/actions/setup-ci + - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} shell: bash @@ -316,9 +312,6 @@ jobs: sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends pkg-config libcap-dev bubblewrap fi - - name: Install DotSlash - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 - - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: targets: ${{ inputs.target }} diff --git a/.github/workflows/rust-ci-full.yml b/.github/workflows/rust-ci-full.yml index cb99c8911e..dc38aaa86d 100644 --- a/.github/workflows/rust-ci-full.yml +++ b/.github/workflows/rust-ci-full.yml @@ -8,13 +8,6 @@ on: - "**full-ci**" workflow_dispatch: -# CI builds in debug (dev) for faster signal. -env: - # Cargo's libgit2 transport has been flaky on macOS when fetching git - # dependencies with nested submodules. Use the system git CLI, which has - # better network/proxy behavior and matches Cargo's own suggested fallback. - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - jobs: # --- CI that doesn't need specific targets --------------------------------- general: @@ -27,12 +20,10 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: components: rustfmt - - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 - with: - tool: just - name: cargo fmt run: cargo fmt -- --config imports_granularity=Item --check - name: Rust benchmark smoke test @@ -48,6 +39,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: @@ -65,6 +57,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: toolchain: nightly-2025-09-18 @@ -123,7 +116,6 @@ jobs: - uses: ./.github/actions/setup-bazel-ci with: target: ${{ runner.os }} - install-test-prereqs: true - name: Install Linux sandbox build dependencies if: ${{ runner.os == 'Linux' }} shell: bash @@ -256,6 +248,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - name: Install Linux build dependencies if: ${{ runner.os == 'Linux' }} shell: bash diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index cf1afdfe2d..01d51aac0e 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -3,11 +3,6 @@ on: workflow_call: workflow_dispatch: -# Cargo's libgit2 transport has been flaky when fetching git dependencies with -# nested submodules. Prefer the system git CLI across every Cargo invocation. -env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - jobs: # --- Detect what changed so the fast PR workflow only runs relevant jobs ---- changed: @@ -76,12 +71,10 @@ jobs: with: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: components: rustfmt - - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 - with: - tool: just - name: cargo fmt run: cargo fmt -- --config imports_granularity=Item --check - name: Rust benchmark smoke test @@ -104,6 +97,7 @@ jobs: with: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2.62.49 with: @@ -128,6 +122,7 @@ jobs: with: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - uses: ./.github/actions/setup-ci - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 - name: Install nightly argument-comment-lint toolchain shell: bash diff --git a/.github/workflows/rust-release-windows.yml b/.github/workflows/rust-release-windows.yml index 31d832fcbe..ccb2ee13f7 100644 --- a/.github/workflows/rust-release-windows.yml +++ b/.github/workflows/rust-release-windows.yml @@ -3,10 +3,7 @@ name: rust-release-windows on: workflow_call: -# Cargo's libgit2 transport has been flaky when fetching git dependencies with -# nested submodules. Prefer the system git CLI across every Cargo invocation. env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" WINDOWS_BINARIES: "codex codex-code-mode-host codex-responses-api-proxy codex-windows-sandbox-setup codex-command-runner codex-app-server" jobs: @@ -72,6 +69,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - name: Print runner specs (Windows) shell: powershell run: | @@ -164,6 +162,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + - uses: ./.github/actions/setup-ci - name: Download prebuilt Windows binaries uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -221,6 +220,8 @@ jobs: with: persist-credentials: false + - uses: ./.github/actions/setup-ci + - name: Download prebuilt Windows primary binaries uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -270,9 +271,6 @@ jobs: "$dest/${binary}-${{ matrix.target }}.exe" done - - name: Install DotSlash - uses: facebook/install-dotslash@1e4e7b3e07eaca387acb98f1d4720e0bee8dbb6a # v2 - - name: Build Codex package archives shell: bash run: | diff --git a/.github/workflows/v8-canary.yml b/.github/workflows/v8-canary.yml index 53d9585108..f338c341e4 100644 --- a/.github/workflows/v8-canary.yml +++ b/.github/workflows/v8-canary.yml @@ -9,11 +9,6 @@ on: pull_request: {} workflow_dispatch: -# Cargo's libgit2 transport has been flaky when fetching git dependencies with -# nested submodules. Prefer the system git CLI for Cargo builds and smoke tests. -env: - CARGO_NET_GIT_FETCH_WITH_CLI: "true" - concurrency: group: ${{ github.workflow }}::${{ github.event.pull_request.number > 0 && format('pr-{0}', github.event.pull_request.number) || github.ref_name }} cancel-in-progress: ${{ github.ref_name != 'main' }} @@ -325,6 +320,8 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: ./.github/actions/setup-ci + - name: Configure git for upstream checkout shell: bash run: git config --global core.symlinks true From 8a18312ee58b6dce10edca44bbed90365f384edb Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Mon, 6 Jul 2026 17:42:43 -0700 Subject: [PATCH 06/79] app-server: cover selected environments in integration tests (#29992) ## Why Now that basic cross-OS app/exec support is wired up, it's time to clean up the tech debt of the remote_env_windows test and make sure its test logic is covered in more maintainable feature-specific tests. ## What - Add focused app-server tests for target-native `AGENTS.md` sources and content, plus shell and cwd context, while preserving explicit TODO baselines for the remaining host-scoped metadata. - Add a `TestAppServer` helper that waits for and returns the matching typed turn completion. - Remove redundant app-server coverage and dependencies from `remote_env_windows` while retaining its exec and apply-patch smoke coverage. A follow-up will remove these. ## Validation - `just test -p codex-app-server` - `bazel test //codex-rs/app-server:app-server-all-wine-exec-test --test_output=errors` - `bazel test //codex-rs/core/tests/remote_env_windows:smoke-test --test_output=errors` --- .../tests/common/test_app_server.rs | 50 +++- codex-rs/app-server/tests/suite/v2/mod.rs | 1 + .../tests/suite/v2/selected_environment.rs | 252 ++++++++++++++++++ .../core/tests/remote_env_windows/BUILD.bazel | 6 - .../remote_env_windows_test.rs | 171 ------------ 5 files changed, 298 insertions(+), 182 deletions(-) create mode 100644 codex-rs/app-server/tests/suite/v2/selected_environment.rs diff --git a/codex-rs/app-server/tests/common/test_app_server.rs b/codex-rs/app-server/tests/common/test_app_server.rs index cbb8ff161e..0fc0594baa 100644 --- a/codex-rs/app-server/tests/common/test_app_server.rs +++ b/codex-rs/app-server/tests/common/test_app_server.rs @@ -111,6 +111,7 @@ use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnEnvironmentParams; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::WindowsSandboxSetupStartParams; use codex_exec_server::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR; @@ -216,15 +217,21 @@ impl TestAppServer { Ok(app_server) } + /// 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`]. + pub fn auto_env(&self) -> anyhow::Result<&TestEnv> { + self.auto_env + .as_ref() + .context("auto environment is unavailable; use TestAppServer::new_with_auto_env") + } + /// 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`]. pub fn auto_env_params(&self) -> anyhow::Result { - let selection = self - .auto_env - .as_ref() - .context("auto environment is unavailable; use TestAppServer::new_with_auto_env")? - .selection(); + let selection = self.auto_env()?.selection(); Ok(TurnEnvironmentParams { environment_id: selection.environment_id.clone(), cwd: selection.cwd.clone().into(), @@ -1052,6 +1059,39 @@ impl TestAppServer { self.send_request("turn/start", params).await } + /// Start a turn and return its matching typed completion notification. + pub async fn start_turn_and_wait_for_completion( + &mut self, + params: TurnStartParams, + ) -> anyhow::Result { + let thread_id = params.thread_id.clone(); + let request_id = self.send_turn_start_request(params).await?; + let response = self + .read_stream_until_response_message(RequestId::Integer(request_id)) + .await?; + let TurnStartResponse { turn } = crate::to_response(response)?; + let notification = self + .read_stream_until_matching_notification( + "turn/completed for started turn", + |notification| { + notification.method == "turn/completed" + && notification.params.as_ref().is_some_and(|params| { + serde_json::from_value::(params.clone()) + .is_ok_and(|completed| { + completed.thread_id == thread_id && completed.turn.id == turn.id + }) + }) + }, + ) + .await?; + let params = notification + .params + .context("turn/completed notification must include params")?; + let completed = serde_json::from_value(params) + .context("failed to deserialize turn/completed notification")?; + Ok(completed) + } + /// Send a `thread/inject_items` JSON-RPC request (v2). pub async fn send_thread_inject_items_request( &mut self, diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index bdb03271d0..3d55079dc6 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -60,6 +60,7 @@ mod review; mod safety_check_downgrade; #[cfg(not(target_os = "windows"))] mod selected_capability_stack; +mod selected_environment; mod skills_list; mod sleep; mod thread_archive; diff --git a/codex-rs/app-server/tests/suite/v2/selected_environment.rs b/codex-rs/app-server/tests/suite/v2/selected_environment.rs new file mode 100644 index 0000000000..513cd25d7f --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/selected_environment.rs @@ -0,0 +1,252 @@ +use std::collections::BTreeMap; +use std::time::Duration; + +use anyhow::Context; +use anyhow::Result; +use app_test_support::PathBufExt; +use app_test_support::TestAppServer; +use app_test_support::to_response; +use app_test_support::write_mock_responses_config_toml; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadStartParams; +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 pretty_assertions::assert_eq; +use tempfile::TempDir; +use tokio::time::timeout; + +const AGENTS_INSTRUCTIONS: &str = "selected environment workspace instructions"; +const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); + +fn text_turn_params(thread_id: String, prompt: &str) -> TurnStartParams { + TurnStartParams { + thread_id, + input: vec![V2UserInput::Text { + text: prompt.to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + } +} + +#[tokio::test] +async fn thread_start_reports_selected_environment_metadata() -> Result<()> { + let server = responses::start_mock_server().await; + let codex_home = TempDir::new()?; + write_mock_responses_config_toml( + codex_home.path(), + &server.uri(), + &BTreeMap::new(), + /*auto_compact_limit*/ 100_000, + /*requires_openai_auth*/ None, + "mock_provider", + "compact", + )?; + let mut app_server = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; + + let request_id = app_server + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let ThreadStartResponse { + cwd, + runtime_workspace_roots, + active_permission_profile, + .. + } = to_response(response)?; + let host_cwd = codex_home.path().to_path_buf().abs().canonicalize()?; + let cwd = cwd.canonicalize()?; + let runtime_workspace_roots = runtime_workspace_roots + .into_iter() + .map(|root| root.canonicalize()) + .collect::>>()?; + assert_eq!( + (cwd, runtime_workspace_roots, active_permission_profile), + ( + // TODO(anp): Return the selected environment's native cwd from thread/start. + host_cwd.clone(), + // TODO(anp): Derive runtime workspace roots from the selected remote environment. + vec![host_cwd], + // TODO(anp): Report the implicit built-in permission profile instead of None. + None, + ) + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_start_reports_selected_environment_instruction_source() -> Result<()> { + let server = responses::start_mock_server().await; + let response_mock = responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "done"), + responses::ev_completed("resp-1"), + ]), + ) + .await; + let codex_home = TempDir::new()?; + write_mock_responses_config_toml( + codex_home.path(), + &server.uri(), + &BTreeMap::new(), + /*auto_compact_limit*/ 100_000, + /*requires_openai_auth*/ None, + "mock_provider", + "compact", + )?; + let mut app_server = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; + + let (agents_source, environment_cwd) = { + let auto_env = app_server.auto_env()?; + let environment_cwd = auto_env.selection().cwd.clone(); + let agents_source = environment_cwd.join("AGENTS.md")?; + auto_env + .environment() + .get_filesystem() + .write_file( + &agents_source, + AGENTS_INSTRUCTIONS.as_bytes().to_vec(), + /*sandbox*/ None, + ) + .await?; + (agents_source, environment_cwd) + }; + + let request_id = app_server + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let response: ThreadStartResponse = to_response(response)?; + + assert_eq!(response.instruction_sources, vec![agents_source.into()]); + timeout( + DEFAULT_READ_TIMEOUT, + app_server.start_turn_and_wait_for_completion(text_turn_params( + response.thread.id, + "inspect workspace instructions", + )), + ) + .await??; + + let user_context = response_mock.single_request().message_input_texts("user"); + let instructions = user_context + .iter() + .find(|text| text.starts_with("# AGENTS.md instructions")) + .context("selected environment instructions should be model visible")?; + let expected_instructions = format!( + "# AGENTS.md instructions for {}\n\n\n{AGENTS_INSTRUCTIONS}\n", + environment_cwd.inferred_native_path_string() + ); + assert_eq!(instructions, &expected_instructions); + + Ok(()) +} + +#[tokio::test] +async fn turn_model_context_uses_selected_environment() -> Result<()> { + let server = responses::start_mock_server().await; + let response_mock = responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "done"), + responses::ev_completed("resp-1"), + ]), + ) + .await; + let codex_home = TempDir::new()?; + write_mock_responses_config_toml( + codex_home.path(), + &server.uri(), + &BTreeMap::new(), + /*auto_compact_limit*/ 100_000, + /*requires_openai_auth*/ None, + "mock_provider", + "compact", + )?; + let mut app_server = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; + let (environment_cwd, environment_shell) = { + let auto_env = app_server.auto_env()?; + ( + auto_env.selection().cwd.clone(), + auto_env.environment().info().await?.shell.name, + ) + }; + + let request_id = app_server + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let ThreadStartResponse { + thread, + runtime_workspace_roots, + .. + } = to_response(response)?; + timeout( + DEFAULT_READ_TIMEOUT, + app_server.start_turn_and_wait_for_completion(text_turn_params( + thread.id, + "inspect the selected environment", + )), + ) + .await??; + + let user_context = response_mock.single_request().message_input_texts("user"); + let environment_context = user_context + .iter() + .find(|text| text.starts_with("")) + .context("selected environment context should be model visible")?; + let shell = environment_context + .lines() + .find(|line| line.trim_start().starts_with("")) + .map(str::trim) + .map(str::to_string); + let cwd = environment_context + .lines() + .find(|line| line.trim_start().starts_with("")) + .map(str::trim) + .map(str::to_string); + assert_eq!( + (shell, cwd), + ( + Some(format!("{environment_shell}")), + Some(format!( + "{}", + environment_cwd.inferred_native_path_string() + )), + ) + ); + let [runtime_workspace_root] = runtime_workspace_roots.as_slice() else { + anyhow::bail!("expected one runtime workspace root"); + }; + let expected_workspace_roots = format!( + "{}", + runtime_workspace_root.as_path().display() + ); + // TODO(anp): Derive model-visible workspace roots from the selected remote environment and + // render them using its native path convention. + assert!(environment_context.contains(&expected_workspace_roots)); + + Ok(()) +} diff --git a/codex-rs/core/tests/remote_env_windows/BUILD.bazel b/codex-rs/core/tests/remote_env_windows/BUILD.bazel index 9b5ce52bd9..1f2465ffcb 100644 --- a/codex-rs/core/tests/remote_env_windows/BUILD.bazel +++ b/codex-rs/core/tests/remote_env_windows/BUILD.bazel @@ -6,15 +6,10 @@ wine_rust_test( srcs = ["remote_env_windows_test.rs"], crate_name = "remote_env_windows_test", crate_root = "remote_env_windows_test.rs", - host_binaries = { - "codex-app-server": "//codex-rs/app-server:codex-app-server", - }, windows_binaries = { "wine-windows-exec-server": "//codex-rs/exec-server/testing:windows-exec-server", }, deps = [ - "//codex-rs/app-server-protocol", - "//codex-rs/app-server/tests/common", "//codex-rs/core/tests/common", "//codex-rs/exec-server", "//codex-rs/exec-server/testing:wine-exec-server-test-support", @@ -24,7 +19,6 @@ wine_rust_test( "@crates//:anyhow", "@crates//:pretty_assertions", "@crates//:serde_json", - "@crates//:tempfile", "@crates//:tokio", ], ) diff --git a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs index 04f8914982..ff80316061 100644 --- a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs +++ b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs @@ -2,20 +2,7 @@ use anyhow::Context; use anyhow::Result; -use app_test_support::PathBufExt; -use app_test_support::TestAppServer; -use app_test_support::create_mock_responses_server_repeating_assistant; -use app_test_support::to_response; -use app_test_support::write_mock_responses_config_toml; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnEnvironmentParams; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::UserInput as V2UserInput; use codex_exec_server::REMOTE_ENVIRONMENT_ID; -use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR; use codex_features::Feature; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; @@ -35,20 +22,11 @@ use core_test_support::responses::start_mock_server; use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; -use codex_utils_path_uri::LegacyAppPathString; -use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use pretty_assertions::assert_eq; -use serde_json::Value; use serde_json::json; -use std::collections::BTreeMap; -use std::fs; -use tempfile::TempDir; -use tokio::time::timeout; use wine_exec_server_test_support::WineExecServer; -const APP_SERVER_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn windows_exec_server_runs_with_native_shell_and_cwd() -> Result<()> { const CALL_ID: &str = "wine-cmd-smoke"; @@ -244,152 +222,3 @@ async fn windows_exec_server_runs_with_native_shell_and_cwd() -> Result<()> { }) .await } - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn app_server_starts_thread_with_windows_environment_native_cwd() -> Result<()> { - const AGENTS_INSTRUCTIONS: &str = "remote Windows workspace instructions"; - const NATIVE_CWD: &str = r"C:\windows"; - - WineExecServer - .scope(|exec_server_url, wine_prefix| async move { - let agents_path = PathUri::parse("file:///C:/windows/AGENTS.md")?; - fs::write( - wine_prefix.join("drive_c").join("windows").join("AGENTS.md"), - AGENTS_INSTRUCTIONS, - )?; - - let codex_home = TempDir::new()?; - let server = create_mock_responses_server_repeating_assistant("done").await; - write_mock_responses_config_toml( - codex_home.path(), - &server.uri(), - &BTreeMap::new(), - 100_000, - /*requires_openai_auth*/ None, - "mock", - "compact", - )?; - let mut app_server = TestAppServer::new_with_env( - codex_home.path(), - &[( - CODEX_EXEC_SERVER_URL_ENV_VAR, - Some(exec_server_url.as_str()), - )], - ) - .await?; - timeout(APP_SERVER_READ_TIMEOUT, app_server.initialize()).await??; - - let request_id = app_server - .send_thread_start_request(ThreadStartParams { - environments: Some(vec![TurnEnvironmentParams { - environment_id: REMOTE_ENVIRONMENT_ID.to_string(), - cwd: serde_json::from_value::(json!(NATIVE_CWD))?, - }]), - ..Default::default() - }) - .await?; - let response = timeout( - APP_SERVER_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: ThreadStartResponse = to_response(response)?; - assert!(!response.thread.id.is_empty()); - let host_cwd = codex_home.path().to_path_buf().abs(); - // TODO(anp): Return the selected environment's native cwd from thread/start. - assert_eq!(response.cwd, host_cwd); - // TODO(anp): Derive runtime workspace roots from the selected remote environment. - assert_eq!(response.runtime_workspace_roots, vec![host_cwd]); - assert_eq!( - response.instruction_sources, - vec![LegacyAppPathString::from_path_uri( - &agents_path, - PathConvention::Windows, - )?] - ); - // TODO(anp): Report the implicit built-in permission profile instead of None. - assert_eq!(response.active_permission_profile, None); - - let turn_request_id = app_server - .send_turn_start_request(TurnStartParams { - thread_id: response.thread.id, - client_user_message_id: None, - input: vec![V2UserInput::Text { - text: "say done".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - let turn_response = timeout( - APP_SERVER_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(turn_request_id)), - ) - .await??; - let _: TurnStartResponse = to_response(turn_response)?; - timeout( - APP_SERVER_READ_TIMEOUT, - app_server.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - let requests = server - .received_requests() - .await - .context("failed to fetch received requests")?; - let first_request = requests - .iter() - .find(|request| request.url.path().ends_with("/responses")) - .context("turn should send a Responses request")?; - let body = first_request.body_json::()?; - let remote_instructions = body["input"] - .as_array() - .into_iter() - .flatten() - .filter(|item| item.get("role").and_then(Value::as_str) == Some("user")) - .filter_map(|item| item.get("content").and_then(Value::as_array)) - .flatten() - .filter_map(|content| content.get("text").and_then(Value::as_str)) - .find(|text| text.contains(AGENTS_INSTRUCTIONS)) - .context("remote workspace instructions should be model visible")?; - assert!(remote_instructions.contains(r"# AGENTS.md instructions for C:\windows")); - let environment_context = body["input"] - .as_array() - .into_iter() - .flatten() - .filter(|item| item.get("role").and_then(Value::as_str) == Some("user")) - .filter_map(|item| item.get("content").and_then(Value::as_array)) - .flatten() - .filter_map(|content| content.get("text").and_then(Value::as_str)) - .find(|text| text.starts_with("")) - .context("environment context should be model visible")?; - // The model should see the remote environment's shell, not the Linux app-server's - // host shell. - assert_eq!( - environment_context - .lines() - .find(|line| line.trim_start().starts_with("")) - .map(str::trim), - Some("powershell"), - ); - // The model should see cwd using the remote environment's native path convention, not - // the Linux app-server's host path convention. - assert_eq!( - environment_context - .lines() - .find(|line| line.trim_start().starts_with("")) - .map(str::trim), - Some(r"C:\windows"), - ); - let host_workspace_roots = format!( - "{}", - codex_home.path().display() - ); - // TODO(anp): Derive model-visible workspace roots from the selected remote environment - // and render them using its native path convention. - assert!(environment_context.contains(&host_workspace_roots)); - - Ok(()) - }) - .await -} From 45be435135a7936f4b01916a6d8f0c8091229fb8 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 6 Jul 2026 18:08:35 -0700 Subject: [PATCH 07/79] Warn when configured service tiers are unsupported (#31284) ## Why Codex currently omits a configured `service_tier` when the selected model's catalog entry does not advertise support for it. That fallback is silent, so users can unknowingly send requests at the default tier instead. This makes cases such as #26604 difficult to diagnose. ## What changed - Emit the shared core `Warning` event during session startup when a configured service tier will be omitted because the initial model does not advertise support for it. - Do not warn on later model or service-tier changes, which keeps warning emission stateless and avoids client-specific handling. - Keep the existing request filtering behavior unchanged. ## Validation - `just test -p codex-core unsupported_service_tier` - `just test -p codex-core unsupported_configured_service_tier_warns_at_session_start` ### Manual validation - Launched the real TUI with the bundled catalog, where `gpt-5.5` advertises the `priority` tier but not `flex`, and configured `service_tier = "flex"`. - Confirmed the unsupported-tier warning appeared exactly once during startup. - Submitted two turns through a local Responses API SSE stub; both received mock replies and neither emitted another warning. - Inspected both captured `/v1/responses` request bodies and confirmed that neither contained a `service_tier` field. - Repeated the two-turn TUI flow against the live Responses API; both turns completed and the warning was not repeated. --- codex-rs/core/src/session/mod.rs | 33 ++++++++++++++-- codex-rs/core/tests/suite/model_switching.rs | 40 ++++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index ba8eacb395..91a21ef731 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -629,11 +629,14 @@ impl Codex { developer_instructions: None, }, }; - let service_tier = get_service_tier( - config.service_tier.clone(), - config.features.enabled(Feature::FastMode), + let fast_mode_enabled = config.features.enabled(Feature::FastMode); + let initial_service_tier_warning = unsupported_service_tier_warning( + config.service_tier.as_deref(), + fast_mode_enabled, &model_info, ); + let service_tier = + get_service_tier(config.service_tier.clone(), fast_mode_enabled, &model_info); let session_configuration = SessionConfiguration { provider: config.model_provider.clone(), collaboration_mode, @@ -706,6 +709,14 @@ impl Codex { error!("Failed to create session: {e:#}"); map_session_init_error(&e, &config.codex_home) })?; + if let Some(message) = initial_service_tier_warning { + session + .send_event_raw(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::Warning(WarningEvent { message }), + }) + .await; + } let thread_id = session.thread_id; // This task will run until Op::Shutdown is received. @@ -908,6 +919,22 @@ fn get_service_tier( }) } +fn unsupported_service_tier_warning( + configured_service_tier: Option<&str>, + fast_mode_enabled: bool, + model_info: &ModelInfo, +) -> Option { + let service_tier = configured_service_tier.filter(|service_tier| { + fast_mode_enabled + && *service_tier != SERVICE_TIER_DEFAULT_REQUEST_VALUE + && !model_info.supports_service_tier(service_tier) + })?; + Some(format!( + "Configured service tier `{service_tier}` is not advertised as supported for model `{}` and will be omitted from requests.", + model_info.slug + )) +} + fn session_permission_profile_state_from_config( config: &Config, ) -> CodexResult { diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index b08ca7cc8a..9ef3675b3e 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -387,6 +387,46 @@ async fn unsupported_service_tier_is_omitted_from_http_turn() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn unsupported_configured_service_tier_warns_at_session_start() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let model_slug = "test-no-tier-model"; + let model = test_model_info( + model_slug, + model_slug, + "no service tiers", + default_input_modalities(), + ); + let mut builder = test_codex() + .with_model(model_slug) + .with_config(move |config| { + config.service_tier = Some(ServiceTier::Flex.request_value().to_string()); + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + }); + let test = builder.build(&server).await?; + + let warning = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::Warning(warning) + if warning.message.contains("will be omitted from requests") + ) + }) + .await; + let EventMsg::Warning(warning) = warning else { + unreachable!("wait_for_event matched a warning") + }; + assert_eq!( + warning.message, + "Configured service tier `flex` is not advertised as supported for model `test-no-tier-model` and will be omitted from requests." + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn default_service_tier_override_is_omitted_from_http_turn() -> Result<()> { skip_if_no_network!(Ok(())); From 9acfe8965d44af60c71227f4577902e467ba5119 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 6 Jul 2026 18:12:24 -0700 Subject: [PATCH 08/79] Extract shared HTTP transport into codex-http-client (#31323) ## Why Codex-owned HTTP construction currently lives in `codex-client` alongside higher-level retry, SSE, and request-telemetry policy. That makes it difficult to apply shared network behavior consistently across crates, particularly system proxy/PAC resolution, custom CA handling, and the ChatGPT Cloudflare cookie policy. It also leaves no clear crate boundary for migrating direct `reqwest` usage behind a single Codex abstraction. This change establishes that low-level ownership boundary without changing request behavior. It builds on the system proxy support introduced in #26706, #26707, #26708, and #26709. ## What changed - Added `codex-rs/http-client` as the `codex-http-client` crate. - Moved request/response types, the concrete `reqwest` transport, custom CA handling, Cloudflare cookie policy, and macOS/Windows proxy resolution into the new crate. - Kept retry, SSE, and request-telemetry policy in `codex-client`. - Re-exported the moved API from `codex-client`, including compatibility aliases for `CodexHttpClient` and `CodexRequestBuilder`, so existing consumers do not change in this PR. - Moved the existing proxy and custom-CA tests with their implementation. ## Scope boundary This PR deliberately stops at the crate extraction. Stacked follow-up #31331 migrates downstream imports from `codex-client` to `codex-http-client`, keeping this change focused on ownership and compatibility rather than mixing in repository-wide call-site churn. ## Review guide GitHub reports 30 changed files, of which 17 are detected renames. A useful review order is: 1. Review the new boundary in `codex-rs/http-client/Cargo.toml` and `codex-rs/http-client/src/lib.rs`. 2. Review `codex-rs/codex-client/Cargo.toml` and `codex-rs/codex-client/src/lib.rs` for what remains in the higher-level crate and how compatibility is preserved. 3. Treat the renamed implementation and test files as moves. Their meaningful edits are limited to crate paths and normalizing the new crate's type names to `HttpClient` and `RequestBuilder`. 4. Review `codex-rs/Cargo.toml`, `codex-rs/Cargo.lock`, and the two `BUILD.bazel` files as mechanical workspace integration. ## Test plan - `just test -p codex-http-client -p codex-client` (38 tests) - Compile-checked the unchanged `codex-api`, `codex-backend-client`, `codex-cloud-tasks`, `codex-exec-server`, `codex-login`, and `codex-model-provider` consumers against the compatibility re-exports. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/31323). * #31331 * __->__ #31323 --- codex-rs/Cargo.lock | 54 +++++++++++-------- codex-rs/Cargo.toml | 2 + codex-rs/codex-client/BUILD.bazel | 1 - codex-rs/codex-client/Cargo.toml | 35 +----------- codex-rs/codex-client/README.md | 6 +-- codex-rs/codex-client/src/lib.rs | 42 ++------------- codex-rs/codex-client/src/retry.rs | 4 +- codex-rs/codex-client/src/sse.rs | 4 +- codex-rs/codex-client/src/telemetry.rs | 2 +- codex-rs/http-client/BUILD.bazel | 7 +++ codex-rs/http-client/Cargo.toml | 49 +++++++++++++++++ codex-rs/http-client/README.md | 9 ++++ .../src/bin/custom_ca_probe.rs | 8 +-- .../src/chatgpt_cloudflare_cookies.rs | 2 +- .../src/chatgpt_hosts.rs | 2 +- .../src/custom_ca.rs | 2 +- .../src/default_client.rs | 16 +++--- .../src/error.rs | 2 + codex-rs/http-client/src/lib.rs | 40 ++++++++++++++ .../src/outbound_proxy.rs | 2 +- .../src/outbound_proxy/macos.rs | 2 + .../src/outbound_proxy/windows.rs | 2 + .../src/outbound_proxy/windows_tests.rs | 2 + .../src/outbound_proxy_tests.rs | 2 + .../src/request.rs | 6 +-- .../src/transport.rs | 10 ++-- .../tests/ca_env.rs | 2 +- .../tests/fixtures/test-ca-trusted.pem | 0 .../tests/fixtures/test-ca.pem | 0 .../tests/fixtures/test-intermediate.pem | 0 30 files changed, 187 insertions(+), 128 deletions(-) create mode 100644 codex-rs/http-client/BUILD.bazel create mode 100644 codex-rs/http-client/Cargo.toml create mode 100644 codex-rs/http-client/README.md rename codex-rs/{codex-client => http-client}/src/bin/custom_ca_probe.rs (91%) rename codex-rs/{codex-client => http-client}/src/chatgpt_cloudflare_cookies.rs (98%) rename codex-rs/{codex-client => http-client}/src/chatgpt_hosts.rs (96%) rename codex-rs/{codex-client => http-client}/src/custom_ca.rs (99%) rename codex-rs/{codex-client => http-client}/src/default_client.rs (93%) rename codex-rs/{codex-client => http-client}/src/error.rs (91%) create mode 100644 codex-rs/http-client/src/lib.rs rename codex-rs/{codex-client => http-client}/src/outbound_proxy.rs (99%) rename codex-rs/{codex-client => http-client}/src/outbound_proxy/macos.rs (99%) rename codex-rs/{codex-client => http-client}/src/outbound_proxy/windows.rs (99%) rename codex-rs/{codex-client => http-client}/src/outbound_proxy/windows_tests.rs (93%) rename codex-rs/{codex-client => http-client}/src/outbound_proxy_tests.rs (99%) rename codex-rs/{codex-client => http-client}/src/request.rs (98%) rename codex-rs/{codex-client => http-client}/src/transport.rs (94%) rename codex-rs/{codex-client => http-client}/tests/ca_env.rs (99%) rename codex-rs/{codex-client => http-client}/tests/fixtures/test-ca-trusted.pem (100%) rename codex-rs/{codex-client => http-client}/tests/fixtures/test-ca.pem (100%) rename codex-rs/{codex-client => http-client}/tests/fixtures/test-intermediate.pem (100%) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c0ff4a585a..c6eeb7f978 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2392,33 +2392,12 @@ dependencies = [ name = "codex-client" version = "0.0.0" dependencies = [ - "bytes", - "codex-utils-cargo-bin", - "codex-utils-rustls-provider", + "codex-http-client", "eventsource-stream", "futures", "http 1.4.0", - "opentelemetry", - "opentelemetry_sdk", - "pretty_assertions", "rand 0.9.3", - "rcgen", - "reqwest 0.12.28", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "serde", - "serde_json", - "sha2 0.10.9", - "system-configuration", - "tempfile", - "thiserror 2.0.18", "tokio", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "windows-sys 0.52.0", - "zstd 0.13.3", ] [[package]] @@ -3214,6 +3193,37 @@ dependencies = [ "uuid", ] +[[package]] +name = "codex-http-client" +version = "0.0.0" +dependencies = [ + "bytes", + "codex-utils-cargo-bin", + "codex-utils-rustls-provider", + "futures", + "http 1.4.0", + "opentelemetry", + "opentelemetry_sdk", + "pretty_assertions", + "rcgen", + "reqwest 0.12.28", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "serde", + "serde_json", + "sha2 0.10.9", + "system-configuration", + "tempfile", + "thiserror 2.0.18", + "tokio", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "windows-sys 0.52.0", + "zstd 0.13.3", +] + [[package]] name = "codex-image-generation-extension" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 2f73c216a9..ad08ce8e02 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -41,6 +41,7 @@ members = [ "core-plugins", "core-skills", "hooks", + "http-client", "secrets", "exec", "file-system", @@ -164,6 +165,7 @@ codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" } 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-config = { path = "config" } codex-connectors = { path = "connectors" } codex-connectors-extension = { path = "ext/connectors" } diff --git a/codex-rs/codex-client/BUILD.bazel b/codex-rs/codex-client/BUILD.bazel index 3d26819111..dd7e504634 100644 --- a/codex-rs/codex-client/BUILD.bazel +++ b/codex-rs/codex-client/BUILD.bazel @@ -2,6 +2,5 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "codex-client", - compile_data = glob(["tests/fixtures/**"]), crate_name = "codex_client", ) diff --git a/codex-rs/codex-client/Cargo.toml b/codex-rs/codex-client/Cargo.toml index fcd97b6bda..8e354ebeea 100644 --- a/codex-rs/codex-client/Cargo.toml +++ b/codex-rs/codex-client/Cargo.toml @@ -5,47 +5,16 @@ name = "codex-client" version.workspace = true [dependencies] -bytes = { workspace = true } +codex-http-client = { workspace = true } eventsource-stream = { workspace = true } futures = { workspace = true } http = { workspace = true } -opentelemetry = { workspace = true } rand = { workspace = true } -reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots", "stream"] } -rustls = { workspace = true } -rustls-native-certs = { workspace = true } -rustls-pki-types = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -thiserror = { workspace = true } tokio = { workspace = true, features = ["macros", "rt", "time", "sync"] } -tracing = { workspace = true } -tracing-opentelemetry = { workspace = true } -codex-utils-rustls-provider = { workspace = true } -zstd = { workspace = true } - -[target.'cfg(any(target_os = "windows", target_os = "macos"))'.dependencies] -sha2 = { workspace = true } - -[target.'cfg(target_os = "macos")'.dependencies] -system-configuration = { workspace = true } - -[target.'cfg(target_os = "windows")'.dependencies] -windows-sys = { version = "0.52", features = [ - "Win32_Foundation", - "Win32_Networking_WinHttp", -] } [lints] workspace = true -[dev-dependencies] -codex-utils-cargo-bin = { workspace = true } -opentelemetry_sdk = { workspace = true } -pretty_assertions = { workspace = true } -rcgen = { workspace = true } -tempfile = { workspace = true } -tracing-subscriber = { workspace = true } - [lib] doctest = false +test = false diff --git a/codex-rs/codex-client/README.md b/codex-rs/codex-client/README.md index 045ee7b343..1e4073117a 100644 --- a/codex-rs/codex-client/README.md +++ b/codex-rs/codex-client/README.md @@ -1,8 +1,8 @@ # codex-client -Generic transport layer that wraps HTTP requests, retries, and streaming primitives without any Codex/OpenAI awareness. +Higher-level request policy layered on `codex-http-client` without any Codex/OpenAI API awareness. -- Defines `HttpTransport` and a default `ReqwestTransport` plus thin `Request`/`Response` types. - Provides retry utilities (`RetryPolicy`, `RetryOn`, `run_with_retry`, `backoff`) that callers plug into for unary and streaming calls. - Supplies the `sse_stream` helper to turn byte streams into raw SSE `data:` frames with idle timeouts and surfaced stream errors. -- Consumed by higher-level crates like `codex-api`; it stays neutral on endpoints, headers, or API-specific error shapes. +- Defines the request telemetry callback used by higher-level clients. +- Re-exports the low-level HTTP types temporarily so consumers can migrate to `codex-http-client` incrementally. diff --git a/codex-rs/codex-client/src/lib.rs b/codex-rs/codex-client/src/lib.rs index 78daa6c288..4b83ba0dd0 100644 --- a/codex-rs/codex-client/src/lib.rs +++ b/codex-rs/codex-client/src/lib.rs @@ -1,49 +1,13 @@ -mod chatgpt_cloudflare_cookies; -mod chatgpt_hosts; -mod custom_ca; -mod default_client; -mod error; -mod outbound_proxy; -mod request; mod retry; mod sse; mod telemetry; -mod transport; -pub use crate::chatgpt_cloudflare_cookies::with_chatgpt_cloudflare_cookie_store; -pub use crate::chatgpt_hosts::is_allowed_chatgpt_host; -pub use crate::custom_ca::BuildCustomCaTransportError; -/// Test-only subprocess hook for custom CA coverage. -/// -/// This stays public only so the `custom_ca_probe` binary target can reuse the shared helper. It -/// is hidden from normal docs because ordinary callers should use -/// [`build_reqwest_client_with_custom_ca`] instead. -#[doc(hidden)] -pub use crate::custom_ca::build_reqwest_client_for_subprocess_tests; -pub use crate::custom_ca::build_reqwest_client_with_custom_ca; -pub use crate::custom_ca::maybe_build_rustls_client_config_with_custom_ca; -pub use crate::default_client::CodexHttpClient; -pub use crate::default_client::CodexRequestBuilder; -pub use crate::error::StreamError; -pub use crate::error::TransportError; -pub use crate::outbound_proxy::BuildRouteAwareHttpClientError; -pub use crate::outbound_proxy::ClientRouteClass; -pub use crate::outbound_proxy::OutboundProxyConfig; -pub use crate::outbound_proxy::RouteFailureClass; -pub use crate::outbound_proxy::build_reqwest_client_for_route; -pub use crate::request::EncodedJsonBody; -pub use crate::request::PreparedRequestBody; -pub use crate::request::Request; -pub use crate::request::RequestBody; -pub use crate::request::RequestCompression; -pub use crate::request::Response; pub use crate::retry::RetryOn; pub use crate::retry::RetryPolicy; pub use crate::retry::backoff; pub use crate::retry::run_with_retry; pub use crate::sse::sse_stream; pub use crate::telemetry::RequestTelemetry; -pub use crate::transport::ByteStream; -pub use crate::transport::HttpTransport; -pub use crate::transport::ReqwestTransport; -pub use crate::transport::StreamResponse; +pub use codex_http_client::HttpClient as CodexHttpClient; +pub use codex_http_client::RequestBuilder as CodexRequestBuilder; +pub use codex_http_client::*; diff --git a/codex-rs/codex-client/src/retry.rs b/codex-rs/codex-client/src/retry.rs index c7bdd34b1e..9eb408878b 100644 --- a/codex-rs/codex-client/src/retry.rs +++ b/codex-rs/codex-client/src/retry.rs @@ -1,5 +1,5 @@ -use crate::error::TransportError; -use crate::request::Request; +use codex_http_client::Request; +use codex_http_client::TransportError; use rand::Rng; use std::future::Future; use std::time::Duration; diff --git a/codex-rs/codex-client/src/sse.rs b/codex-rs/codex-client/src/sse.rs index f3aba3a2c5..ed1591f6de 100644 --- a/codex-rs/codex-client/src/sse.rs +++ b/codex-rs/codex-client/src/sse.rs @@ -1,5 +1,5 @@ -use crate::error::StreamError; -use crate::transport::ByteStream; +use codex_http_client::ByteStream; +use codex_http_client::StreamError; use eventsource_stream::Eventsource; use futures::StreamExt; use tokio::sync::mpsc; diff --git a/codex-rs/codex-client/src/telemetry.rs b/codex-rs/codex-client/src/telemetry.rs index 457d47f4fc..b856414d33 100644 --- a/codex-rs/codex-client/src/telemetry.rs +++ b/codex-rs/codex-client/src/telemetry.rs @@ -1,4 +1,4 @@ -use crate::error::TransportError; +use codex_http_client::TransportError; use http::StatusCode; use std::time::Duration; diff --git a/codex-rs/http-client/BUILD.bazel b/codex-rs/http-client/BUILD.bazel new file mode 100644 index 0000000000..6092c05bf2 --- /dev/null +++ b/codex-rs/http-client/BUILD.bazel @@ -0,0 +1,7 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "http-client", + compile_data = glob(["tests/fixtures/**"]), + crate_name = "codex_http_client", +) diff --git a/codex-rs/http-client/Cargo.toml b/codex-rs/http-client/Cargo.toml new file mode 100644 index 0000000000..46afa51ba5 --- /dev/null +++ b/codex-rs/http-client/Cargo.toml @@ -0,0 +1,49 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-http-client" +version.workspace = true + +[dependencies] +bytes = { workspace = true } +codex-utils-rustls-provider = { workspace = true } +futures = { workspace = true } +http = { workspace = true } +opentelemetry = { workspace = true } +reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots", "stream"] } +rustls = { workspace = true } +rustls-native-certs = { workspace = true } +rustls-pki-types = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "time", "sync"] } +tracing = { workspace = true } +tracing-opentelemetry = { workspace = true } +zstd = { workspace = true } + +[target.'cfg(any(target_os = "windows", target_os = "macos"))'.dependencies] +sha2 = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +system-configuration = { workspace = true } + +[target.'cfg(target_os = "windows")'.dependencies] +windows-sys = { version = "0.52", features = [ + "Win32_Foundation", + "Win32_Networking_WinHttp", +] } + +[lints] +workspace = true + +[dev-dependencies] +codex-utils-cargo-bin = { workspace = true } +opentelemetry_sdk = { workspace = true } +pretty_assertions = { workspace = true } +rcgen = { workspace = true } +tempfile = { workspace = true } +tracing-subscriber = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/http-client/README.md b/codex-rs/http-client/README.md new file mode 100644 index 0000000000..89e35ac59d --- /dev/null +++ b/codex-rs/http-client/README.md @@ -0,0 +1,9 @@ +# codex-http-client + +Low-level HTTP transport shared by Codex crates. + +- Defines the request, response, streaming, and transport types used for outbound HTTP calls. +- Owns the `reqwest` implementation, custom CA handling, and ChatGPT Cloudflare cookie policy. +- Resolves system, PAC/WPAD, environment, and direct proxy routes for supported clients. + +Higher-level retry, SSE, and request telemetry policy remains in `codex-client`. diff --git a/codex-rs/codex-client/src/bin/custom_ca_probe.rs b/codex-rs/http-client/src/bin/custom_ca_probe.rs similarity index 91% rename from codex-rs/codex-client/src/bin/custom_ca_probe.rs rename to codex-rs/http-client/src/bin/custom_ca_probe.rs index 81f5ba9bc2..c8db21510d 100644 --- a/codex-rs/codex-client/src/bin/custom_ca_probe.rs +++ b/codex-rs/http-client/src/bin/custom_ca_probe.rs @@ -10,9 +10,9 @@ //! - error messages guide users when CA files are invalid. //! - optional HTTPS probes can complete a request through the constructed client. //! -//! The detailed explanation of what "hermetic" means here lives in `codex_client::custom_ca`. +//! The detailed explanation of what "hermetic" means here lives in `codex_http_client::custom_ca`. //! This binary exists so the tests can exercise -//! [`codex_client::build_reqwest_client_for_subprocess_tests`] in a separate process without +//! [`codex_http_client::build_reqwest_client_for_subprocess_tests`] in a separate process without //! duplicating client-construction logic. use std::env; @@ -69,11 +69,11 @@ fn build_probe_client( if let Some(proxy_url) = proxy_url { let proxy = reqwest::Proxy::https(proxy_url) .map_err(|error| format!("failed to configure probe proxy {proxy_url}: {error}"))?; - return codex_client::build_reqwest_client_with_custom_ca(builder.proxy(proxy)) + return codex_http_client::build_reqwest_client_with_custom_ca(builder.proxy(proxy)) .map_err(|error| error.to_string()); } - codex_client::build_reqwest_client_for_subprocess_tests(builder) + codex_http_client::build_reqwest_client_for_subprocess_tests(builder) .map_err(|error| error.to_string()) } diff --git a/codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs b/codex-rs/http-client/src/chatgpt_cloudflare_cookies.rs similarity index 98% rename from codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs rename to codex-rs/http-client/src/chatgpt_cloudflare_cookies.rs index 7e5d22057c..f63763dad4 100644 --- a/codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs +++ b/codex-rs/http-client/src/chatgpt_cloudflare_cookies.rs @@ -7,7 +7,7 @@ use reqwest::header::HeaderValue; use crate::chatgpt_hosts::is_allowed_chatgpt_host; -// WARNING: this store is process-global and may be shared across auth contexts. +// WARNING: this HTTP cookie store is process-global and may be shared across auth contexts. // It must only ever contain Cloudflare infrastructure cookies. Never extend this // store to persist ChatGPT account, session, auth, or other user-specific cookie // data. diff --git a/codex-rs/codex-client/src/chatgpt_hosts.rs b/codex-rs/http-client/src/chatgpt_hosts.rs similarity index 96% rename from codex-rs/codex-client/src/chatgpt_hosts.rs rename to codex-rs/http-client/src/chatgpt_hosts.rs index dd0b99589c..0426c8bb36 100644 --- a/codex-rs/codex-client/src/chatgpt_hosts.rs +++ b/codex-rs/http-client/src/chatgpt_hosts.rs @@ -1,5 +1,5 @@ /// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat -/// as first-party ChatGPT traffic. +/// as first-party ChatGPT HTTP traffic. pub fn is_allowed_chatgpt_host(host: &str) -> bool { const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"]; const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"]; diff --git a/codex-rs/codex-client/src/custom_ca.rs b/codex-rs/http-client/src/custom_ca.rs similarity index 99% rename from codex-rs/codex-client/src/custom_ca.rs rename to codex-rs/http-client/src/custom_ca.rs index 1a211beedf..4cfae8f23d 100644 --- a/codex-rs/codex-client/src/custom_ca.rs +++ b/codex-rs/http-client/src/custom_ca.rs @@ -1,4 +1,4 @@ -//! Custom CA handling for Codex outbound HTTP and websocket clients. +//! Custom CA handling shared by Codex outbound HTTP and websocket clients. //! //! Codex constructs outbound reqwest clients and secure websocket connections in a few crates, but //! they all need the same trust-store policy when enterprise proxies or gateways intercept TLS. diff --git a/codex-rs/codex-client/src/default_client.rs b/codex-rs/http-client/src/default_client.rs similarity index 93% rename from codex-rs/codex-client/src/default_client.rs rename to codex-rs/http-client/src/default_client.rs index 56b3ce4b16..b4465e7f8c 100644 --- a/codex-rs/codex-client/src/default_client.rs +++ b/codex-rs/http-client/src/default_client.rs @@ -14,47 +14,47 @@ use tracing::Span; use tracing_opentelemetry::OpenTelemetrySpanExt; #[derive(Clone, Debug)] -pub struct CodexHttpClient { +pub struct HttpClient { inner: reqwest::Client, } -impl CodexHttpClient { +impl HttpClient { pub fn new(inner: reqwest::Client) -> Self { Self { inner } } - pub fn get(&self, url: U) -> CodexRequestBuilder + pub fn get(&self, url: U) -> RequestBuilder where U: IntoUrl, { self.request(Method::GET, url) } - pub fn post(&self, url: U) -> CodexRequestBuilder + pub fn post(&self, url: U) -> RequestBuilder where U: IntoUrl, { self.request(Method::POST, url) } - pub fn request(&self, method: Method, url: U) -> CodexRequestBuilder + pub fn request(&self, method: Method, url: U) -> RequestBuilder where U: IntoUrl, { let url_str = url.as_str().to_string(); - CodexRequestBuilder::new(self.inner.request(method.clone(), url), method, url_str) + RequestBuilder::new(self.inner.request(method.clone(), url), method, url_str) } } #[must_use = "requests are not sent unless `send` is awaited"] #[derive(Debug)] -pub struct CodexRequestBuilder { +pub struct RequestBuilder { builder: reqwest::RequestBuilder, method: Method, url: String, } -impl CodexRequestBuilder { +impl RequestBuilder { fn new(builder: reqwest::RequestBuilder, method: Method, url: String) -> Self { Self { builder, diff --git a/codex-rs/codex-client/src/error.rs b/codex-rs/http-client/src/error.rs similarity index 91% rename from codex-rs/codex-client/src/error.rs rename to codex-rs/http-client/src/error.rs index fa2bfb4f79..6b49229026 100644 --- a/codex-rs/codex-client/src/error.rs +++ b/codex-rs/http-client/src/error.rs @@ -1,3 +1,5 @@ +//! Errors returned by the shared Codex HTTP transport. + use http::HeaderMap; use http::StatusCode; use thiserror::Error; diff --git a/codex-rs/http-client/src/lib.rs b/codex-rs/http-client/src/lib.rs new file mode 100644 index 0000000000..5f90435452 --- /dev/null +++ b/codex-rs/http-client/src/lib.rs @@ -0,0 +1,40 @@ +mod chatgpt_cloudflare_cookies; +mod chatgpt_hosts; +mod custom_ca; +mod default_client; +mod error; +mod outbound_proxy; +mod request; +mod transport; + +pub use crate::chatgpt_cloudflare_cookies::with_chatgpt_cloudflare_cookie_store; +pub use crate::chatgpt_hosts::is_allowed_chatgpt_host; +pub use crate::custom_ca::BuildCustomCaTransportError; +/// Test-only subprocess hook for custom CA coverage. +/// +/// This stays public only so the `custom_ca_probe` binary target can reuse the shared helper. It +/// is hidden from normal docs because ordinary callers should use +/// [`build_reqwest_client_with_custom_ca`] instead. +#[doc(hidden)] +pub use crate::custom_ca::build_reqwest_client_for_subprocess_tests; +pub use crate::custom_ca::build_reqwest_client_with_custom_ca; +pub use crate::custom_ca::maybe_build_rustls_client_config_with_custom_ca; +pub use crate::default_client::HttpClient; +pub use crate::default_client::RequestBuilder; +pub use crate::error::StreamError; +pub use crate::error::TransportError; +pub use crate::outbound_proxy::BuildRouteAwareHttpClientError; +pub use crate::outbound_proxy::ClientRouteClass; +pub use crate::outbound_proxy::OutboundProxyConfig; +pub use crate::outbound_proxy::RouteFailureClass; +pub use crate::outbound_proxy::build_reqwest_client_for_route; +pub use crate::request::EncodedJsonBody; +pub use crate::request::PreparedRequestBody; +pub use crate::request::Request; +pub use crate::request::RequestBody; +pub use crate::request::RequestCompression; +pub use crate::request::Response; +pub use crate::transport::ByteStream; +pub use crate::transport::HttpTransport; +pub use crate::transport::ReqwestTransport; +pub use crate::transport::StreamResponse; diff --git a/codex-rs/codex-client/src/outbound_proxy.rs b/codex-rs/http-client/src/outbound_proxy.rs similarity index 99% rename from codex-rs/codex-client/src/outbound_proxy.rs rename to codex-rs/http-client/src/outbound_proxy.rs index ea6587052e..e643698a8c 100644 --- a/codex-rs/codex-client/src/outbound_proxy.rs +++ b/codex-rs/http-client/src/outbound_proxy.rs @@ -1,4 +1,4 @@ -//! Conservative outbound proxy selection for resolver-aware clients. +//! Conservative outbound proxy selection for resolver-aware HTTP clients. //! //! When enabled, platform system discovery is tried first, explicit environment //! proxies are the fallback, and the final fallback is a direct connection. diff --git a/codex-rs/codex-client/src/outbound_proxy/macos.rs b/codex-rs/http-client/src/outbound_proxy/macos.rs similarity index 99% rename from codex-rs/codex-client/src/outbound_proxy/macos.rs rename to codex-rs/http-client/src/outbound_proxy/macos.rs index 3913ecc40b..fe07a6b498 100644 --- a/codex-rs/codex-client/src/outbound_proxy/macos.rs +++ b/codex-rs/http-client/src/outbound_proxy/macos.rs @@ -1,3 +1,5 @@ +//! macOS system proxy resolution through SystemConfiguration and CFNetwork. + use std::ffi::c_void; use std::ptr; use std::time::Duration; diff --git a/codex-rs/codex-client/src/outbound_proxy/windows.rs b/codex-rs/http-client/src/outbound_proxy/windows.rs similarity index 99% rename from codex-rs/codex-client/src/outbound_proxy/windows.rs rename to codex-rs/http-client/src/outbound_proxy/windows.rs index 9e64196705..4ff927723a 100644 --- a/codex-rs/codex-client/src/outbound_proxy/windows.rs +++ b/codex-rs/http-client/src/outbound_proxy/windows.rs @@ -1,3 +1,5 @@ +//! Windows system proxy resolution through WinHTTP. + use std::ffi::c_void; use std::ptr; diff --git a/codex-rs/codex-client/src/outbound_proxy/windows_tests.rs b/codex-rs/http-client/src/outbound_proxy/windows_tests.rs similarity index 93% rename from codex-rs/codex-client/src/outbound_proxy/windows_tests.rs rename to codex-rs/http-client/src/outbound_proxy/windows_tests.rs index 3772c057db..589c06661c 100644 --- a/codex-rs/codex-client/src/outbound_proxy/windows_tests.rs +++ b/codex-rs/http-client/src/outbound_proxy/windows_tests.rs @@ -1,3 +1,5 @@ +//! Windows proxy parsing tests. + use super::*; #[test] diff --git a/codex-rs/codex-client/src/outbound_proxy_tests.rs b/codex-rs/http-client/src/outbound_proxy_tests.rs similarity index 99% rename from codex-rs/codex-client/src/outbound_proxy_tests.rs rename to codex-rs/http-client/src/outbound_proxy_tests.rs index 46868e8f73..60a1d56396 100644 --- a/codex-rs/codex-client/src/outbound_proxy_tests.rs +++ b/codex-rs/http-client/src/outbound_proxy_tests.rs @@ -1,3 +1,5 @@ +//! Shared outbound proxy policy tests. + use super::*; use pretty_assertions::assert_eq; use std::io::Read; diff --git a/codex-rs/codex-client/src/request.rs b/codex-rs/http-client/src/request.rs similarity index 98% rename from codex-rs/codex-client/src/request.rs rename to codex-rs/http-client/src/request.rs index 6d50f7cb57..7608860c3d 100644 --- a/codex-rs/codex-client/src/request.rs +++ b/codex-rs/http-client/src/request.rs @@ -1,7 +1,7 @@ use bytes::Bytes; +use http::HeaderMap; +use http::HeaderValue; use http::Method; -use reqwest::header::HeaderMap; -use reqwest::header::HeaderValue; use serde::Serialize; use serde_json::Value; use std::time::Duration; @@ -121,7 +121,7 @@ impl Request { Some(RequestBody::Json(_) | RequestBody::EncodedJson(_)) ); let trace_bytes = if self.compression != RequestCompression::None - && tracing::enabled!(target: "codex_client::transport", tracing::Level::TRACE) + && tracing::enabled!(target: "codex_http_client::transport", tracing::Level::TRACE) { match self.body.as_ref() { Some(RequestBody::Json(body)) => Some(Bytes::from( diff --git a/codex-rs/codex-client/src/transport.rs b/codex-rs/http-client/src/transport.rs similarity index 94% rename from codex-rs/codex-client/src/transport.rs rename to codex-rs/http-client/src/transport.rs index 708b73bf2b..bda6c28ee9 100644 --- a/codex-rs/codex-client/src/transport.rs +++ b/codex-rs/http-client/src/transport.rs @@ -1,5 +1,5 @@ -use crate::default_client::CodexHttpClient; -use crate::default_client::CodexRequestBuilder; +use crate::default_client::HttpClient; +use crate::default_client::RequestBuilder; use crate::error::TransportError; use crate::request::Request; use crate::request::RequestBody; @@ -35,17 +35,17 @@ pub trait HttpTransport: Send + Sync { #[derive(Clone, Debug)] pub struct ReqwestTransport { - client: CodexHttpClient, + client: HttpClient, } impl ReqwestTransport { pub fn new(client: reqwest::Client) -> Self { Self { - client: CodexHttpClient::new(client), + client: HttpClient::new(client), } } - fn build(&self, req: Request) -> Result { + fn build(&self, req: Request) -> Result { let prepared = req.prepare_body_for_send().map_err(TransportError::Build)?; let Request { diff --git a/codex-rs/codex-client/tests/ca_env.rs b/codex-rs/http-client/tests/ca_env.rs similarity index 99% rename from codex-rs/codex-client/tests/ca_env.rs rename to codex-rs/http-client/tests/ca_env.rs index 7ddd138a33..f35225fee7 100644 --- a/codex-rs/codex-client/tests/ca_env.rs +++ b/codex-rs/http-client/tests/ca_env.rs @@ -3,7 +3,7 @@ //! //! These tests intentionally run through `custom_ca_probe` and //! `build_reqwest_client_for_subprocess_tests` instead of calling the helper in-process. The -//! detailed explanation of what "hermetic" means here lives in `codex_client::custom_ca`; these +//! detailed explanation of what "hermetic" means here lives in `codex_http_client::custom_ca`; these //! tests add the process-level half of that contract by scrubbing inherited CA environment //! variables before each subprocess launch. Most assertions here cover CA file selection, PEM //! parsing, and user-facing errors. The HTTPS probes go further and perform real POSTs against diff --git a/codex-rs/codex-client/tests/fixtures/test-ca-trusted.pem b/codex-rs/http-client/tests/fixtures/test-ca-trusted.pem similarity index 100% rename from codex-rs/codex-client/tests/fixtures/test-ca-trusted.pem rename to codex-rs/http-client/tests/fixtures/test-ca-trusted.pem diff --git a/codex-rs/codex-client/tests/fixtures/test-ca.pem b/codex-rs/http-client/tests/fixtures/test-ca.pem similarity index 100% rename from codex-rs/codex-client/tests/fixtures/test-ca.pem rename to codex-rs/http-client/tests/fixtures/test-ca.pem diff --git a/codex-rs/codex-client/tests/fixtures/test-intermediate.pem b/codex-rs/http-client/tests/fixtures/test-intermediate.pem similarity index 100% rename from codex-rs/codex-client/tests/fixtures/test-intermediate.pem rename to codex-rs/http-client/tests/fixtures/test-intermediate.pem From 641aa1b61902753c2da02443a13bfdd3d039c568 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 6 Jul 2026 18:34:36 -0700 Subject: [PATCH 09/79] Migrate direct HTTP consumers to codex-http-client (#31331) ## Why #31323 introduces `codex-http-client` and leaves compatibility re-exports in `codex-client`. Low-level HTTP consumers should depend on the crate that now owns those APIs rather than continuing through the transitional compatibility layer. This stacked follow-up makes that ownership explicit and moves the repository toward enforcing the abstraction without mixing call-site churn into the extraction itself. ## What changed - Switched `codex-backend-client`, `codex-cloud-tasks`, `codex-exec-server`, `codex-login`, and `codex-model-provider` from `codex-client` to `codex-http-client` where they only use low-level HTTP APIs. - Added the direct dependency to `codex-api` for its custom-CA request and websocket paths while retaining `codex-client` for higher-level retry and transport policy. - Updated imports and normalized login's internal client type name from `CodexHttpClient` to `HttpClient`, while preserving its existing `CodexRequestBuilder` re-export. - Updated `Cargo.lock` to reflect the new direct dependency edges. ## Review guide This PR is intentionally mechanical: 20 files and 92 changed lines, with no runtime logic changes. The largest diff is `codex-rs/login/src/auth/default_client.rs`, where the only semantic-looking changes are type and import renames. The remaining source changes replace `codex_client` import paths with `codex_http_client`; the manifest and lockfile changes mirror those imports. ## Test plan - Compile-checked `codex-api`, `codex-backend-client`, `codex-cloud-tasks`, `codex-exec-server`, `codex-login`, and `codex-model-provider` together. --- codex-rs/Cargo.lock | 11 ++++---- codex-rs/backend-client/Cargo.toml | 2 +- codex-rs/backend-client/src/client.rs | 4 +-- codex-rs/cloud-tasks/Cargo.toml | 2 +- codex-rs/cloud-tasks/src/env_detect.rs | 2 +- codex-rs/codex-api/Cargo.toml | 1 + .../endpoint/realtime_websocket/methods.rs | 2 +- .../src/endpoint/responses_websocket.rs | 2 +- codex-rs/codex-api/src/files.rs | 2 +- codex-rs/exec-server/Cargo.toml | 2 +- .../src/client/reqwest_http_client.rs | 4 +-- codex-rs/login/Cargo.toml | 2 +- codex-rs/login/src/auth/default_client.rs | 26 +++++++++---------- codex-rs/login/src/auth/manager.rs | 8 +++--- .../login/src/auth/personal_access_token.rs | 4 +-- codex-rs/login/src/auth/revoke.rs | 6 ++--- codex-rs/login/src/lib.rs | 2 +- codex-rs/login/src/outbound_proxy.rs | 2 +- codex-rs/model-provider/Cargo.toml | 2 +- .../model-provider/src/amazon_bedrock/auth.rs | 6 ++--- 20 files changed, 47 insertions(+), 45 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c6eeb7f978..9d89f8eb1f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1936,6 +1936,7 @@ dependencies = [ "bytes", "chrono", "codex-client", + "codex-http-client", "codex-protocol", "codex-utils-rustls-provider", "eventsource-stream", @@ -2262,7 +2263,7 @@ dependencies = [ "anyhow", "codex-api", "codex-backend-openapi-models", - "codex-client", + "codex-http-client", "codex-login", "codex-model-provider", "codex-protocol", @@ -2431,11 +2432,11 @@ dependencies = [ "anyhow", "chrono", "clap", - "codex-client", "codex-cloud-tasks-client", "codex-cloud-tasks-mock-client", "codex-core", "codex-git-utils", + "codex-http-client", "codex-login", "codex-model-provider", "codex-tui", @@ -2895,9 +2896,9 @@ dependencies = [ "bytes", "clatter", "codex-api", - "codex-client", "codex-exec-server-protocol", "codex-file-system", + "codex-http-client", "codex-network-proxy", "codex-otel", "codex-protocol", @@ -3315,8 +3316,8 @@ dependencies = [ "base64 0.22.1", "chrono", "codex-agent-identity", - "codex-client", "codex-config", + "codex-http-client", "codex-keyring-store", "codex-model-provider-info", "codex-otel", @@ -3530,8 +3531,8 @@ dependencies = [ "codex-agent-identity", "codex-api", "codex-aws-auth", - "codex-client", "codex-feedback", + "codex-http-client", "codex-login", "codex-model-provider-info", "codex-models-manager", diff --git a/codex-rs/backend-client/Cargo.toml b/codex-rs/backend-client/Cargo.toml index f7b0c8b0f5..4ff5fb9b86 100644 --- a/codex-rs/backend-client/Cargo.toml +++ b/codex-rs/backend-client/Cargo.toml @@ -19,7 +19,7 @@ serde_json = "1" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } codex-backend-openapi-models = { path = "../codex-backend-openapi-models" } codex-api = { workspace = true } -codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-login = { workspace = true } codex-model-provider = { workspace = true } codex-protocol = { workspace = true } diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index be444b6247..a5db25618b 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -9,8 +9,8 @@ use crate::types::TokenUsageProfile; use crate::types::TurnAttemptsSiblingTurnsResponse; use anyhow::Result; use codex_api::SharedAuthProvider; -use codex_client::build_reqwest_client_with_custom_ca; -use codex_client::with_chatgpt_cloudflare_cookie_store; +use codex_http_client::build_reqwest_client_with_custom_ca; +use codex_http_client::with_chatgpt_cloudflare_cookie_store; use codex_login::CodexAuth; use codex_login::default_client::get_codex_user_agent; use codex_protocol::account::PlanType as AccountPlanType; diff --git a/codex-rs/cloud-tasks/Cargo.toml b/codex-rs/cloud-tasks/Cargo.toml index e7997259a5..d842a95a94 100644 --- a/codex-rs/cloud-tasks/Cargo.toml +++ b/codex-rs/cloud-tasks/Cargo.toml @@ -16,7 +16,7 @@ workspace = true anyhow = { workspace = true } chrono = { workspace = true, features = ["serde"] } clap = { workspace = true, features = ["derive"] } -codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-cloud-tasks-client = { workspace = true } # TODO: codex-cloud-tasks-mock-client should be in dev-dependencies. codex-cloud-tasks-mock-client = { workspace = true } diff --git a/codex-rs/cloud-tasks/src/env_detect.rs b/codex-rs/cloud-tasks/src/env_detect.rs index cd38c7f347..6137f27ea8 100644 --- a/codex-rs/cloud-tasks/src/env_detect.rs +++ b/codex-rs/cloud-tasks/src/env_detect.rs @@ -1,4 +1,4 @@ -use codex_client::build_reqwest_client_with_custom_ca; +use codex_http_client::build_reqwest_client_with_custom_ca; use reqwest::header::CONTENT_TYPE; use reqwest::header::HeaderMap; use std::collections::HashMap; diff --git a/codex-rs/codex-api/Cargo.toml b/codex-rs/codex-api/Cargo.toml index 72aa66a810..084b058e12 100644 --- a/codex-rs/codex-api/Cargo.toml +++ b/codex-rs/codex-api/Cargo.toml @@ -10,6 +10,7 @@ base64 = { workspace = true } bytes = { workspace = true } chrono = { workspace = true } codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-protocol = { workspace = true } codex-utils-rustls-provider = { workspace = true } futures = { workspace = true } diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs index 0ae443d00a..7b1a74e4ae 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs @@ -16,7 +16,7 @@ use crate::endpoint::realtime_websocket::protocol::parse_realtime_event; use crate::error::ApiError; use crate::provider::Provider; use codex_client::backoff; -use codex_client::maybe_build_rustls_client_config_with_custom_ca; +use codex_http_client::maybe_build_rustls_client_config_with_custom_ca; use codex_protocol::protocol::ConversationTextRole; use codex_protocol::protocol::RealtimeTranscriptDelta; use codex_utils_rustls_provider::ensure_rustls_crypto_provider; diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index 7f261bba36..447450fae1 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -11,7 +11,7 @@ use crate::sse::ResponsesStreamEvent; use crate::sse::process_responses_event; use crate::telemetry::WebsocketTelemetry; use codex_client::TransportError; -use codex_client::maybe_build_rustls_client_config_with_custom_ca; +use codex_http_client::maybe_build_rustls_client_config_with_custom_ca; use codex_utils_rustls_provider::ensure_rustls_crypto_provider; use futures::SinkExt; use futures::StreamExt; diff --git a/codex-rs/codex-api/src/files.rs b/codex-rs/codex-api/src/files.rs index 8bcf1a4d0d..3cd3932d06 100644 --- a/codex-rs/codex-api/src/files.rs +++ b/codex-rs/codex-api/src/files.rs @@ -2,7 +2,7 @@ use std::time::Duration; use crate::AuthProvider; use bytes::Bytes; -use codex_client::build_reqwest_client_with_custom_ca; +use codex_http_client::build_reqwest_client_with_custom_ca; use futures::Stream; use reqwest::StatusCode; use reqwest::header::CONTENT_LENGTH; diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml index 35fa411021..ba9058f0c6 100644 --- a/codex-rs/exec-server/Cargo.toml +++ b/codex-rs/exec-server/Cargo.toml @@ -17,7 +17,7 @@ base64 = { workspace = true } bytes = { workspace = true } clatter = { workspace = true } codex-api = { workspace = true } -codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-exec-server-protocol = { workspace = true } codex-file-system = { workspace = true } codex-network-proxy = { workspace = true } diff --git a/codex-rs/exec-server/src/client/reqwest_http_client.rs b/codex-rs/exec-server/src/client/reqwest_http_client.rs index 7ead01c9ba..d0cffa6a32 100644 --- a/codex-rs/exec-server/src/client/reqwest_http_client.rs +++ b/codex-rs/exec-server/src/client/reqwest_http_client.rs @@ -8,9 +8,9 @@ use std::error::Error as StdError; use std::time::Duration; -use codex_client::build_reqwest_client_with_custom_ca; -use codex_client::with_chatgpt_cloudflare_cookie_store; use codex_exec_server_protocol::JSONRPCErrorError; +use codex_http_client::build_reqwest_client_with_custom_ca; +use codex_http_client::with_chatgpt_cloudflare_cookie_store; use futures::FutureExt; use futures::StreamExt; use futures::future::BoxFuture; diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 04066f5894..3eb253d7dc 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -11,7 +11,7 @@ workspace = true base64 = { workspace = true } chrono = { workspace = true, features = ["serde"] } codex-agent-identity = { workspace = true } -codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-config = { workspace = true } codex-keyring-store = { workspace = true } codex-model-provider-info = { workspace = true } diff --git a/codex-rs/login/src/auth/default_client.rs b/codex-rs/login/src/auth/default_client.rs index f72727bfca..1146a89d96 100644 --- a/codex-rs/login/src/auth/default_client.rs +++ b/codex-rs/login/src/auth/default_client.rs @@ -1,17 +1,17 @@ //! Default Codex HTTP client: shared `User-Agent`, `originator`, optional residency header, and -//! reqwest/`CodexHttpClient` construction. +//! reqwest/`HttpClient` construction. //! //! Use [`crate::default_client`] or [`codex_login::default_client`] from other crates in this //! workspace. -use codex_client::BuildCustomCaTransportError; -use codex_client::BuildRouteAwareHttpClientError; -use codex_client::ClientRouteClass; -use codex_client::CodexHttpClient; -pub use codex_client::CodexRequestBuilder; -use codex_client::build_reqwest_client_for_route; -use codex_client::build_reqwest_client_with_custom_ca; -use codex_client::with_chatgpt_cloudflare_cookie_store; +use codex_http_client::BuildCustomCaTransportError; +use codex_http_client::BuildRouteAwareHttpClientError; +use codex_http_client::ClientRouteClass; +use codex_http_client::HttpClient; +pub use codex_http_client::RequestBuilder as CodexRequestBuilder; +use codex_http_client::build_reqwest_client_for_route; +use codex_http_client::build_reqwest_client_with_custom_ca; +use codex_http_client::with_chatgpt_cloudflare_cookie_store; use codex_terminal_detection::user_agent; use reqwest::header::HeaderMap; use reqwest::header::HeaderValue; @@ -197,9 +197,9 @@ fn sanitize_user_agent(candidate: String, fallback: &str) -> String { /// /// This supported default path preserves reqwest's existing proxy behavior and does not opt into /// Codex's route-aware system/PAC resolution. -pub fn create_client() -> CodexHttpClient { +pub fn create_client() -> HttpClient { let inner = build_reqwest_client(); - CodexHttpClient::new(inner) + HttpClient::new(inner) } /// Builds the default reqwest client used for ordinary Codex HTTP traffic. @@ -282,8 +282,8 @@ pub(crate) fn build_default_auth_reqwest_client( pub(crate) fn create_default_auth_client( endpoint: &str, auth_route_config: Option<&AuthRouteConfig>, -) -> Result { - build_default_auth_reqwest_client(endpoint, auth_route_config).map(CodexHttpClient::new) +) -> Result { + build_default_auth_reqwest_client(endpoint, auth_route_config).map(HttpClient::new) } pub fn default_headers() -> HeaderMap { diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 844410874d..a2d005dfa6 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -55,8 +55,8 @@ use crate::outbound_proxy::AuthRouteConfig; use crate::token_data::TokenData; use crate::token_data::parse_chatgpt_jwt_claims; use crate::token_data::parse_jwt_expiration; -use codex_client::CodexHttpClient; use codex_config::types::AuthCredentialsStoreMode; +use codex_http_client::HttpClient; use codex_protocol::account::PlanType as AccountPlanType; use codex_protocol::auth::PlanType as InternalPlanType; use codex_protocol::auth::RefreshTokenFailedError; @@ -171,7 +171,7 @@ pub struct ChatgptAuthTokens { #[derive(Debug, Clone)] struct ChatgptAuthState { auth_dot_json: Arc>>, - client: CodexHttpClient, + client: HttpClient, } const TOKEN_REFRESH_INTERVAL: i64 = 8; @@ -805,7 +805,7 @@ impl ChatgptAuth { &self.storage } - fn client(&self) -> &CodexHttpClient { + fn client(&self) -> &HttpClient { &self.state.client } @@ -1331,7 +1331,7 @@ fn persist_tokens( // The caller is responsible for persisting any returned tokens. async fn request_chatgpt_token_refresh( refresh_token: String, - client: &CodexHttpClient, + client: &HttpClient, ) -> Result { let refresh_request = RefreshRequest { client_id: oauth_client_id(), diff --git a/codex-rs/login/src/auth/personal_access_token.rs b/codex-rs/login/src/auth/personal_access_token.rs index ea75648d1b..09c6d5d2b3 100644 --- a/codex-rs/login/src/auth/personal_access_token.rs +++ b/codex-rs/login/src/auth/personal_access_token.rs @@ -1,4 +1,4 @@ -use codex_client::CodexHttpClient; +use codex_http_client::HttpClient; use codex_protocol::account::PlanType as AccountPlanType; use codex_protocol::auth::PlanType as InternalPlanType; use serde::Deserialize; @@ -77,7 +77,7 @@ impl PersonalAccessTokenAuth { } async fn hydrate_personal_access_token( - client: &CodexHttpClient, + client: &HttpClient, endpoint: &str, access_token: &str, ) -> std::io::Result { diff --git a/codex-rs/login/src/auth/revoke.rs b/codex-rs/login/src/auth/revoke.rs index 076b8b53da..ca22adb571 100644 --- a/codex-rs/login/src/auth/revoke.rs +++ b/codex-rs/login/src/auth/revoke.rs @@ -7,7 +7,7 @@ use serde::Serialize; use std::time::Duration; -use codex_client::CodexHttpClient; +use codex_http_client::HttpClient; use codex_protocol::auth::AuthMode; use super::manager::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; @@ -95,7 +95,7 @@ fn resolved_auth_mode(auth_dot_json: &AuthDotJson) -> AuthMode { } async fn revoke_oauth_token( - client: &CodexHttpClient, + client: &HttpClient, endpoint: &str, token: &str, kind: RevokeTokenKind, @@ -181,7 +181,7 @@ mod tests { .mount(&server) .await; - let client = CodexHttpClient::new(reqwest::Client::new()); + let client = HttpClient::new(reqwest::Client::new()); let endpoint = format!("{}/oauth/revoke", server.uri()); let error = revoke_oauth_token( &client, diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 44c2f1c4d3..7ea415fcc5 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -7,8 +7,8 @@ mod outbound_proxy; mod pkce; mod server; -pub use codex_client::BuildCustomCaTransportError as BuildLoginHttpClientError; pub use codex_config::types::AuthCredentialsStoreMode; +pub use codex_http_client::BuildCustomCaTransportError as BuildLoginHttpClientError; pub use device_code_auth::DeviceCode; pub use device_code_auth::complete_device_code_login; pub use device_code_auth::request_device_code; diff --git a/codex-rs/login/src/outbound_proxy.rs b/codex-rs/login/src/outbound_proxy.rs index bf7dfbeb4d..66441e3637 100644 --- a/codex-rs/login/src/outbound_proxy.rs +++ b/codex-rs/login/src/outbound_proxy.rs @@ -1,4 +1,4 @@ -use codex_client::OutboundProxyConfig; +use codex_http_client::OutboundProxyConfig; /// Auth-layer adapter around client-owned proxy policy. /// diff --git a/codex-rs/model-provider/Cargo.toml b/codex-rs/model-provider/Cargo.toml index 29599c6c7e..b6ee6acbfc 100644 --- a/codex-rs/model-provider/Cargo.toml +++ b/codex-rs/model-provider/Cargo.toml @@ -16,7 +16,7 @@ workspace = true codex-api = { workspace = true } codex-agent-identity = { workspace = true } codex-aws-auth = { workspace = true } -codex-client = { workspace = true } +codex-http-client = { workspace = true } codex-feedback = { workspace = true } codex-login = { workspace = true } codex-model-provider-info = { workspace = true } diff --git a/codex-rs/model-provider/src/amazon_bedrock/auth.rs b/codex-rs/model-provider/src/amazon_bedrock/auth.rs index 6dd897050a..b9b318d9b1 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/auth.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/auth.rs @@ -6,9 +6,9 @@ use codex_api::SharedAuthProvider; use codex_aws_auth::AwsAuthContext; use codex_aws_auth::AwsAuthError; use codex_aws_auth::AwsRequestToSign; -use codex_client::Request; -use codex_client::RequestBody; -use codex_client::RequestCompression; +use codex_http_client::Request; +use codex_http_client::RequestBody; +use codex_http_client::RequestCompression; use codex_login::auth::BedrockApiKeyAuth; use codex_model_provider_info::ModelProviderAwsAuthInfo; use codex_protocol::error::CodexErr; From 8f3431054fe44dbf0d901bb12c522bb87c64fd47 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Mon, 6 Jul 2026 19:08:50 -0700 Subject: [PATCH 10/79] fix: restore Codex environment setup table (#31337) ## Why Creating a Codex worktree skips local environment setup because `.codex/environments/environment.toml` omits the required `setup` object. ## What Restore an empty `[setup]` table with `script = ""`, preserving the intended no-op setup while satisfying the environment parser schema. ## Validation - Parsed the final TOML and verified `setup.script` is present as a string. --- .codex/environments/environment.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.codex/environments/environment.toml b/.codex/environments/environment.toml index b3c5910fbc..ae0bd24ca8 100644 --- a/.codex/environments/environment.toml +++ b/.codex/environments/environment.toml @@ -2,6 +2,10 @@ version = 1 name = "codex" +# TODO(anp) make it optional to specify this field +[setup] +script = "" + [[actions]] name = "Run" icon = "run" From 831c14fc39f7810703263c31a4a712842dba35f4 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 6 Jul 2026 19:28:44 -0700 Subject: [PATCH 11/79] Preserve managed exec policy after rules parse errors (#31188) ## Why Cleanup for #31179 exposed a core fallback bug that the TUI had been handling locally. When a custom `.rules` file fails to parse, nonfatal clients warn and continue, but `load_exec_policy_with_warning` replaced the entire policy with `Policy::empty()` before managed requirements were merged. App-server and desktop clients could therefore silently lose required prompt and forbidden rules. This fix is intentionally separate from #31179 so the TUI cleanup does not depend on it. ## What changed - Preserve the managed requirements exec policy when custom file rules fail to parse, while returning the existing warning and discarding the file-based policy. - Use the same nonfatal fallback when loading network proxy policy. - Keep parse errors fatal for strict clients such as `codex exec`. --- codex-rs/core/src/exec_policy.rs | 11 ++- codex-rs/core/src/exec_policy_tests.rs | 36 +++++++++ codex-rs/core/src/network_proxy_loader.rs | 27 +++---- .../core/src/network_proxy_loader_tests.rs | 50 ++++++++++++ codex-rs/core/tests/suite/exec_policy.rs | 80 +++++++++++++++++++ 5 files changed, 188 insertions(+), 16 deletions(-) diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index cbffcd7e43..8f31f150b3 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -554,12 +554,19 @@ pub fn format_exec_policy_error_with_source(error: &ExecPolicyError) -> String { } } -async fn load_exec_policy_with_warning( +pub(crate) async fn load_exec_policy_with_warning( config_stack: &ConfigLayerStack, ) -> Result<(Policy, Option), ExecPolicyError> { match load_exec_policy(config_stack).await { Ok(policy) => Ok((policy, None)), - Err(err @ ExecPolicyError::ParsePolicy { .. }) => Ok((Policy::empty(), Some(err))), + Err(err @ ExecPolicyError::ParsePolicy { .. }) => { + let policy = config_stack + .requirements() + .exec_policy + .as_deref() + .map_or_else(Policy::empty, |policy| policy.as_ref().clone()); + Ok((policy, Some(err))) + } Err(err) => Err(err), } } diff --git a/codex-rs/core/src/exec_policy_tests.rs b/codex-rs/core/src/exec_policy_tests.rs index cf17387ef5..95d29e0bac 100644 --- a/codex-rs/core/src/exec_policy_tests.rs +++ b/codex-rs/core/src/exec_policy_tests.rs @@ -374,6 +374,42 @@ async fn merges_requirements_exec_policy_network_rules() -> anyhow::Result<()> { Ok(()) } +#[tokio::test] +async fn malformed_custom_rules_preserve_requirements_exec_policy() -> anyhow::Result<()> { + let temp_dir = tempdir()?; + let policy_dir = temp_dir.path().join(RULES_DIR_NAME); + fs::create_dir_all(&policy_dir)?; + fs::write(policy_dir.join("broken.rules"), "prefix_rule(")?; + + let mut requirements_exec_policy = Policy::empty(); + requirements_exec_policy.add_prefix_rule(&["rm".to_string()], Decision::Forbidden)?; + let requirements = ConfigRequirements { + exec_policy: Some(Sourced::new( + RequirementsExecPolicy::new(requirements_exec_policy), + RequirementSource::Unknown, + )), + ..ConfigRequirements::default() + }; + let dot_codex_folder = AbsolutePathBuf::from_absolute_path(temp_dir.path())?; + let layer = ConfigLayerEntry::new( + ConfigLayerSource::Project { dot_codex_folder }, + TomlValue::Table(Default::default()), + ); + let config_stack = + ConfigLayerStack::new(vec![layer], requirements, ConfigRequirementsToml::default())?; + + let (policy, warning) = load_exec_policy_with_warning(&config_stack).await?; + + assert!(matches!(warning, Some(ExecPolicyError::ParsePolicy { .. }))); + assert_eq!( + policy + .check_multiple([vec!["rm".to_string()]].iter(), &|_| Decision::Allow) + .decision, + Decision::Forbidden + ); + Ok(()) +} + #[tokio::test] async fn preserves_host_executables_when_requirements_overlay_is_present() -> anyhow::Result<()> { let temp_dir = tempdir()?; diff --git a/codex-rs/core/src/network_proxy_loader.rs b/codex-rs/core/src/network_proxy_loader.rs index 0a4fe2d7c2..62ed44ad81 100644 --- a/codex-rs/core/src/network_proxy_loader.rs +++ b/codex-rs/core/src/network_proxy_loader.rs @@ -2,9 +2,8 @@ use crate::config::find_codex_home; use crate::config::is_builtin_permission_profile_name; use crate::config::reject_unknown_builtin_permission_profile; use crate::config::resolve_permission_profile; -use crate::exec_policy::ExecPolicyError; use crate::exec_policy::format_exec_policy_error_with_source; -use crate::exec_policy::load_exec_policy; +use crate::exec_policy::load_exec_policy_with_warning; use anyhow::Context; use anyhow::Result; use codex_config::CONFIG_TOML_FILE; @@ -64,13 +63,15 @@ async fn build_config_state_with_mtimes() -> Result<(ConfigState, Vec (policy, None), - Err(err @ ExecPolicyError::ParsePolicy { .. }) => { - (codex_execpolicy::Policy::empty(), Some(err)) - } - Err(err) => return Err(err.into()), - }; + let layer_mtimes = collect_layer_mtimes(&config_layer_stack); + let state = build_config_state_from_layers(&config_layer_stack).await?; + Ok((state, layer_mtimes)) +} + +async fn build_config_state_from_layers( + config_layer_stack: &ConfigLayerStack, +) -> Result { + let (exec_policy, warning) = load_exec_policy_with_warning(config_layer_stack).await?; if let Some(err) = warning.as_ref() { tracing::warn!( "failed to parse execpolicy while building network proxy state: {}", @@ -78,12 +79,10 @@ async fn build_config_state_with_mtimes() -> Result<(ConfigState, Vec Vec { diff --git a/codex-rs/core/src/network_proxy_loader_tests.rs b/codex-rs/core/src/network_proxy_loader_tests.rs index d6c8efc9ae..f7c7c2e452 100644 --- a/codex-rs/core/src/network_proxy_loader_tests.rs +++ b/codex-rs/core/src/network_proxy_loader_tests.rs @@ -5,6 +5,9 @@ use codex_config::ConfigLayerSource; use codex_config::ConfigLayerStack; use codex_config::ConfigRequirements; use codex_config::ConfigRequirementsToml; +use codex_config::RequirementSource; +use codex_config::RequirementsExecPolicy; +use codex_config::Sourced; use codex_config::permissions_toml::NetworkDomainPermissionToml; use codex_config::permissions_toml::NetworkDomainPermissionsToml; use codex_execpolicy::Decision; @@ -12,6 +15,8 @@ use codex_execpolicy::NetworkRuleProtocol; use codex_execpolicy::Policy; use pretty_assertions::assert_eq; use std::collections::BTreeMap; +use std::fs; +use tempfile::tempdir; #[test] fn higher_precedence_profile_network_overlays_domain_entries() { @@ -225,6 +230,51 @@ fn execpolicy_network_rules_overlay_network_lists() { ); } +#[tokio::test] +async fn malformed_custom_rules_preserve_managed_denied_domain() { + let temp_dir = tempdir().expect("create temp dir"); + let policy_dir = temp_dir.path().join("rules"); + fs::create_dir_all(&policy_dir).expect("create policy dir"); + fs::write(policy_dir.join("broken.rules"), "prefix_rule(").expect("write malformed policy"); + + let mut requirements_exec_policy = Policy::empty(); + requirements_exec_policy + .add_network_rule( + "blocked.example.com", + NetworkRuleProtocol::Https, + Decision::Forbidden, + /*justification*/ None, + ) + .expect("managed network rule should be valid"); + let requirements = ConfigRequirements { + exec_policy: Some(Sourced::new( + RequirementsExecPolicy::new(requirements_exec_policy), + RequirementSource::Unknown, + )), + ..ConfigRequirements::default() + }; + let dot_codex_folder = AbsolutePathBuf::from_absolute_path(temp_dir.path()) + .expect("dot codex folder should be absolute"); + let layers = ConfigLayerStack::new( + vec![ConfigLayerEntry::new( + ConfigLayerSource::Project { dot_codex_folder }, + toml::Value::Table(Default::default()), + )], + requirements, + ConfigRequirementsToml::default(), + ) + .expect("layer stack should be valid"); + + let state = build_config_state_from_layers(&layers) + .await + .expect("proxy state should tolerate malformed custom rules"); + + assert_eq!( + state.config.network.denied_domains(), + Some(vec!["blocked.example.com".to_string()]) + ); +} + #[test] fn apply_network_constraints_includes_allow_all_unix_sockets_flag() { let config: toml::Value = toml::from_str( diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index 4e64c66b0a..0c73b74ab2 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used)] use anyhow::Result; +use codex_config::test_support::CloudConfigBundleFixture; use codex_features::Feature; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; @@ -17,6 +18,7 @@ use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; +use core_test_support::skip_if_target_windows; use core_test_support::test_codex::local_selections; use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; @@ -255,6 +257,84 @@ async fn execpolicy_blocks_shell_invocation() -> Result<()> { Ok(()) } +#[tokio::test] +async fn malformed_custom_rules_preserve_managed_forbidden_prefix() -> Result<()> { + skip_if_target_windows!( + Ok(()), + "managed prefix fixture uses POSIX executable semantics" + ); + + let mut builder = test_codex() + .with_cloud_config_bundle( + CloudConfigBundleFixture::loader_with_enterprise_requirement( + r#" +[rules] +prefix_rules = [ + { pattern = [{ token = "echo" }], decision = "forbidden" }, +] +"#, + ), + ) + .with_config(|config| { + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + let policy_path = config.codex_home.join("rules").join("broken.rules"); + fs::create_dir_all( + policy_path + .parent() + .expect("policy directory must have a parent"), + ) + .expect("create policy directory"); + fs::write(policy_path, "prefix_rule(").expect("write malformed policy file"); + }); + let server = start_mock_server().await; + let test = builder.build_with_auto_env(&server).await?; + let call_id = "managed-shell-forbidden"; + let args = json!({ + "cmd": "echo blocked", + "yield_time_ms": 1_000, + }); + + mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-managed-1"), + ev_function_call(call_id, "exec_command", &serde_json::to_string(&args)?), + ev_completed("resp-managed-1"), + ]), + ) + .await; + let results_mock = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-managed-1", "done"), + ev_completed("resp-managed-2"), + ]), + ) + .await; + + test.submit_turn_with_approval_and_permission_profile( + "run shell command", + AskForApproval::Never, + PermissionProfile::Disabled, + ) + .await?; + + let output_item = results_mock.single_request().function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("function call output should include a string output payload"); + assert!( + output.contains("policy forbids commands starting with `echo`"), + "unexpected output: {output}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_command_empty_script_with_collaboration_mode_does_not_panic() -> Result<()> { let server = start_mock_server().await; From 775ef7dcc7d50069e759f3e11454f412a3e39d95 Mon Sep 17 00:00:00 2001 From: ashwinnathan-openai Date: Mon, 6 Jul 2026 23:23:56 -0400 Subject: [PATCH 12/79] [codex] Support sequential cutoff reasoning summaries (#31306) ## Summary When enabled for the OpenAI provider, Codex sends `stream_options.reasoning_summary_delivery = "sequential_cutoff"` on HTTP and WebSocket requests, including prewarm, and renders completed summary sections from `reasoning_summary_text.done`. Flag-off and non-OpenAI behavior is unchanged. ## Expected rollout ```text reasoning 0 added summary 0 done summary 1 done summary 2 starts summary 2 cancelled / incomplete reasoning 0 done <-- cancel summary 2 work and mark it incomplete message 1 added message 1 text streams message 1 completed ``` Depends on [openai/openai#1096660](https://github.com/openai/openai/pull/1096660). --- codex-rs/codex-api/src/common.rs | 21 +++++ .../src/endpoint/responses_websocket.rs | 1 + codex-rs/codex-api/src/lib.rs | 2 + codex-rs/codex-api/src/sse/responses.rs | 38 ++++++++ codex-rs/codex-api/tests/clients.rs | 3 + codex-rs/core/config.schema.json | 6 ++ codex-rs/core/src/client.rs | 16 +++- codex-rs/core/src/client_common_tests.rs | 4 + codex-rs/core/src/client_tests.rs | 3 + codex-rs/core/src/session/session.rs | 3 + codex-rs/core/src/session/tests.rs | 9 ++ codex-rs/core/src/session/turn.rs | 45 +++++++++ codex-rs/core/src/turn_timing.rs | 1 + codex-rs/core/tests/responses_headers.rs | 3 + codex-rs/core/tests/suite/client.rs | 58 ++++++++++++ .../core/tests/suite/client_websockets.rs | 42 ++++++++- codex-rs/core/tests/suite/items.rs | 93 +++++++++++++++++++ codex-rs/features/src/lib.rs | 8 ++ codex-rs/memories/write/src/runtime.rs | 1 + codex-rs/otel/src/events/session_telemetry.rs | 1 + 20 files changed, 352 insertions(+), 6 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index 254a5cb38f..e4600e26aa 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -104,6 +104,11 @@ pub enum ResponseEvent { delta: String, summary_index: i64, }, + ReasoningSummaryDone { + item_id: String, + text: String, + summary_index: i64, + }, ReasoningContentDelta { delta: String, content_index: i64, @@ -148,6 +153,17 @@ pub struct Reasoning { pub context: Option, } +#[derive(Debug, Serialize, Clone, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ReasoningSummaryDelivery { + SequentialCutoff, +} + +#[derive(Debug, Serialize, Clone, PartialEq)] +pub struct StreamOptions { + pub reasoning_summary_delivery: ReasoningSummaryDelivery, +} + #[derive(Debug, Serialize, Default, Clone, PartialEq)] #[serde(rename_all = "snake_case")] pub enum TextFormatType { @@ -209,6 +225,8 @@ pub struct ResponsesApiRequest { pub reasoning: Option, pub store: bool, pub stream: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub stream_options: Option, pub include: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub service_tier: Option, @@ -233,6 +251,7 @@ impl From<&ResponsesApiRequest> for ResponseCreateWsRequest { reasoning: request.reasoning.clone(), store: request.store, stream: request.stream, + stream_options: request.stream_options.clone(), include: request.include.clone(), service_tier: request.service_tier.clone(), prompt_cache_key: request.prompt_cache_key.clone(), @@ -258,6 +277,8 @@ pub struct ResponseCreateWsRequest { pub reasoning: Option, pub store: bool, pub stream: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub stream_options: Option, pub include: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub service_tier: Option, diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index 447450fae1..cce056f638 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -851,6 +851,7 @@ mod tests { reasoning: None, store: false, stream: true, + stream_options: None, include: vec!["reasoning.encrypted_content".to_string()], service_tier: Some("priority".to_string()), prompt_cache_key: Some("cache-key".to_string()), diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index 72de4d0585..1d1a4c8c6e 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -34,11 +34,13 @@ pub use crate::common::RawMemory; pub use crate::common::RawMemoryMetadata; pub use crate::common::Reasoning; pub use crate::common::ReasoningContext; +pub use crate::common::ReasoningSummaryDelivery; pub use crate::common::ResponseCreateWsRequest; pub use crate::common::ResponseEvent; pub use crate::common::ResponseStream; pub use crate::common::ResponsesApiRequest; pub use crate::common::ResponsesWsRequest; +pub use crate::common::StreamOptions; pub use crate::common::TextControls; pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY; pub use crate::common::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY; diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 17d31a02ee..265d3ced5c 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -167,6 +167,7 @@ pub struct ResponsesStreamEvent { item_id: Option, call_id: Option, delta: Option, + text: Option, summary_index: Option, content_index: Option, safety_buffering: Option, @@ -358,6 +359,17 @@ pub fn process_responses_event( })); } } + "response.reasoning_summary_text.done" => { + if let (Some(item_id), Some(text), Some(summary_index)) = + (event.item_id, event.text, event.summary_index) + { + return Ok(Some(ResponseEvent::ReasoningSummaryDone { + item_id, + text, + summary_index, + })); + } + } "response.reasoning_text.delta" => { if let (Some(delta), Some(content_index)) = (event.delta, event.content_index) { return Ok(Some(ResponseEvent::ReasoningContentDelta { @@ -796,6 +808,32 @@ mod tests { } } + #[tokio::test] + async fn parses_reasoning_summary_done() { + let events = run_sse(vec![ + json!({ + "type": "response.reasoning_summary_text.done", + "item_id": "reasoning-1", + "summary_index": 0, + "text": "Checking", + }), + json!({ + "type": "response.completed", + "response": { "id": "resp1" }, + }), + ]) + .await; + + assert_matches!( + &events[0], + ResponseEvent::ReasoningSummaryDone { + item_id, + text, + summary_index: 0, + } if item_id == "reasoning-1" && text == "Checking" + ); + } + #[tokio::test] async fn error_when_missing_completed() { let item1 = json!({ diff --git a/codex-rs/codex-api/tests/clients.rs b/codex-rs/codex-api/tests/clients.rs index 60a9852cfa..ab4ab1d08f 100644 --- a/codex-rs/codex-api/tests/clients.rs +++ b/codex-rs/codex-api/tests/clients.rs @@ -321,6 +321,7 @@ async fn responses_client_stream_request_preserves_item_ids() -> Result<()> { reasoning: None, store: false, stream: true, + stream_options: None, include: Vec::new(), service_tier: None, prompt_cache_key: None, @@ -407,6 +408,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> { reasoning: None, store: false, stream: true, + stream_options: None, include: Vec::new(), service_tier: None, prompt_cache_key: None, @@ -526,6 +528,7 @@ async fn azure_store_sends_ids_and_headers() -> Result<()> { reasoning: None, store: true, stream: true, + stream_options: None, include: Vec::new(), service_tier: None, prompt_cache_key: None, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 876180dd7e..0a48882b09 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -469,6 +469,9 @@ "computer_use": { "type": "boolean" }, + "concurrent_reasoning_summaries": { + "type": "boolean" + }, "connectors": { "type": "boolean" }, @@ -4838,6 +4841,9 @@ "computer_use": { "type": "boolean" }, + "concurrent_reasoning_summaries": { + "type": "boolean" + }, "connectors": { "type": "boolean" }, diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 43a758b0e8..716466b189 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -56,6 +56,7 @@ use codex_api::ResponsesWebsocketConnection as ApiWebSocketConnection; use codex_api::ResponsesWsRequest; use codex_api::SharedAuthProvider; use codex_api::SseTelemetry; +use codex_api::StreamOptions; use codex_api::TransportError; use codex_api::WebsocketTelemetry; use codex_api::auth_header_telemetry; @@ -203,6 +204,7 @@ struct ModelClientState { include_timing_metrics: bool, beta_features_header: Option, item_ids_enabled: bool, + concurrent_reasoning_summaries_enabled: bool, include_attestation: bool, attestation_provider: Option>, disable_websockets: AtomicBool, @@ -311,6 +313,7 @@ fn responses_request_properties_match( reasoning: previous_reasoning, store: previous_store, stream: previous_stream, + stream_options: _, include: previous_include, service_tier: previous_service_tier, prompt_cache_key: previous_prompt_cache_key, @@ -327,6 +330,7 @@ fn responses_request_properties_match( reasoning: current_reasoning, store: current_store, stream: current_stream, + stream_options: _, include: current_include, service_tier: current_service_tier, prompt_cache_key: current_prompt_cache_key, @@ -342,6 +346,8 @@ fn responses_request_properties_match( && previous_reasoning == current_reasoning && previous_store == current_store && previous_stream == current_stream + // Stream options control delivery for this response, not the context + // referenced by `previous_response_id`. && previous_include == current_include && previous_service_tier == current_service_tier && previous_prompt_cache_key == current_prompt_cache_key @@ -409,6 +415,7 @@ impl ModelClient { include_timing_metrics: bool, beta_features_header: Option, item_ids_enabled: bool, + concurrent_reasoning_summaries_enabled: bool, attestation_provider: Option>, ) -> Self { let model_provider = create_model_provider(provider_info, auth_manager); @@ -431,6 +438,7 @@ impl ModelClient { include_timing_metrics, beta_features_header, item_ids_enabled, + concurrent_reasoning_summaries_enabled, include_attestation, attestation_provider, disable_websockets: AtomicBool::new(false), @@ -820,7 +828,8 @@ impl ModelClient { responses_metadata: &CodexResponsesMetadata, ) -> Result { let mut input = prompt.get_formatted_input_for_request(model_info.use_responses_lite); - if !self.state.provider.info().is_openai() { + let is_openai = self.state.provider.info().is_openai(); + if !is_openai { input .iter_mut() .for_each(ResponseItem::clear_internal_chat_message_metadata_passthrough); @@ -848,6 +857,10 @@ impl ModelClient { } else { (prompt.base_instructions.text.clone(), Some(tools)) }; + let stream_options = (self.state.concurrent_reasoning_summaries_enabled && is_openai) + .then_some(StreamOptions { + reasoning_summary_delivery: codex_api::ReasoningSummaryDelivery::SequentialCutoff, + }); let reasoning = Self::build_reasoning(model_info, effort, summary); let include = if reasoning.is_some() { vec!["reasoning.encrypted_content".to_string()] @@ -882,6 +895,7 @@ impl ModelClient { reasoning, store: provider.is_azure_responses_endpoint(), stream: true, + stream_options, include, service_tier, prompt_cache_key, diff --git a/codex-rs/core/src/client_common_tests.rs b/codex-rs/core/src/client_common_tests.rs index 38c4aaecb5..b8d0a364a3 100644 --- a/codex-rs/core/src/client_common_tests.rs +++ b/codex-rs/core/src/client_common_tests.rs @@ -116,6 +116,7 @@ fn serializes_text_verbosity_when_set() { reasoning: None, store: false, stream: true, + stream_options: None, include: vec![], prompt_cache_key: None, service_tier: None, @@ -163,6 +164,7 @@ fn serializes_text_schema_with_strict_format() { reasoning: None, store: false, stream: true, + stream_options: None, include: vec![], prompt_cache_key: None, service_tier: None, @@ -224,6 +226,7 @@ fn omits_text_when_not_set() { reasoning: None, store: false, stream: true, + stream_options: None, include: vec![], prompt_cache_key: None, service_tier: None, @@ -247,6 +250,7 @@ fn serializes_flex_service_tier_when_set() { reasoning: None, store: false, stream: true, + stream_options: None, include: vec![], prompt_cache_key: None, service_tier: Some(ServiceTier::Flex.to_string()), diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index 82c464625d..c05f56b713 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -103,6 +103,7 @@ fn test_model_client_with_thread_id( /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ) } @@ -147,6 +148,7 @@ async fn compact_uses_bearer_after_agent_identity_session_fallback() -> anyhow:: /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); let prompt = Prompt { @@ -821,6 +823,7 @@ fn model_client_with_counting_attestation( /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, Some(Arc::new(CountingAttestationProvider { calls: attestation_calls.clone(), })), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 2261eaa495..78a7f02588 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -1111,6 +1111,9 @@ impl Session { config.features.enabled(Feature::RuntimeMetrics), Self::build_model_client_beta_features_header(config.as_ref()), /*item_ids_enabled*/ config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ config + .features + .enabled(Feature::ConcurrentReasoningSummaries), attestation_provider, ) .with_prompt_cache_key_override( diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 6cc223cd7d..1ff469cf4c 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -490,6 +490,7 @@ fn test_model_client_session() -> crate::client::ModelClientSession { /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ) .new_session() @@ -5460,6 +5461,10 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { config.features.enabled(Feature::RuntimeMetrics), Session::build_model_client_beta_features_header(config.as_ref()), /*item_ids_enabled*/ config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ + config + .features + .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, ), code_mode_service: crate::tools::code_mode::CodeModeService::new(Arc::new( @@ -7586,6 +7591,10 @@ where config.features.enabled(Feature::RuntimeMetrics), Session::build_model_client_beta_features_header(config.as_ref()), /*item_ids_enabled*/ config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ + config + .features + .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, ), code_mode_service: crate::tools::code_mode::CodeModeService::new(Arc::new( diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index f16b525002..708f42f0ff 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -1909,6 +1909,11 @@ async fn try_run_sampling_request( turn_context.provider.info().name.as_str(), ); let sampling_timing_guard = turn_context.turn_timing_state.begin_sampling(); + let uses_sequential_cutoff_reasoning_summaries = turn_context + .config + .features + .enabled(Feature::ConcurrentReasoningSummaries) + && turn_context.provider.info().is_openai(); let mut stream = client_session .stream( prompt, @@ -2291,6 +2296,9 @@ async fn try_run_sampling_request( delta, summary_index, } => { + if uses_sequential_cutoff_reasoning_summaries { + continue; + } if let Some(active) = active_item.as_ref() { if !active_item_is_streaming_to_client { continue; @@ -2309,6 +2317,9 @@ async fn try_run_sampling_request( } } ResponseEvent::ReasoningSummaryPartAdded { summary_index } => { + if uses_sequential_cutoff_reasoning_summaries { + continue; + } if let Some(active) = active_item.as_ref() { if !active_item_is_streaming_to_client { continue; @@ -2323,6 +2334,40 @@ async fn try_run_sampling_request( error_or_panic("ReasoningSummaryPartAdded without active item".to_string()); } } + ResponseEvent::ReasoningSummaryDone { + item_id, + text, + summary_index, + } => { + if !uses_sequential_cutoff_reasoning_summaries { + continue; + } + let Some(active) = active_item.as_ref() else { + continue; + }; + if !active_item_is_streaming_to_client || active.id() != item_id { + continue; + } + if summary_index > 0 { + sess.send_event( + &turn_context, + EventMsg::AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent { + item_id: item_id.clone(), + summary_index, + }), + ) + .await; + } + let event = ReasoningContentDeltaEvent { + thread_id: sess.thread_id.to_string(), + turn_id: turn_context.sub_id.clone(), + item_id, + delta: text, + summary_index, + }; + sess.send_event(&turn_context, EventMsg::ReasoningContentDelta(event)) + .await; + } ResponseEvent::ReasoningContentDelta { delta, content_index, diff --git a/codex-rs/core/src/turn_timing.rs b/codex-rs/core/src/turn_timing.rs index 04f7aeb69b..d0f4f46cc3 100644 --- a/codex-rs/core/src/turn_timing.rs +++ b/codex-rs/core/src/turn_timing.rs @@ -334,6 +334,7 @@ fn response_event_records_turn_ttft(event: &ResponseEvent) -> bool { } ResponseEvent::OutputTextDelta(_) | ResponseEvent::ReasoningSummaryDelta { .. } + | ResponseEvent::ReasoningSummaryDone { .. } | ResponseEvent::ReasoningContentDelta { .. } => true, ResponseEvent::Created | ResponseEvent::ServerModel(_) diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 5b7c2c65b8..4c5f906160 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -131,6 +131,7 @@ async fn responses_stream_includes_subagent_header_on_review() { /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); @@ -265,6 +266,7 @@ async fn responses_stream_includes_subagent_header_on_other() { /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); @@ -385,6 +387,7 @@ async fn responses_respects_model_info_overrides_from_config() { /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index c87539f940..92624bfcb3 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -1334,6 +1334,10 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ + config + .features + .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, ); let responses_metadata = test_turn_responses_metadata(&client, thread_id); @@ -2376,6 +2380,9 @@ async fn configured_reasoning_summary_is_sent() -> anyhow::Result<()> { let TestCodex { codex, .. } = test_codex() .with_config(|config| { config.model_reasoning_summary = Some(ReasoningSummary::Concise); + let _ = config + .features + .enable(Feature::ConcurrentReasoningSummaries); }) .build(&server) .await?; @@ -2412,6 +2419,55 @@ async fn configured_reasoning_summary_is_sent() -> anyhow::Result<()> { .and_then(|reasoning| reasoning.get("context")), None ); + pretty_assertions::assert_eq!( + request_body + .get("stream_options") + .and_then(|stream_options| stream_options.get("reasoning_summary_delivery")) + .and_then(|value| value.as_str()), + Some("sequential_cutoff") + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sequential_cutoff_is_omitted_for_non_openai_provider() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.model_provider.name = "mock".to_string(); + let _ = config + .features + .enable(Feature::ConcurrentReasoningSummaries); + }) + .build(&server) + .await?; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request_body = resp_mock.single_request().body_json(); + pretty_assertions::assert_eq!(request_body.get("stream_options"), None); Ok(()) } @@ -2583,6 +2639,7 @@ async fn reasoning_summary_is_omitted_when_disabled() -> anyhow::Result<()> { .and_then(|reasoning| reasoning.get("summary")), None ); + pretty_assertions::assert_eq!(request_body.get("stream_options"), None); Ok(()) } @@ -2948,6 +3005,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { /*include_timing_metrics*/ false, /*beta_features_header*/ None, /*item_ids_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); let responses_metadata = test_turn_responses_metadata(&client, thread_id); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index d5218cdcab..c56a8680ab 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -386,7 +386,13 @@ async fn responses_websocket_request_prewarm_reuses_connection() { ]]) .await; - let harness = websocket_harness_with_options(&server, /*runtime_metrics_enabled*/ true).await; + let mut provider = websocket_provider(&server); + provider.name = ModelProviderInfo::create_openai_provider(/*base_url*/ None).name; + let harness = websocket_harness_with_provider_options( + provider, /*runtime_metrics_enabled*/ true, + /*concurrent_reasoning_summaries_enabled*/ true, + ) + .await; let mut client_session = harness.client.new_session(); let prompt = prompt_with_input(vec![message_item("hello")]); let responses_metadata = prewarm_metadata(&harness, /*turn_id*/ None); @@ -422,6 +428,10 @@ async fn responses_websocket_request_prewarm_reuses_connection() { assert_eq!(warmup["type"].as_str(), Some("response.create")); assert_eq!(warmup["generate"].as_bool(), Some(false)); + assert_eq!( + warmup["stream_options"]["reasoning_summary_delivery"].as_str(), + Some("sequential_cutoff") + ); assert_eq!(warmup["tools"], serde_json::json!([])); let warmup_turn_metadata: serde_json::Value = serde_json::from_str( warmup["client_metadata"]["x-codex-turn-metadata"] @@ -436,6 +446,10 @@ async fn responses_websocket_request_prewarm_reuses_connection() { assert_eq!(follow_up["type"].as_str(), Some("response.create")); assert_eq!(follow_up["previous_response_id"].as_str(), Some("warm-1")); assert_eq!(follow_up["input"], serde_json::json!([])); + assert_eq!( + follow_up["stream_options"]["reasoning_summary_delivery"].as_str(), + Some("sequential_cutoff") + ); server.shutdown().await; } @@ -990,8 +1004,11 @@ async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() { // use OpenAI provider to check metadata logic let mut provider = websocket_provider(&server); provider.name = ModelProviderInfo::create_openai_provider(/*base_url*/ None).name; - let harness = - websocket_harness_with_provider_options(provider, /*runtime_metrics_enabled*/ false).await; + let harness = websocket_harness_with_provider_options( + provider, /*runtime_metrics_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, + ) + .await; // Turn one: initiate let prompt_one = prompt_with_input(vec![message_item("hello")]); @@ -2195,13 +2212,18 @@ async fn websocket_harness_with_options( server: &WebSocketTestServer, runtime_metrics_enabled: bool, ) -> WebsocketTestHarness { - websocket_harness_with_provider_options(websocket_provider(server), runtime_metrics_enabled) - .await + websocket_harness_with_provider_options( + websocket_provider(server), + runtime_metrics_enabled, + /*concurrent_reasoning_summaries_enabled*/ false, + ) + .await } async fn websocket_harness_with_provider_options( provider: ModelProviderInfo, runtime_metrics_enabled: bool, + concurrent_reasoning_summaries_enabled: bool, ) -> WebsocketTestHarness { let codex_home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&codex_home).await; @@ -2212,6 +2234,12 @@ async fn websocket_harness_with_provider_options( .enable(Feature::RuntimeMetrics) .expect("test config should allow feature update"); } + if concurrent_reasoning_summaries_enabled { + config + .features + .enable(Feature::ConcurrentReasoningSummaries) + .expect("test config should allow feature update"); + } let config = Arc::new(config); let model_info = codex_core::test_support::construct_model_info_offline(MODEL, &config); let thread_id = ThreadId::new(); @@ -2251,6 +2279,10 @@ async fn websocket_harness_with_provider_options( runtime_metrics_enabled, /*beta_features_header*/ None, /*item_ids_enabled*/ config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ + config + .features + .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, ); diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 515d496b8b..196277394a 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -1,6 +1,7 @@ #![cfg(not(target_os = "windows"))] use anyhow::Ok; +use codex_features::Feature; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; @@ -1134,6 +1135,98 @@ async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sequential_cutoff_renders_done_summaries_for_active_reasoning_item() -> anyhow::Result<()> +{ + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config + .features + .enable(Feature::ConcurrentReasoningSummaries) + .expect("test config should allow feature update"); + }) + .build(&server) + .await?; + let summary_done = |item_id: &str, summary_index: i64, text: &str| { + serde_json::json!({ + "type": "response.reasoning_summary_text.done", + "item_id": item_id, + "summary_index": summary_index, + "text": text, + }) + }; + mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_reasoning_item_added("reasoning-1", &[""]), + // Sequential cutoff renders atomic done events, not partial legacy events. + ev_reasoning_summary_text_delta("partial"), + summary_done("reasoning-1", 0, "step one"), + summary_done("reasoning-1", 1, "step two"), + ev_reasoning_item("reasoning-1", &["step one", "step two"], &[]), + ev_message_item_added("message-1", ""), + // Drop a stale completion rather than attaching it to the active message. + summary_done("reasoning-1", 2, "late step"), + ev_output_text_delta("Done"), + ev_assistant_message("message-1", "Done"), + ev_completed("resp-1"), + ]), + ) + .await; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "reason through it".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + + let reasoning_item = wait_for_event_match(&codex, |ev| match ev { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::Reasoning(item), + .. + }) => Some(item.clone()), + _ => None, + }) + .await; + + let mut summary_deltas = Vec::new(); + let mut summary_sections = Vec::new(); + loop { + match wait_for_event(&codex, |_| true).await { + EventMsg::ReasoningContentDelta(event) => { + summary_deltas.push((event.item_id, event.delta, event.summary_index)); + } + EventMsg::AgentReasoningSectionBreak(event) => { + summary_sections.push((event.item_id, event.summary_index)); + } + EventMsg::TurnComplete(_) => break, + _ => {} + } + } + + assert_eq!( + summary_deltas, + vec![ + (reasoning_item.id.clone(), "step one".to_string(), 0), + (reasoning_item.id, "step two".to_string(), 1), + ] + ); + assert_eq!(summary_sections, vec![("reasoning-1".to_string(), 1)]); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn reasoning_raw_content_delta_respects_flag() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 7ab7df18d1..ce5ca459b4 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -204,6 +204,8 @@ pub enum Feature { ResizeAllImages, /// Generate Responses API item IDs for client-created history items. ItemIds, + /// Request sequential cutoff reasoning summary delivery. + ConcurrentReasoningSummaries, /// Allow prompting and installing missing MCP dependencies. SkillMcpDependencyInstall, /// Removed compatibility flag for deleted skill env var dependency prompting. @@ -1184,6 +1186,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::ConcurrentReasoningSummaries, + key: "concurrent_reasoning_summaries", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::SkillMcpDependencyInstall, key: "skill_mcp_dependency_install", diff --git a/codex-rs/memories/write/src/runtime.rs b/codex-rs/memories/write/src/runtime.rs index 6c7ad3978f..ae0903cfdc 100644 --- a/codex-rs/memories/write/src/runtime.rs +++ b/codex-rs/memories/write/src/runtime.rs @@ -261,6 +261,7 @@ impl MemoryStartupContext { config.features.enabled(Feature::RuntimeMetrics), /*beta_features_header*/ None, config.features.enabled(Feature::ItemIds), + /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, ); diff --git a/codex-rs/otel/src/events/session_telemetry.rs b/codex-rs/otel/src/events/session_telemetry.rs index 440f8f04a5..c470f8dc7c 100644 --- a/codex-rs/otel/src/events/session_telemetry.rs +++ b/codex-rs/otel/src/events/session_telemetry.rs @@ -1195,6 +1195,7 @@ impl SessionTelemetry { ResponseEvent::OutputTextDelta(_) => "text_delta".into(), ResponseEvent::ToolCallInputDelta { .. } => "tool_input_delta".into(), ResponseEvent::ReasoningSummaryDelta { .. } => "reasoning_summary_delta".into(), + ResponseEvent::ReasoningSummaryDone { .. } => "reasoning_summary_done".into(), ResponseEvent::ReasoningContentDelta { .. } => "reasoning_content_delta".into(), ResponseEvent::ReasoningSummaryPartAdded { .. } => { "reasoning_summary_part_added".into() From 9365b08467b79a116ff78f00931306d3dfca004f Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 6 Jul 2026 20:25:33 -0700 Subject: [PATCH 13/79] exec-server: use virtual time in Noise relay test (#31344) ## Why `fragmented_writes_yield_to_keepalive_and_queued_pong` deliberately blocks WebSocket writes while exercising keepalive and queued-Pong scheduling. It previously advanced those states with wall-clock sleeps. Under a sufficiently delayed CI worker, those sleeps and scheduling gaps could consume the test-only 100 ms Pong-watchdog budget, causing the relay to exit and the next write-permit send to fail with `TrySendError::Disconnected`. The failure was therefore a timing flake in the harness test, not evidence that the production relay mishandled a Pong. ## What changed - Run this test with Tokio time paused. - Advance the virtual clock through its two keepalive transitions instead of sleeping in wall-clock time. - Enable Tokio's `test-util` feature only for `codex-exec-server` dev dependencies. No production code or timeout values change. ## Review guide The behavioral change is confined to `noise_relay/harness_tests.rs`; the `Cargo.toml` change only exposes Tokio's paused-clock test APIs. ## Validation - `just test -p codex-exec-server fragmented_writes_yield_to_keepalive_and_queued_pong` - `just fix -p codex-exec-server` - `just bazel-lock-update` (no lockfile changes) --- codex-rs/exec-server/Cargo.toml | 1 + codex-rs/exec-server/src/noise_relay/harness_tests.rs | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml index ba9058f0c6..f303ac70ee 100644 --- a/codex-rs/exec-server/Cargo.toml +++ b/codex-rs/exec-server/Cargo.toml @@ -74,6 +74,7 @@ rustls = { workspace = true } serial_test = { workspace = true } tempfile = { workspace = true } test-case = "3.3.1" +tokio = { workspace = true, features = ["test-util"] } tracing-opentelemetry = { workspace = true } tracing-subscriber = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/exec-server/src/noise_relay/harness_tests.rs b/codex-rs/exec-server/src/noise_relay/harness_tests.rs index ce26a8ca8c..348351e61c 100644 --- a/codex-rs/exec-server/src/noise_relay/harness_tests.rs +++ b/codex-rs/exec-server/src/noise_relay/harness_tests.rs @@ -31,7 +31,7 @@ use crate::noise_channel::PendingResponderHandshake; const ENVIRONMENT_ID: &str = "environment-1"; const EXECUTOR_REGISTRATION_ID: &str = "registration-1"; -#[tokio::test] +#[tokio::test(start_paused = true)] async fn fragmented_writes_yield_to_keepalive_and_queued_pong() -> Result<()> { let (connection, mut control, mut outbound_rx) = connected_controlled_harness().await?; @@ -48,7 +48,7 @@ async fn fragmented_writes_yield_to_keepalive_and_queued_pong() -> Result<()> { .await?; control.wait_for_blocked_write(/*expected*/ 1).await?; - tokio::time::sleep(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await; + tokio::time::advance(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await; control.grant_writes(/*count*/ 1); let first_data = read_outbound_data(&mut outbound_rx).await?; assert_eq!(first_data.seq, 0); @@ -64,7 +64,7 @@ async fn fragmented_writes_yield_to_keepalive_and_queued_pong() -> Result<()> { control.wait_for_blocked_write(/*expected*/ 3).await?; control.send_inbound(Message::Pong(ping_payload))?; - tokio::time::sleep(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await; + tokio::time::advance(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await; control.grant_writes(/*count*/ 1); let second_data = read_outbound_data(&mut outbound_rx).await?; assert_eq!(second_data.seq, 1); From b9b934e99b57aa1908a7cd83adee9faf6d0b8f7d Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Mon, 6 Jul 2026 20:41:57 -0700 Subject: [PATCH 14/79] refactor(protocol): map canonical tool items to legacy events (#31296) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description This PR adds legacy `EventMsg` mappings for the `TurnItem` types introduced in [#30282](https://github.com/openai/codex/pull/30282): - `CommandExecution` - `DynamicToolCall` - `CollabAgentToolCall` - `SubAgentActivity` When their producers move to canonical `ItemStarted` / `ItemCompleted`, raw core event consumers can still receive the existing begin/end-style events. The canonical item lifecycle remains the live source of truth. We also record the mapped legacy events in rollout trace so the producer migration preserves the existing tool-runtime trace entries. ## Why This is the compatibility layer for the follow-up producer migrations. Splitting it out first keeps each producer PR small and keeps the legacy mapping in one place. ## What changed - Added `TurnItem` → legacy `EventMsg` mappings in `protocol/src/legacy_events.rs`. - Added the command execution status conversion used by the exec mapping. - Added focused coverage for command execution and dynamic tool mappings. --- codex-rs/core/src/session/mod.rs | 3 + codex-rs/protocol/src/items.rs | 11 + codex-rs/protocol/src/legacy_events.rs | 304 +++++++++++++++++++++++++ codex-rs/protocol/src/protocol.rs | 137 +++++++++++ 4 files changed, 455 insertions(+) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 91a21ef731..fa240b890b 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -1794,6 +1794,9 @@ impl Session { let show_raw_agent_reasoning = self.show_raw_agent_reasoning(); for legacy in legacy_source.as_legacy_events(show_raw_agent_reasoning) { + self.services + .rollout_thread_trace + .record_tool_call_event(turn_context.sub_id.clone(), &legacy); let legacy_event = Event { id: turn_context.sub_id.clone(), msg: legacy, diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 820c3b774b..2c9d073f0d 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -13,6 +13,7 @@ use crate::parse_command::ParsedCommand; use crate::protocol::AgentStatus; use crate::protocol::CollabAgentRef; use crate::protocol::ExecCommandSource; +use crate::protocol::ExecCommandStatus; use crate::protocol::FileChange; use crate::protocol::PatchApplyStatus; use crate::protocol::SubAgentActivityKind; @@ -137,6 +138,16 @@ pub enum CommandExecutionStatus { Declined, } +impl From for CommandExecutionStatus { + fn from(value: ExecCommandStatus) -> Self { + match value { + ExecCommandStatus::Completed => Self::Completed, + ExecCommandStatus::Failed => Self::Failed, + ExecCommandStatus::Declined => Self::Declined, + } + } +} + #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)] pub struct CommandExecutionItem { pub id: String, diff --git a/codex-rs/protocol/src/legacy_events.rs b/codex-rs/protocol/src/legacy_events.rs index f4a511d367..c12a2747a2 100644 --- a/codex-rs/protocol/src/legacy_events.rs +++ b/codex-rs/protocol/src/legacy_events.rs @@ -1,10 +1,20 @@ +use crate::ThreadId; +use crate::dynamic_tools::DynamicToolCallRequest; use crate::items::AgentMessageContent; use crate::items::AgentMessageItem; +use crate::items::CollabAgentTool; +use crate::items::CollabAgentToolCallItem; +use crate::items::CollabAgentToolCallStatus; +use crate::items::CommandExecutionItem; +use crate::items::CommandExecutionStatus; use crate::items::ContextCompactionItem; +use crate::items::DynamicToolCallItem; +use crate::items::DynamicToolCallStatus; use crate::items::FileChangeItem; use crate::items::ImageGenerationItem; use crate::items::McpToolCallItem; use crate::items::ReasoningItem; +use crate::items::SubAgentActivityItem; use crate::items::TurnItem; use crate::items::UserMessageItem; use crate::items::WebSearchItem; @@ -12,8 +22,24 @@ use crate::protocol::AgentMessageContentDeltaEvent; use crate::protocol::AgentMessageEvent; use crate::protocol::AgentReasoningEvent; use crate::protocol::AgentReasoningRawContentEvent; +use crate::protocol::AgentStatus; +use crate::protocol::CollabAgentInteractionBeginEvent; +use crate::protocol::CollabAgentInteractionEndEvent; +use crate::protocol::CollabAgentSpawnBeginEvent; +use crate::protocol::CollabAgentSpawnEndEvent; +use crate::protocol::CollabAgentStatusEntry; +use crate::protocol::CollabCloseBeginEvent; +use crate::protocol::CollabCloseEndEvent; +use crate::protocol::CollabResumeBeginEvent; +use crate::protocol::CollabResumeEndEvent; +use crate::protocol::CollabWaitingBeginEvent; +use crate::protocol::CollabWaitingEndEvent; use crate::protocol::ContextCompactedEvent; +use crate::protocol::DynamicToolCallResponseEvent; use crate::protocol::EventMsg; +use crate::protocol::ExecCommandBeginEvent; +use crate::protocol::ExecCommandEndEvent; +use crate::protocol::ExecCommandStatus; use crate::protocol::ImageGenerationBeginEvent; use crate::protocol::ImageGenerationEndEvent; use crate::protocol::ItemCompletedEvent; @@ -26,6 +52,7 @@ use crate::protocol::PatchApplyEndEvent; use crate::protocol::PatchApplyStatus; use crate::protocol::ReasoningContentDeltaEvent; use crate::protocol::ReasoningRawContentDeltaEvent; +use crate::protocol::SubAgentActivityEvent; use crate::protocol::UserMessageEvent; use crate::protocol::ViewImageToolCallEvent; use crate::protocol::WebSearchBeginEvent; @@ -97,6 +124,258 @@ impl ReasoningItem { } } +impl CommandExecutionItem { + pub(crate) fn as_legacy_begin_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg { + EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: self.id.clone(), + process_id: self.process_id.clone(), + turn_id, + started_at_ms, + command: self.command.clone(), + cwd: self.cwd.clone(), + parsed_cmd: self.parsed_cmd.clone(), + source: self.source, + interaction_input: self.interaction_input.clone(), + }) + } + + pub(crate) fn as_legacy_end_event( + &self, + turn_id: String, + completed_at_ms: i64, + ) -> Option { + let status = match self.status { + CommandExecutionStatus::InProgress => return None, + CommandExecutionStatus::Completed => ExecCommandStatus::Completed, + CommandExecutionStatus::Failed => ExecCommandStatus::Failed, + CommandExecutionStatus::Declined => ExecCommandStatus::Declined, + }; + Some(EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id: self.id.clone(), + process_id: self.process_id.clone(), + turn_id, + completed_at_ms, + command: self.command.clone(), + cwd: self.cwd.clone(), + parsed_cmd: self.parsed_cmd.clone(), + source: self.source, + interaction_input: self.interaction_input.clone(), + stdout: self.stdout.clone().unwrap_or_default(), + stderr: self.stderr.clone().unwrap_or_default(), + aggregated_output: self.aggregated_output.clone().unwrap_or_default(), + exit_code: self.exit_code.unwrap_or_default(), + duration: self.duration.unwrap_or_default(), + formatted_output: self.formatted_output.clone().unwrap_or_default(), + status, + })) + } +} + +impl DynamicToolCallItem { + pub(crate) fn as_legacy_request_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg { + EventMsg::DynamicToolCallRequest(DynamicToolCallRequest { + call_id: self.id.clone(), + turn_id, + started_at_ms, + namespace: self.namespace.clone(), + tool: self.tool.clone(), + arguments: self.arguments.clone(), + }) + } + + pub(crate) fn as_legacy_response_event( + &self, + turn_id: String, + completed_at_ms: i64, + ) -> Option { + if matches!(self.status, DynamicToolCallStatus::InProgress) { + return None; + } + Some(EventMsg::DynamicToolCallResponse( + DynamicToolCallResponseEvent { + call_id: self.id.clone(), + turn_id, + completed_at_ms, + namespace: self.namespace.clone(), + tool: self.tool.clone(), + arguments: self.arguments.clone(), + content_items: self.content_items.clone().unwrap_or_default(), + success: self.success.unwrap_or(false), + error: self.error.clone(), + duration: self.duration.unwrap_or_default(), + }, + )) + } +} + +impl CollabAgentToolCallItem { + pub(crate) fn as_legacy_begin_event(&self, started_at_ms: i64) -> Option { + let receiver_thread_id = self.receiver_thread_ids.first().copied(); + match self.tool { + CollabAgentTool::SpawnAgent => Some(EventMsg::CollabAgentSpawnBegin( + CollabAgentSpawnBeginEvent { + call_id: self.id.clone(), + started_at_ms, + sender_thread_id: self.sender_thread_id, + prompt: self.prompt.clone().unwrap_or_default(), + model: self.model.clone().unwrap_or_default(), + reasoning_effort: self.reasoning_effort.clone().unwrap_or_default(), + }, + )), + CollabAgentTool::SendInput => receiver_thread_id.map(|receiver_thread_id| { + EventMsg::CollabAgentInteractionBegin(CollabAgentInteractionBeginEvent { + call_id: self.id.clone(), + started_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + prompt: self.prompt.clone().unwrap_or_default(), + }) + }), + CollabAgentTool::ResumeAgent => receiver_thread_id.map(|receiver_thread_id| { + let (receiver_agent_nickname, receiver_agent_role) = + self.receiver_agent_identity(receiver_thread_id); + EventMsg::CollabResumeBegin(CollabResumeBeginEvent { + call_id: self.id.clone(), + started_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, + }) + }), + CollabAgentTool::Wait => Some(EventMsg::CollabWaitingBegin(CollabWaitingBeginEvent { + started_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_ids: self.receiver_thread_ids.clone(), + receiver_agents: self.receiver_agents.clone(), + call_id: self.id.clone(), + })), + CollabAgentTool::CloseAgent => receiver_thread_id.map(|receiver_thread_id| { + EventMsg::CollabCloseBegin(CollabCloseBeginEvent { + call_id: self.id.clone(), + started_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + }) + }), + } + } + + pub(crate) fn as_legacy_end_event(&self, completed_at_ms: i64) -> Option { + if matches!(self.status, CollabAgentToolCallStatus::InProgress) { + return None; + } + let receiver_thread_id = self.receiver_thread_ids.first().copied(); + match self.tool { + CollabAgentTool::SpawnAgent => { + let (new_agent_nickname, new_agent_role) = receiver_thread_id + .map(|thread_id| self.receiver_agent_identity(thread_id)) + .unwrap_or_default(); + Some(EventMsg::CollabAgentSpawnEnd(CollabAgentSpawnEndEvent { + call_id: self.id.clone(), + completed_at_ms, + sender_thread_id: self.sender_thread_id, + new_thread_id: receiver_thread_id, + new_agent_nickname, + new_agent_role, + prompt: self.prompt.clone().unwrap_or_default(), + model: self.model.clone().unwrap_or_default(), + reasoning_effort: self.reasoning_effort.clone().unwrap_or_default(), + status: receiver_thread_id + .map(|thread_id| self.agent_status(thread_id)) + .unwrap_or(AgentStatus::NotFound), + })) + } + CollabAgentTool::SendInput => receiver_thread_id.map(|receiver_thread_id| { + let (receiver_agent_nickname, receiver_agent_role) = + self.receiver_agent_identity(receiver_thread_id); + EventMsg::CollabAgentInteractionEnd(CollabAgentInteractionEndEvent { + call_id: self.id.clone(), + completed_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, + prompt: self.prompt.clone().unwrap_or_default(), + status: self.agent_status(receiver_thread_id), + }) + }), + CollabAgentTool::ResumeAgent => receiver_thread_id.map(|receiver_thread_id| { + let (receiver_agent_nickname, receiver_agent_role) = + self.receiver_agent_identity(receiver_thread_id); + EventMsg::CollabResumeEnd(CollabResumeEndEvent { + call_id: self.id.clone(), + completed_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, + status: self.agent_status(receiver_thread_id), + }) + }), + CollabAgentTool::Wait => Some(EventMsg::CollabWaitingEnd(CollabWaitingEndEvent { + sender_thread_id: self.sender_thread_id, + call_id: self.id.clone(), + completed_at_ms, + agent_statuses: self + .receiver_agents + .iter() + .map(|agent| CollabAgentStatusEntry { + thread_id: agent.thread_id, + agent_nickname: agent.agent_nickname.clone(), + agent_role: agent.agent_role.clone(), + status: self.agent_status(agent.thread_id), + }) + .collect(), + statuses: self.agents_states.clone(), + })), + CollabAgentTool::CloseAgent => receiver_thread_id.map(|receiver_thread_id| { + let (receiver_agent_nickname, receiver_agent_role) = + self.receiver_agent_identity(receiver_thread_id); + EventMsg::CollabCloseEnd(CollabCloseEndEvent { + call_id: self.id.clone(), + completed_at_ms, + sender_thread_id: self.sender_thread_id, + receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, + status: self.agent_status(receiver_thread_id), + }) + }), + } + } + + fn receiver_agent_identity(&self, thread_id: ThreadId) -> (Option, Option) { + let receiver_agent = self + .receiver_agents + .iter() + .find(|agent| agent.thread_id == thread_id); + ( + receiver_agent.and_then(|agent| agent.agent_nickname.clone()), + receiver_agent.and_then(|agent| agent.agent_role.clone()), + ) + } + + fn agent_status(&self, thread_id: ThreadId) -> AgentStatus { + self.agents_states + .get(&thread_id) + .cloned() + .unwrap_or(AgentStatus::NotFound) + } +} + +impl SubAgentActivityItem { + pub(crate) fn as_legacy_event(&self, occurred_at_ms: i64) -> EventMsg { + EventMsg::SubAgentActivity(SubAgentActivityEvent { + event_id: self.id.clone(), + occurred_at_ms, + agent_thread_id: self.agent_thread_id, + agent_path: self.agent_path.clone(), + kind: self.kind, + }) + } +} + impl WebSearchItem { pub fn as_legacy_event(&self) -> EventMsg { EventMsg::WebSearchEnd(WebSearchEndEvent { @@ -234,6 +513,16 @@ impl HasLegacyEvent for ItemStartedEvent { } TurnItem::FileChange(item) => vec![item.as_legacy_begin_event(self.turn_id.clone())], TurnItem::McpToolCall(item) => vec![item.as_legacy_begin_event()], + TurnItem::CommandExecution(item) => { + vec![item.as_legacy_begin_event(self.turn_id.clone(), self.started_at_ms)] + } + TurnItem::DynamicToolCall(item) => { + vec![item.as_legacy_request_event(self.turn_id.clone(), self.started_at_ms)] + } + TurnItem::CollabAgentToolCall(item) => item + .as_legacy_begin_event(self.started_at_ms) + .into_iter() + .collect(), _ => Vec::new(), } } @@ -246,6 +535,21 @@ impl HasLegacyEvent for ItemCompletedEvent { .as_legacy_end_event(self.turn_id.clone()) .into_iter() .collect(), + TurnItem::CommandExecution(item) => item + .as_legacy_end_event(self.turn_id.clone(), self.completed_at_ms) + .into_iter() + .collect(), + TurnItem::DynamicToolCall(item) => item + .as_legacy_response_event(self.turn_id.clone(), self.completed_at_ms) + .into_iter() + .collect(), + TurnItem::CollabAgentToolCall(item) => item + .as_legacy_end_event(self.completed_at_ms) + .into_iter() + .collect(), + TurnItem::SubAgentActivity(item) => { + vec![item.as_legacy_event(self.completed_at_ms)] + } _ => self.item.as_legacy_events(show_raw_agent_reasoning), } } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index ca509a5a17..b1b845fe28 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -4309,6 +4309,10 @@ pub struct CollabResumeEndEvent { #[cfg(test)] mod tests { use super::*; + use crate::items::CommandExecutionItem; + use crate::items::CommandExecutionStatus; + use crate::items::DynamicToolCallItem; + use crate::items::DynamicToolCallStatus; use crate::items::FileChangeItem; use crate::items::ImageGenerationItem; use crate::items::McpToolCallItem; @@ -5290,6 +5294,139 @@ mod tests { } } + #[test] + fn command_execution_item_lifecycle_emits_legacy_exec_events() { + let cwd = PathUri::from_abs_path(&test_path_buf("/tmp").abs()); + let started = ItemStartedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".into(), + started_at_ms: 10, + item: TurnItem::CommandExecution(CommandExecutionItem { + id: "exec-1".into(), + process_id: Some("pid-1".into()), + command: vec!["echo".into(), "done".into()], + cwd: cwd.clone(), + parsed_cmd: vec![ParsedCommand::Unknown { + cmd: "echo done".into(), + }], + source: ExecCommandSource::Agent, + interaction_input: None, + status: CommandExecutionStatus::InProgress, + stdout: None, + stderr: None, + aggregated_output: None, + exit_code: None, + duration: None, + formatted_output: None, + }), + }; + let completed = ItemCompletedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".into(), + completed_at_ms: 20, + item: TurnItem::CommandExecution(CommandExecutionItem { + id: "exec-1".into(), + process_id: Some("pid-1".into()), + command: vec!["echo".into(), "done".into()], + cwd, + parsed_cmd: vec![ParsedCommand::Unknown { + cmd: "echo done".into(), + }], + source: ExecCommandSource::Agent, + interaction_input: None, + status: CommandExecutionStatus::Completed, + stdout: Some("done\n".into()), + stderr: Some(String::new()), + aggregated_output: Some("done\n".into()), + exit_code: Some(0), + duration: Some(Duration::from_millis(5)), + formatted_output: Some("done\n".into()), + }), + }; + + assert!(matches!( + started.as_legacy_events(/*show_raw_agent_reasoning*/ false).as_slice(), + [EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id, + turn_id, + started_at_ms: 10, + .. + })] if call_id == "exec-1" && turn_id == "turn-1" + )); + assert!(matches!( + completed + .as_legacy_events(/*show_raw_agent_reasoning*/ false) + .as_slice(), + [EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id, + turn_id, + completed_at_ms: 20, + aggregated_output, + .. + })] if call_id == "exec-1" && turn_id == "turn-1" && aggregated_output == "done\n" + )); + } + + #[test] + fn dynamic_tool_call_item_lifecycle_emits_legacy_dynamic_tool_events() { + let started = ItemStartedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".into(), + started_at_ms: 10, + item: TurnItem::DynamicToolCall(DynamicToolCallItem { + id: "dynamic-1".into(), + namespace: Some("apps".into()), + tool: "lookup".into(), + arguments: json!({"id": "123"}), + status: DynamicToolCallStatus::InProgress, + content_items: None, + success: None, + error: None, + duration: None, + }), + }; + let completed = ItemCompletedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".into(), + completed_at_ms: 20, + item: TurnItem::DynamicToolCall(DynamicToolCallItem { + id: "dynamic-1".into(), + namespace: Some("apps".into()), + tool: "lookup".into(), + arguments: json!({"id": "123"}), + status: DynamicToolCallStatus::Completed, + content_items: Some(vec![DynamicToolCallOutputContentItem::InputText { + text: "ok".into(), + }]), + success: Some(true), + error: None, + duration: Some(Duration::from_millis(5)), + }), + }; + + assert!(matches!( + started.as_legacy_events(/*show_raw_agent_reasoning*/ false).as_slice(), + [EventMsg::DynamicToolCallRequest(DynamicToolCallRequest { + call_id, + turn_id, + started_at_ms: 10, + .. + })] if call_id == "dynamic-1" && turn_id == "turn-1" + )); + assert!(matches!( + completed + .as_legacy_events(/*show_raw_agent_reasoning*/ false) + .as_slice(), + [EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { + call_id, + turn_id, + completed_at_ms: 20, + success: true, + .. + })] if call_id == "dynamic-1" && turn_id == "turn-1" + )); + } + #[test] fn item_started_event_requires_started_at_ms() { let mut value = serde_json::to_value(ItemStartedEvent { From 6afcf26d5d76c2f88b9096caa758931ffa673745 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 6 Jul 2026 20:49:53 -0700 Subject: [PATCH 15/79] core: route Responses API through system proxy (#31335) ## Why `features.respect_system_proxy` already routes authentication traffic through the OS proxy APIs, but it does not affect the primary inference path. That leaves users behind OS-managed proxies unable to send normal Responses API requests even after login succeeds. This PR is the first product-path migration onto the route-aware transport introduced in #31323 and refined in #31331. It also establishes the construction pattern for later migrations: the effective feature state is resolved once into a required HTTP client factory rather than represented by an optional per-call setting. The scope remains limited to the two HTTP Responses endpoints; WebSockets, model discovery, memories, realtime, and file uploads remain follow-up migrations. ## What changed - Replace the optional proxy marker with an explicit `OutboundProxyPolicy::{ReqwestDefault, RespectSystemProxy}` and a required `HttpClientFactory`. The policy has no default, and the lower-level route-aware reqwest builder is now private. - Have `Config` construct the factory from the effective feature state and require every `ModelClient` constructor to receive it. There is no optional setter or implicit `None` fallback. - Build HTTP clients for `/responses` and `/responses/compact` with `ClientRouteClass::Api`, using the complete destination URL so PAC rules can make URL-specific decisions. - Layer route-aware selection onto Codex's existing default headers, Cloudflare cookie store, custom CA handling, and sandbox no-proxy behavior. - Add an integration test that loads `features.respect_system_proxy` through `config.toml`, creates a real Codex session, and verifies that both a normal Responses turn and remote compaction reach an isolated local proxy. ## Review guide 1. `http-client/src/outbound_proxy.rs` defines the mandatory policy/factory boundary and keeps route resolution private. 2. `core/src/config/mod.rs`, `core/src/session/session.rs`, and `core/src/client.rs` show the compile-time invariant: effective config creates the factory, and `ModelClient` cannot be constructed without one. 3. `login/src/auth/default_client.rs` preserves existing default-client behavior while accepting the required factory for migrated routes. 4. `core/src/client.rs` switches only streaming Responses and remote compaction HTTP transports to the API route class. 5. `core/tests/suite/responses_api_system_proxy.rs` is the behavioral regression boundary. Its Linux subprocess deliberately sets the CGI marker that disables reqwest's implicit environment-proxy handling, so the test fails if session wiring or either Responses call site falls back to the default client. ## Test plan - `cargo check --tests -p codex-http-client -p codex-login -p codex-core` - `just test -p codex-login` - `just test -p codex-core respect_system_proxy_feature_resolves_enabled` - Existing `compact_uses_bearer_after_agent_identity_session_fallback` coverage passes with the new transport construction. - New Linux integration coverage: `responses_and_compact_use_enabled_system_proxy` - `just bazel-lock-check` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/31335). * #31342 * __->__ #31335 --- codex-rs/Cargo.lock | 1 + codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/client.rs | 32 +++++++++- codex-rs/core/src/client_tests.rs | 5 ++ codex-rs/core/src/config/config_tests.rs | 4 ++ codex-rs/core/src/config/mod.rs | 12 ++++ codex-rs/core/src/session/session.rs | 1 + codex-rs/core/src/session/tests.rs | 5 ++ codex-rs/core/tests/responses_headers.rs | 3 + codex-rs/core/tests/suite/client.rs | 2 + .../core/tests/suite/client_websockets.rs | 1 + codex-rs/http-client/src/lib.rs | 4 +- codex-rs/http-client/src/outbound_proxy.rs | 62 +++++++++++++++---- .../http-client/src/outbound_proxy_tests.rs | 3 +- codex-rs/login/src/auth/default_client.rs | 56 ++++++++++++----- codex-rs/login/src/outbound_proxy.rs | 11 ++-- codex-rs/memories/write/src/runtime.rs | 1 + 17 files changed, 166 insertions(+), 38 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 9d89f8eb1f..0d4d3c33bf 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2647,6 +2647,7 @@ dependencies = [ "codex-git-utils", "codex-home", "codex-hooks", + "codex-http-client", "codex-image-generation-extension", "codex-install-context", "codex-login", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 4435a2eb63..c617684f78 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -49,6 +49,7 @@ codex-shell-command = { workspace = true } codex-execpolicy = { workspace = true } codex-git-utils = { workspace = true } codex-hooks = { workspace = true } +codex-http-client = { workspace = true } codex-install-context = { workspace = true } codex-network-proxy = { workspace = true } codex-otel = { workspace = true } diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 716466b189..0bf33b3993 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -63,10 +63,13 @@ use codex_api::auth_header_telemetry; use codex_api::build_session_headers; use codex_api::create_text_param_for_request; use codex_api::response_create_client_metadata; +use codex_http_client::ClientRouteClass; +use codex_http_client::HttpClientFactory; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::RefreshTokenError; use codex_login::UnauthorizedRecovery; +use codex_login::default_client::build_default_reqwest_client_for_route; use codex_login::default_client::build_reqwest_client; use codex_otel::SessionTelemetry; use codex_otel::current_span_w3c_trace_context; @@ -250,6 +253,7 @@ pub struct ModelClient { state: Arc, agent_identity_policy: AgentIdentityAuthPolicy, prompt_cache_key_override: Option, + http_client_factory: HttpClientFactory, } /// A turn-scoped streaming session created from a [`ModelClient`]. @@ -402,7 +406,9 @@ impl ModelClient { /// Creates a new session-scoped `ModelClient`. /// /// All arguments are expected to be stable for the lifetime of a Codex session. Per-turn values - /// are passed to [`ModelClientSession::stream`] (and other turn-scoped methods) explicitly. + /// are passed to [`ModelClientSession::stream`] (and other turn-scoped methods) explicitly. The + /// HTTP client factory must come from the effective session configuration so every transport + /// observes the resolved outbound proxy policy. pub fn new( auth_manager: Option>, agent_identity_policy: AgentIdentityAuthPolicy, @@ -417,6 +423,7 @@ impl ModelClient { item_ids_enabled: bool, concurrent_reasoning_summaries_enabled: bool, attestation_provider: Option>, + http_client_factory: HttpClientFactory, ) -> Self { let model_provider = create_model_provider(provider_info, auth_manager); let codex_api_key_env_enabled = model_provider @@ -447,6 +454,7 @@ impl ModelClient { }), agent_identity_policy, prompt_cache_key_override: None, + http_client_factory, } } @@ -540,7 +548,8 @@ impl ModelClient { return Ok(Vec::new()); } let client_setup = self.current_client_setup().await?; - let transport = ReqwestTransport::new(build_reqwest_client()); + let transport = + self.build_responses_transport(&client_setup.api_provider, RESPONSES_COMPACT_ENDPOINT)?; let request_telemetry = Self::build_request_telemetry( session_telemetry, AuthRequestTelemetryContext::new( @@ -952,6 +961,21 @@ impl ModelClient { }) } + fn build_responses_transport( + &self, + api_provider: &ApiProvider, + endpoint: &str, + ) -> Result { + let request_url = api_provider.url_for_path(endpoint); + let client = build_default_reqwest_client_for_route( + &self.http_client_factory, + &request_url, + ClientRouteClass::Api, + ) + .map_err(std::io::Error::from)?; + Ok(ReqwestTransport::new(client)) + } + pub(crate) async fn prewarm_auth(&self) -> Result<()> { self.current_client_setup().await.map(|_| ()) } @@ -1386,7 +1410,9 @@ impl ModelClientSession { let mut pending_retry = PendingUnauthorizedRetry::default(); loop { let client_setup = self.client.current_client_setup().await?; - let transport = ReqwestTransport::new(build_reqwest_client()); + let transport = self + .client + .build_responses_transport(&client_setup.api_provider, RESPONSES_ENDPOINT)?; let request_auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), client_setup.api_auth.as_ref(), diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index c05f56b713..ddf9c4ebec 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -19,6 +19,8 @@ use codex_api::AgentIdentityTelemetry; use codex_api::ApiError; use codex_api::ResponseEvent; use codex_api::TransportError; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use codex_login::AuthCredentialsStoreMode; use codex_login::AuthKeyringBackendKind; use codex_login::AuthManager; @@ -105,6 +107,7 @@ fn test_model_client_with_thread_id( /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), ) } @@ -150,6 +153,7 @@ async fn compact_uses_bearer_after_agent_identity_session_fallback() -> anyhow:: /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), ); let prompt = Prompt { input: vec![ResponseItem::Message { @@ -827,6 +831,7 @@ fn model_client_with_counting_attestation( Some(Arc::new(CountingAttestationProvider { calls: attestation_calls.clone(), })), + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), ); (model_client, attestation_calls) } diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 6156b9b9ea..40ebc64a0b 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1590,6 +1590,10 @@ respect_system_proxy = true .await?; assert!(config.respect_system_proxy); + assert_eq!( + config.http_client_factory().outbound_proxy_policy(), + codex_http_client::OutboundProxyPolicy::RespectSystemProxy + ); Ok(()) } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 54fbb97f69..8c0a165564 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -70,6 +70,8 @@ use codex_features::MultiAgentV2ConfigToml; use codex_features::NetworkProxyConfigToml; use codex_features::TokenBudgetConfigToml; use codex_git_utils::resolve_root_git_project_for_trust; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use codex_install_context::InstallContext; use codex_login::AuthManagerConfig; use codex_login::AuthRouteConfig; @@ -1481,6 +1483,16 @@ impl Config { .then(AuthRouteConfig::respect_system_proxy) } + /// Creates the HTTP client factory resolved from the effective feature configuration. + pub fn http_client_factory(&self) -> HttpClientFactory { + let outbound_proxy_policy = if self.respect_system_proxy { + OutboundProxyPolicy::RespectSystemProxy + } else { + OutboundProxyPolicy::ReqwestDefault + }; + HttpClientFactory::new(outbound_proxy_policy) + } + /// Build the plugin-manager input from the effective config. pub fn plugins_config_input(&self) -> PluginsConfigInput { PluginsConfigInput::new( diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 78a7f02588..08abb46377 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -1115,6 +1115,7 @@ impl Session { .features .enabled(Feature::ConcurrentReasoningSummaries), attestation_provider, + config.http_client_factory(), ) .with_prompt_cache_key_override( crate::guardian::prompt_cache_key_override_for_review_session( diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 1ff469cf4c..5ebce9aa42 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -33,6 +33,8 @@ use codex_core_skills::HostSkillsSnapshot; use core_test_support::test_codex::local_selections; use codex_features::Feature; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use codex_login::CodexAuth; use codex_login::auth::AgentIdentityAuthPolicy; use codex_model_provider_info::ModelProviderInfo; @@ -492,6 +494,7 @@ fn test_model_client_session() -> crate::client::ModelClientSession { /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), ) .new_session() } @@ -5466,6 +5469,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { .features .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, + config.http_client_factory(), ), code_mode_service: crate::tools::code_mode::CodeModeService::new(Arc::new( codex_code_mode::InProcessCodeModeSessionProvider, @@ -7596,6 +7600,7 @@ where .features .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, + config.http_client_factory(), ), code_mode_service: crate::tools::code_mode::CodeModeService::new(Arc::new( codex_code_mode::InProcessCodeModeSessionProvider, diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 4c5f906160..b31b6d5682 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -133,6 +133,7 @@ async fn responses_stream_includes_subagent_header_on_review() { /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + config.http_client_factory(), ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); let mut client_session = client.new_session(); @@ -268,6 +269,7 @@ async fn responses_stream_includes_subagent_header_on_other() { /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + config.http_client_factory(), ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); let mut client_session = client.new_session(); @@ -389,6 +391,7 @@ async fn responses_respects_model_info_overrides_from_config() { /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + config.http_client_factory(), ); let responses_metadata = test_turn_responses_metadata(&client, thread_id, &session_source); let mut client_session = client.new_session(); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 92624bfcb3..4d298998af 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -1339,6 +1339,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth .features .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, + config.http_client_factory(), ); let responses_metadata = test_turn_responses_metadata(&client, thread_id); let mut client_session = client.new_session(); @@ -3007,6 +3008,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { /*item_ids_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + config.http_client_factory(), ); let responses_metadata = test_turn_responses_metadata(&client, thread_id); let mut client_session = client.new_session(); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index c56a8680ab..05a93807b2 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -2284,6 +2284,7 @@ async fn websocket_harness_with_provider_options( .features .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, + config.http_client_factory(), ); WebsocketTestHarness { diff --git a/codex-rs/http-client/src/lib.rs b/codex-rs/http-client/src/lib.rs index 5f90435452..07e579ecb3 100644 --- a/codex-rs/http-client/src/lib.rs +++ b/codex-rs/http-client/src/lib.rs @@ -25,9 +25,9 @@ pub use crate::error::StreamError; pub use crate::error::TransportError; pub use crate::outbound_proxy::BuildRouteAwareHttpClientError; pub use crate::outbound_proxy::ClientRouteClass; -pub use crate::outbound_proxy::OutboundProxyConfig; +pub use crate::outbound_proxy::HttpClientFactory; +pub use crate::outbound_proxy::OutboundProxyPolicy; pub use crate::outbound_proxy::RouteFailureClass; -pub use crate::outbound_proxy::build_reqwest_client_for_route; pub use crate::request::EncodedJsonBody; pub use crate::request::PreparedRequestBody; pub use crate::request::Request; diff --git a/codex-rs/http-client/src/outbound_proxy.rs b/codex-rs/http-client/src/outbound_proxy.rs index e643698a8c..5506f3d40b 100644 --- a/codex-rs/http-client/src/outbound_proxy.rs +++ b/codex-rs/http-client/src/outbound_proxy.rs @@ -84,14 +84,54 @@ impl fmt::Display for RouteFailureClass { } } -/// Marker enabling fixed system/PAC/WPAD, environment, then direct routing. -/// Resolved endpoints and platform details remain internal to the client builder. +/// Resolved outbound proxy behavior for HTTP clients. +/// +/// Callers must choose a policy explicitly so omitting feature resolution cannot silently select +/// legacy behavior. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct OutboundProxyConfig; +pub enum OutboundProxyPolicy { + /// Preserve reqwest's built-in proxy behavior. + ReqwestDefault, + /// Resolve system/PAC/WPAD settings, then environment settings, then direct routing. + RespectSystemProxy, +} -impl OutboundProxyConfig { - pub const fn respect_system_proxy() -> Self { - Self +/// Builds route-specific HTTP clients using one resolved outbound proxy policy. +/// +/// Construct this once from the effective application configuration and carry it with the +/// session or component that owns outbound requests. Individual request paths should supply only +/// their destination and route class rather than resolving feature state themselves. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpClientFactory { + outbound_proxy_policy: OutboundProxyPolicy, +} + +impl HttpClientFactory { + /// Creates a factory from the outbound proxy policy resolved by the application. + pub const fn new(outbound_proxy_policy: OutboundProxyPolicy) -> Self { + Self { + outbound_proxy_policy, + } + } + + /// Returns the outbound proxy policy used for clients built by this factory. + pub const fn outbound_proxy_policy(&self) -> OutboundProxyPolicy { + self.outbound_proxy_policy + } + + /// Builds a reqwest client for a concrete outbound route. + pub fn build_reqwest_client( + &self, + builder: reqwest::ClientBuilder, + request_url: &str, + route_class: ClientRouteClass, + ) -> Result { + build_reqwest_client_for_route( + builder, + request_url, + route_class, + self.outbound_proxy_policy, + ) } } @@ -120,18 +160,18 @@ impl From for io::Error { /// a route is selected are returned without trying another route. Ordered PAC candidates are /// currently collapsed to one route on both Windows and macOS; later proxy or `DIRECT` candidates /// are not retried after a connection failure. -pub fn build_reqwest_client_for_route( +fn build_reqwest_client_for_route( builder: reqwest::ClientBuilder, request_url: &str, route_class: ClientRouteClass, - config: Option<&OutboundProxyConfig>, + outbound_proxy_policy: OutboundProxyPolicy, ) -> Result { let builder = configure_proxy_for_route( &ProcessEnv, builder, request_url, route_class, - config, + outbound_proxy_policy, resolve_system_proxy, )?; build_reqwest_client_with_custom_ca(builder).map_err(Into::into) @@ -142,10 +182,10 @@ fn configure_proxy_for_route( builder: reqwest::ClientBuilder, request_url: &str, route_class: ClientRouteClass, - config: Option<&OutboundProxyConfig>, + outbound_proxy_policy: OutboundProxyPolicy, resolve_system_proxy: impl FnOnce(&str, &RequestOrigin) -> SystemProxyDecision, ) -> Result { - if config.is_none() { + if matches!(outbound_proxy_policy, OutboundProxyPolicy::ReqwestDefault) { return Ok(builder); } let origin = RequestOrigin::parse(request_url); diff --git a/codex-rs/http-client/src/outbound_proxy_tests.rs b/codex-rs/http-client/src/outbound_proxy_tests.rs index 60a1d56396..734d5483ec 100644 --- a/codex-rs/http-client/src/outbound_proxy_tests.rs +++ b/codex-rs/http-client/src/outbound_proxy_tests.rs @@ -79,13 +79,12 @@ async fn enabled_environment_proxy_routes_request_through_proxy() { values: HashMap::from([("HTTP_PROXY".to_string(), format!("http://{proxy_addr}"))]), }; let request_url = "http://enabled-proxy.test/proxy-check"; - let config = OutboundProxyConfig::respect_system_proxy(); let builder = configure_proxy_for_route( &env, reqwest::Client::builder().timeout(Duration::from_secs(2)), request_url, ClientRouteClass::Auth, - Some(&config), + OutboundProxyPolicy::RespectSystemProxy, |_, _| SystemProxyDecision::Unavailable { failure: RouteFailureClass::ProxyResolutionUnavailable, }, diff --git a/codex-rs/login/src/auth/default_client.rs b/codex-rs/login/src/auth/default_client.rs index 1146a89d96..089e78340b 100644 --- a/codex-rs/login/src/auth/default_client.rs +++ b/codex-rs/login/src/auth/default_client.rs @@ -8,8 +8,9 @@ use codex_http_client::BuildCustomCaTransportError; use codex_http_client::BuildRouteAwareHttpClientError; use codex_http_client::ClientRouteClass; use codex_http_client::HttpClient; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; pub use codex_http_client::RequestBuilder as CodexRequestBuilder; -use codex_http_client::build_reqwest_client_for_route; use codex_http_client::build_reqwest_client_with_custom_ca; use codex_http_client::with_chatgpt_cloudflare_cookie_store; use codex_terminal_detection::user_agent; @@ -235,6 +236,35 @@ pub fn try_build_reqwest_client() -> Result Result { + if matches!( + http_client_factory.outbound_proxy_policy(), + OutboundProxyPolicy::ReqwestDefault + ) { + return Ok(build_reqwest_client()); + } + if is_sandboxed() { + // Preserve the sandbox's existing no-proxy policy; sandboxed command egress is routed + // separately through network-proxy. + return Ok(build_reqwest_client()); + } + + http_client_factory.build_reqwest_client( + default_reqwest_client_builder(), + request_url, + route_class, + ) +} + fn default_reqwest_client_builder() -> reqwest::ClientBuilder { let mut builder = reqwest::Client::builder().default_headers(default_headers()); if is_sandboxed() { @@ -248,11 +278,10 @@ pub(crate) fn build_raw_auth_reqwest_client( endpoint: &str, auth_route_config: Option<&AuthRouteConfig>, ) -> Result { - build_reqwest_client_for_route( + auth_http_client_factory(auth_route_config).build_reqwest_client( reqwest::Client::builder(), endpoint, ClientRouteClass::Auth, - auth_route_config.map(AuthRouteConfig::route_config), ) } @@ -261,20 +290,10 @@ pub(crate) fn build_default_auth_reqwest_client( endpoint: &str, auth_route_config: Option<&AuthRouteConfig>, ) -> Result { - let Some(route_config) = auth_route_config.map(AuthRouteConfig::route_config) else { - return Ok(build_reqwest_client()); - }; - - if is_sandboxed() { - // Preserve the sandbox's existing no-proxy policy; sandboxed command egress is routed - // separately through network-proxy. - return Ok(build_reqwest_client()); - } - build_reqwest_client_for_route( - default_reqwest_client_builder(), + build_default_reqwest_client_for_route( + &auth_http_client_factory(auth_route_config), endpoint, ClientRouteClass::Auth, - Some(route_config), ) } @@ -286,6 +305,13 @@ pub(crate) fn create_default_auth_client( build_default_auth_reqwest_client(endpoint, auth_route_config).map(HttpClient::new) } +fn auth_http_client_factory(auth_route_config: Option<&AuthRouteConfig>) -> HttpClientFactory { + auth_route_config.map_or_else( + || HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + |config| config.http_client_factory().clone(), + ) +} + pub fn default_headers() -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert("originator", originator().header_value); diff --git a/codex-rs/login/src/outbound_proxy.rs b/codex-rs/login/src/outbound_proxy.rs index 66441e3637..79fcf76de1 100644 --- a/codex-rs/login/src/outbound_proxy.rs +++ b/codex-rs/login/src/outbound_proxy.rs @@ -1,4 +1,5 @@ -use codex_http_client::OutboundProxyConfig; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; /// Auth-layer adapter around client-owned proxy policy. /// @@ -6,17 +7,17 @@ use codex_http_client::OutboundProxyConfig; /// client layer. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuthRouteConfig { - route_config: OutboundProxyConfig, + http_client_factory: HttpClientFactory, } impl AuthRouteConfig { pub fn respect_system_proxy() -> Self { Self { - route_config: OutboundProxyConfig::respect_system_proxy(), + http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy), } } - pub(crate) fn route_config(&self) -> &OutboundProxyConfig { - &self.route_config + pub(crate) fn http_client_factory(&self) -> &HttpClientFactory { + &self.http_client_factory } } diff --git a/codex-rs/memories/write/src/runtime.rs b/codex-rs/memories/write/src/runtime.rs index ae0903cfdc..903a1743ff 100644 --- a/codex-rs/memories/write/src/runtime.rs +++ b/codex-rs/memories/write/src/runtime.rs @@ -263,6 +263,7 @@ impl MemoryStartupContext { config.features.enabled(Feature::ItemIds), /*concurrent_reasoning_summaries_enabled*/ false, /*attestation_provider*/ None, + config.http_client_factory(), ); let mut client_session = model_client.new_session(); From 6cf42cf16516ab3a125d853561ae3b8c77d6c13e Mon Sep 17 00:00:00 2001 From: stevenlee-oai Date: Tue, 7 Jul 2026 00:03:27 -0400 Subject: [PATCH 16/79] Serialize shared MCP OAuth credential stores (#30292) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Codex Thread 019edd6d-6f14-74e2-853c-345d1803d4a6](https://codex-thread-link.openai.chatgpt-team.site/thread/019edd6d-6f14-74e2-853c-345d1803d4a6) ## Stack Review and merge in order. Every layer is independently correct and documents its safe stopping point. 1. [openai/codex#30292](https://github.com/openai/codex/pull/30292) — aggregate File/Secrets store locking 2. [openai/codex#30293](https://github.com/openai/codex/pull/30293) — resolve and lifecycle-pin the exact OAuth store 3. [openai/codex#30416](https://github.com/openai/codex/pull/30416) — serialized authoritative refresh transaction 4. [openai/codex#30294](https://github.com/openai/codex/pull/30294) — Codex-owned transport refresh and one-shot 401 recovery 5. [openai/codex#30295](https://github.com/openai/codex/pull/30295) — login/logout transaction serialization 6. [openai/codex#30296](https://github.com/openai/codex/pull/30296) — diagnostic-only Auto store drift reporting **This PR is layer 1.** ## Why MCP OAuth credentials stored in File or Secrets share one aggregate map. Concurrent read-modify-write operations for different MCP servers can both read the same snapshot and let the later write discard the earlier update. That is a correctness problem independent of refresh-token rotation. ## What this PR does - Adds a bounded cross-process lock around aggregate File and Secrets loads, saves, and deletes. - Distinguishes aggregate-lock failures from Secrets backend unavailability, so Auto can fall back only for the latter and cannot bypass serialization by reading or writing File. - Keeps Direct keyring operations outside this lock because they are already per credential. - Releases the Secrets aggregate lock before legacy File cleanup so cross-store cleanup cannot create nested aggregate-lock ordering. - Tests actual contention by waiting for an observed `WouldBlock`, rather than assuming a sleeping worker reached the lock. - Tests load and save with only the Secrets lock path broken while fallback File remains readable and writable. ## Decisions and non-goals - This lock protects aggregate-store read-modify-write integrity only. It does not choose a credential authority or serialize an OAuth refresh transaction. - The lock is scoped to the active `CODEX_HOME`, matching the aggregate files it protects. - Lock waits are bounded, and coordination failures are surfaced rather than treated as evidence that Secrets is unavailable. ## Safe stopping point This PR can merge alone. It prevents lost updates and partial aggregate reads. Auto can still resolve again during a client lifecycle until layer 2, and concurrent refreshes remain possible until layer 3. ## Validation - `just test -p codex-rmcp-client` (96 passed; expected environment skips) - Focused aggregate File/Secrets lock contention and Auto fallback tests --- codex-rs/rmcp-client/src/oauth.rs | 123 +++-- codex-rs/rmcp-client/src/oauth/store_lock.rs | 181 +++++++ .../rmcp-client/src/oauth/test_support.rs | 46 ++ .../src/oauth/tests/store_lock_tests.rs | 480 ++++++++++++++++++ 4 files changed, 775 insertions(+), 55 deletions(-) create mode 100644 codex-rs/rmcp-client/src/oauth/store_lock.rs create mode 100644 codex-rs/rmcp-client/src/oauth/test_support.rs create mode 100644 codex-rs/rmcp-client/src/oauth/tests/store_lock_tests.rs diff --git a/codex-rs/rmcp-client/src/oauth.rs b/codex-rs/rmcp-client/src/oauth.rs index d0005d20a6..46e6279a16 100644 --- a/codex-rs/rmcp-client/src/oauth.rs +++ b/codex-rs/rmcp-client/src/oauth.rs @@ -16,6 +16,12 @@ //! //! If the keyring is not available or fails, we fall back to CODEX_HOME/.credentials.json which is consistent with other coding CLI agents. +mod store_lock; + +#[cfg(test)] +#[path = "oauth/test_support.rs"] +mod test_support; + use anyhow::Context; use anyhow::Error; use anyhow::Result; @@ -49,6 +55,10 @@ use std::time::SystemTime; use std::time::UNIX_EPOCH; use tracing::warn; +use self::store_lock::OAuthStore; +use self::store_lock::OAuthStoreLock; +use self::store_lock::OAuthStoreLockFailure; + use codex_keyring_store::DefaultKeyringStore; use codex_keyring_store::KeyringStore; use rmcp::transport::auth::AuthorizationManager; @@ -173,6 +183,11 @@ fn load_oauth_tokens_from_keyring_with_fallback_to_file Ok(Some(tokens)), Ok(None) => load_oauth_tokens_from_file(server_name, url), + // A store lock failure means the configured aggregate authority could be changing, or + // that coordination itself is unavailable. It is not evidence that the keyring backend + // is unavailable, so consulting File here could replay credentials hidden behind a + // newer Secrets entry. This is the load-side counterpart of the save guard below. + Err(error) if error.downcast_ref::().is_some() => Err(error), Err(error) => { warn!("failed to read OAuth tokens from keyring: {error}"); load_oauth_tokens_from_file(server_name, url) @@ -220,6 +235,7 @@ fn load_oauth_tokens_from_secrets_keyring( server_name: &str, url: &str, ) -> Result> { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?; let codex_home = find_codex_home()?; let manager = SecretsManager::new_with_keyring_store_and_namespace( codex_home.to_path_buf(), @@ -308,12 +324,39 @@ fn save_oauth_tokens_to_direct_keyring( } } +/// Saves one credential while holding the Secrets aggregate-store lock across the mutation. +/// +/// The Secrets lock is released before fallback File cleanup to preserve aggregate-lock ordering. fn save_oauth_tokens_to_secrets_keyring( keyring_store: &K, server_name: &str, tokens: &StoredOAuthTokens, ) -> Result<()> { let serialized = serde_json::to_string(tokens).context("failed to serialize OAuth tokens")?; + { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?; + save_oauth_tokens_to_secrets_keyring_with_lock_held( + keyring_store, + server_name, + tokens, + &serialized, + )?; + } + + let key = compute_store_key(server_name, &tokens.url)?; + if let Err(error) = delete_oauth_tokens_from_file(&key) { + warn!("failed to remove OAuth tokens from fallback storage: {error:?}"); + } + Ok(()) +} + +/// Writes one credential to Secrets. The caller must hold the Secrets aggregate-store lock. +fn save_oauth_tokens_to_secrets_keyring_with_lock_held( + keyring_store: &K, + server_name: &str, + tokens: &StoredOAuthTokens, + serialized: &str, +) -> Result<()> { let codex_home = find_codex_home()?; let manager = SecretsManager::new_with_keyring_store_and_namespace( codex_home.to_path_buf(), @@ -323,14 +366,8 @@ fn save_oauth_tokens_to_secrets_keyring( ); let secret_name = compute_secret_name(server_name, &tokens.url)?; manager - .set(&SecretScope::Global, &secret_name, &serialized) - .context("failed to write OAuth tokens to encrypted storage")?; - - let key = compute_store_key(server_name, &tokens.url)?; - if let Err(error) = delete_oauth_tokens_from_file(&key) { - warn!("failed to remove OAuth tokens from fallback storage: {error:?}"); - } - Ok(()) + .set(&SecretScope::Global, &secret_name, serialized) + .context("failed to write OAuth tokens to encrypted storage") } fn save_oauth_tokens_with_keyring_with_fallback_to_file( @@ -341,6 +378,10 @@ fn save_oauth_tokens_with_keyring_with_fallback_to_file Result<()> { match save_oauth_tokens_with_keyring(keyring_store, keyring_backend_kind, server_name, tokens) { Ok(()) => Ok(()), + // As on load, a store lock failure is a coordination failure rather than evidence that + // the keyring backend is unavailable. Falling back could leave a newer File token hidden + // behind a stale Secrets entry. + Err(error) if error.downcast_ref::().is_some() => Err(error), Err(error) => { let message = error.to_string(); warn!("falling back to file storage for OAuth tokens: {message}"); @@ -430,6 +471,7 @@ fn delete_oauth_tokens_from_secrets_keyring( server_name: &str, url: &str, ) -> Result { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?; let codex_home = find_codex_home()?; let manager = SecretsManager::new_with_keyring_store_and_namespace( codex_home.to_path_buf(), @@ -592,7 +634,8 @@ struct FallbackTokenEntry { } fn load_oauth_tokens_from_file(server_name: &str, url: &str) -> Result> { - let Some(store) = read_fallback_file()? else { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?; + let Some(store) = read_fallback_file_unlocked()? else { return Ok(None); }; @@ -634,9 +677,17 @@ fn load_oauth_tokens_from_file(server_name: &str, url: &str) -> Result Result<()> { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?; + save_oauth_tokens_to_file_with_lock_held(tokens) +} + +/// Updates the fallback File. The caller must hold the File aggregate-store lock. +fn save_oauth_tokens_to_file_with_lock_held(tokens: &StoredOAuthTokens) -> Result<()> { let key = compute_store_key(&tokens.server_name, &tokens.url)?; - let mut store = read_fallback_file()?.unwrap_or_default(); + let mut store = read_fallback_file_unlocked()?.unwrap_or_default(); let token_response = &tokens.token_response.0; let expires_at = tokens @@ -664,7 +715,8 @@ fn save_oauth_tokens_to_file(tokens: &StoredOAuthTokens) -> Result<()> { } fn delete_oauth_tokens_from_file(key: &str) -> Result { - let mut store = match read_fallback_file()? { + let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?; + let mut store = match read_fallback_file_unlocked()? { Some(store) => store, None => return Ok(false), }; @@ -750,7 +802,7 @@ fn fallback_file_path() -> Result { Ok(find_codex_home()?.join(FALLBACK_FILENAME).to_path_buf()) } -fn read_fallback_file() -> Result> { +fn read_fallback_file_unlocked() -> Result> { let path = fallback_file_path()?; let contents = match fs::read_to_string(&path) { Ok(contents) => contents, @@ -814,52 +866,13 @@ fn sha_256_prefix(value: &Value) -> Result { mod tests { use super::*; use anyhow::Result; + use codex_keyring_store::tests::MockKeyringStore; use codex_secrets::compute_keyring_account; use keyring::Error as KeyringError; use pretty_assertions::assert_eq; use std::sync::Arc; - use std::sync::Mutex; - use std::sync::MutexGuard; - use std::sync::OnceLock; - use std::sync::PoisonError; - use tempfile::tempdir; - use codex_keyring_store::tests::MockKeyringStore; - - struct TempCodexHome { - _guard: MutexGuard<'static, ()>, - _dir: tempfile::TempDir, - } - - impl TempCodexHome { - fn new() -> Self { - static LOCK: OnceLock> = OnceLock::new(); - let guard = LOCK - .get_or_init(Mutex::default) - .lock() - .unwrap_or_else(PoisonError::into_inner); - let dir = tempdir().expect("create CODEX_HOME temp dir"); - unsafe { - std::env::set_var("CODEX_HOME", dir.path()); - } - Self { - _guard: guard, - _dir: dir, - } - } - - fn path(&self) -> &std::path::Path { - self._dir.path() - } - } - - impl Drop for TempCodexHome { - fn drop(&mut self) { - unsafe { - std::env::remove_var("CODEX_HOME"); - } - } - } + use super::test_support::TempCodexHome; #[test] fn load_oauth_tokens_reads_from_keyring_when_available() -> Result<()> { @@ -964,7 +977,7 @@ mod tests { let fallback_path = super::fallback_file_path()?; assert!(fallback_path.exists(), "fallback file should be created"); - let saved = super::read_fallback_file()?.expect("fallback file should load"); + let saved = super::read_fallback_file_unlocked()?.expect("fallback file should load"); let key = super::compute_store_key(&tokens.server_name, &tokens.url)?; let entry = saved.get(&key).expect("entry for key"); assert_eq!(entry.server_name, tokens.server_name); @@ -1076,7 +1089,7 @@ mod tests { &tokens, )?; - let saved = super::read_fallback_file()?.expect("fallback file should load"); + let saved = super::read_fallback_file_unlocked()?.expect("fallback file should load"); let key = super::compute_store_key(&tokens.server_name, &tokens.url)?; assert!(saved.contains_key(&key)); Ok(()) diff --git a/codex-rs/rmcp-client/src/oauth/store_lock.rs b/codex-rs/rmcp-client/src/oauth/store_lock.rs new file mode 100644 index 0000000000..5f83ebb8a6 --- /dev/null +++ b/codex-rs/rmcp-client/src/oauth/store_lock.rs @@ -0,0 +1,181 @@ +//! Cross-process serialization for MCP OAuth stores shared by multiple credentials. +//! +//! File and Secrets each keep credentials for multiple MCP servers in one aggregate document. +//! Their lock therefore protects the complete read-modify-write operation. Direct keyring entries +//! are already stored independently per credential and do not use this lock. + +use std::fs; +use std::fs::File; +use std::fs::OpenOptions; +use std::io; +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; +use std::time::Instant; + +use anyhow::Result; +use codex_utils_home_dir::find_codex_home; + +const OAUTH_LOCK_DIR: &str = "mcp-oauth-locks"; +const STORE_LOCK_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(60); +const STORE_LOCK_RETRY_SLEEP: Duration = Duration::from_millis(50); +// Tests listen for this event so they prove a contender reached the real WouldBlock branch. +const LOCK_CONTENTION_EVENT_TARGET: &str = "codex_rmcp_client::oauth::store_lock::contention"; + +#[derive(Clone, Copy, Debug)] +pub(super) enum OAuthStore { + File, + Secrets, +} + +impl OAuthStore { + fn lock_filename(self) -> &'static str { + match self { + Self::File => "file-store.lock", + Self::Secrets => "secrets-store.lock", + } + } +} + +impl std::fmt::Display for OAuthStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::File => f.write_str("fallback file"), + Self::Secrets => f.write_str("encrypted secrets"), + } + } +} + +/// Serializes one complete operation on an aggregate OAuth credential store. +pub(super) struct OAuthStoreLock { + _file: File, +} + +impl OAuthStoreLock { + pub(super) fn acquire(store: OAuthStore) -> Result { + // This lock intentionally follows the existing local File/Secrets credential-store + // authority. Those stores are CODEX_HOME-backed today: if CODEX_HOME is unset they use + // the default home (`~/.codex`), and if an embedder has no local home/filesystem authority + // those stores already cannot operate. A future provider-backed credential store should + // provide its own matching lock authority instead of using this local path. + let codex_home = find_codex_home() + .map_err(|source| OAuthStoreLockFailure::CodexHome { store, source })?; + Self::acquire_in(&codex_home, store, STORE_LOCK_ACQUIRE_TIMEOUT) + } + + pub(super) fn acquire_in( + codex_home: &Path, + store: OAuthStore, + acquire_timeout: Duration, + ) -> Result { + let path = oauth_store_lock_path(codex_home, store); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|source| OAuthStoreLockFailure::CreateDir { + store, + path: parent.to_path_buf(), + source, + })?; + } + + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path) + .map_err(|source| OAuthStoreLockFailure::Open { + store, + path: path.clone(), + source, + })?; + let started = Instant::now(); + let mut reported_contention = false; + + loop { + match file.try_lock() { + Ok(()) => return Ok(Self { _file: file }), + Err(std::fs::TryLockError::WouldBlock) if started.elapsed() >= acquire_timeout => { + return Err(OAuthStoreLockFailure::Timeout { + store, + path, + acquire_timeout, + } + .into()); + } + Err(std::fs::TryLockError::WouldBlock) => { + if !reported_contention { + tracing::debug!( + target: LOCK_CONTENTION_EVENT_TARGET, + store = %store, + lock_path = %path.display(), + "waiting for another process to finish updating MCP OAuth store state" + ); + reported_contention = true; + } + std::thread::sleep(STORE_LOCK_RETRY_SLEEP.min(acquire_timeout)); + } + Err(error) => { + return Err(OAuthStoreLockFailure::Lock { + store, + path, + source: io::Error::from(error), + } + .into()); + } + } + } + } +} + +/// Marks aggregate-store coordination failures in an [`anyhow::Error`] chain. +/// +/// Auto may fall back when the configured keyring backend is unavailable, but it must surface a +/// lock failure. Falling back while another process owns the aggregate-store lock could leave the +/// newer credential in File while a stale Secrets entry remains preferred. +#[derive(Debug, thiserror::Error)] +pub(super) enum OAuthStoreLockFailure { + #[error("failed to resolve CODEX_HOME for MCP OAuth {store} aggregate-store lock")] + CodexHome { + store: OAuthStore, + #[source] + source: io::Error, + }, + #[error("failed to create MCP OAuth {store} aggregate-store lock directory {}", path.display())] + CreateDir { + store: OAuthStore, + path: PathBuf, + #[source] + source: io::Error, + }, + #[error("failed to open MCP OAuth {store} aggregate-store lock {}", path.display())] + Open { + store: OAuthStore, + path: PathBuf, + #[source] + source: io::Error, + }, + #[error( + "timed out after {acquire_timeout:?} waiting for MCP OAuth {store} aggregate-store lock {}", + path.display() + )] + Timeout { + store: OAuthStore, + path: PathBuf, + acquire_timeout: Duration, + }, + #[error("failed to lock MCP OAuth {store} aggregate-store lock {}", path.display())] + Lock { + store: OAuthStore, + path: PathBuf, + #[source] + source: io::Error, + }, +} + +fn oauth_store_lock_path(codex_home: &Path, store: OAuthStore) -> PathBuf { + codex_home.join(OAUTH_LOCK_DIR).join(store.lock_filename()) +} + +#[cfg(test)] +#[path = "tests/store_lock_tests.rs"] +mod tests; diff --git a/codex-rs/rmcp-client/src/oauth/test_support.rs b/codex-rs/rmcp-client/src/oauth/test_support.rs new file mode 100644 index 0000000000..6ca2f510f5 --- /dev/null +++ b/codex-rs/rmcp-client/src/oauth/test_support.rs @@ -0,0 +1,46 @@ +use std::path::Path; +use std::sync::Mutex; +use std::sync::MutexGuard; +use std::sync::OnceLock; +use std::sync::PoisonError; + +use tempfile::tempdir; + +/// Serializes tests that mutate process-wide CODEX_HOME. +/// +/// Keep OAuth tests on this one guard instead of defining per-module helpers; otherwise +/// concurrently running test modules can point File/Secrets storage at different homes. +pub(super) struct TempCodexHome { + _guard: MutexGuard<'static, ()>, + _dir: tempfile::TempDir, +} + +impl TempCodexHome { + pub(super) fn new() -> Self { + static LOCK: OnceLock> = OnceLock::new(); + let guard = LOCK + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(PoisonError::into_inner); + let dir = tempdir().expect("create CODEX_HOME temp dir"); + unsafe { + std::env::set_var("CODEX_HOME", dir.path()); + } + Self { + _guard: guard, + _dir: dir, + } + } + + pub(super) fn path(&self) -> &Path { + self._dir.path() + } +} + +impl Drop for TempCodexHome { + fn drop(&mut self) { + unsafe { + std::env::remove_var("CODEX_HOME"); + } + } +} diff --git a/codex-rs/rmcp-client/src/oauth/tests/store_lock_tests.rs b/codex-rs/rmcp-client/src/oauth/tests/store_lock_tests.rs new file mode 100644 index 0000000000..aafc362c20 --- /dev/null +++ b/codex-rs/rmcp-client/src/oauth/tests/store_lock_tests.rs @@ -0,0 +1,480 @@ +use std::process::Command; +use std::sync::mpsc; +use std::time::Duration; +use std::time::Instant; + +use anyhow::Context; +use anyhow::Result; +use codex_config::types::AuthKeyringBackendKind; +use codex_keyring_store::tests::MockKeyringStore; +use oauth2::AccessToken; +use oauth2::RefreshToken; +use oauth2::Scope; +use oauth2::TokenResponse; +use oauth2::basic::BasicTokenType; +use pretty_assertions::assert_eq; +use rmcp::transport::auth::OAuthTokenResponse; +use rmcp::transport::auth::VendorExtraTokenFields; +use tracing::Event; +use tracing::Id; +use tracing::Metadata; +use tracing::Subscriber; +use tracing::span::Attributes; +use tracing::span::Record; +use tracing::subscriber::Interest; + +use super::OAuthStore; +use super::OAuthStoreLock; +use super::OAuthStoreLockFailure; +use crate::oauth::StoredOAuthTokens; +use crate::oauth::WrappedOAuthTokenResponse; +use crate::oauth::fallback_file_path; +use crate::oauth::load_oauth_tokens_from_file; +use crate::oauth::load_oauth_tokens_from_keyring; +use crate::oauth::load_oauth_tokens_from_keyring_with_fallback_to_file; +use crate::oauth::save_oauth_tokens_to_file; +use crate::oauth::save_oauth_tokens_to_file_with_lock_held; +use crate::oauth::save_oauth_tokens_to_secrets_keyring_with_lock_held; +use crate::oauth::save_oauth_tokens_with_keyring; +use crate::oauth::save_oauth_tokens_with_keyring_with_fallback_to_file; +use crate::oauth::test_support::TempCodexHome; + +const STORE_LOCK_CONTENTION_EVENT_TARGET: &str = "codex_rmcp_client::oauth::store_lock::contention"; + +fn assert_tokens_match_without_expiry(actual: &StoredOAuthTokens, expected: &StoredOAuthTokens) { + assert_eq!(actual.server_name, expected.server_name); + assert_eq!(actual.url, expected.url); + assert_eq!(actual.client_id, expected.client_id); + assert_eq!(actual.expires_at, expected.expires_at); + assert_token_response_match_without_expiry(&actual.token_response, &expected.token_response); +} + +fn assert_token_response_match_without_expiry( + actual: &WrappedOAuthTokenResponse, + expected: &WrappedOAuthTokenResponse, +) { + let actual_response = &actual.0; + let expected_response = &expected.0; + + assert_eq!( + actual_response.access_token().secret(), + expected_response.access_token().secret() + ); + assert_eq!(actual_response.token_type(), expected_response.token_type()); + assert_eq!( + actual_response.refresh_token().map(RefreshToken::secret), + expected_response.refresh_token().map(RefreshToken::secret), + ); + assert_eq!(actual_response.scopes(), expected_response.scopes()); + assert_eq!( + actual_response.extra_fields().0, + expected_response.extra_fields().0 + ); + assert_eq!( + actual_response.expires_in().is_some(), + expected_response.expires_in().is_some() + ); +} + +fn sample_tokens() -> StoredOAuthTokens { + let mut response = OAuthTokenResponse::new( + AccessToken::new("access-token".to_string()), + BasicTokenType::Bearer, + VendorExtraTokenFields::default(), + ); + response.set_refresh_token(Some(RefreshToken::new("refresh-token".to_string()))); + response.set_scopes(Some(vec![ + Scope::new("scope-a".to_string()), + Scope::new("scope-b".to_string()), + ])); + let expires_in = Duration::from_secs(3600); + response.set_expires_in(Some(&expires_in)); + let expires_at = crate::oauth::compute_expires_at_millis(&response); + + StoredOAuthTokens { + server_name: "test-server".to_string(), + url: "https://example.test".to_string(), + client_id: "client-id".to_string(), + token_response: WrappedOAuthTokenResponse(response), + expires_at, + } +} + +const LOCK_HOLDER_CHILD_TEST: &str = + "oauth::store_lock::tests::store_lock_is_released_when_holder_process_exits_child"; +const LOCK_HOLDER_READY_PATH_ENV: &str = "CODEX_OAUTH_STORE_LOCK_CHILD_READY_PATH"; + +#[test] +fn store_lock_is_released_when_holder_process_exits() -> Result<()> { + let env = TempCodexHome::new(); + let ready_file = env.path().join("lock-holder-ready"); + let mut child = Command::new(std::env::current_exe()?) + .arg("--exact") + .arg(LOCK_HOLDER_CHILD_TEST) + .arg("--ignored") + .env("CODEX_HOME", env.path()) + .env(LOCK_HOLDER_READY_PATH_ENV, &ready_file) + .spawn() + .context("spawn OAuth store lock holder test process")?; + + let test_result = (|| -> Result<()> { + let started = Instant::now(); + while !ready_file.exists() { + if started.elapsed() > Duration::from_secs(/*secs*/ 5) { + anyhow::bail!("timed out waiting for child process to acquire OAuth store lock"); + } + std::thread::sleep(Duration::from_millis(/*millis*/ 20)); + } + + let error = match OAuthStoreLock::acquire_in( + env.path(), + OAuthStore::File, + Duration::from_millis(/*millis*/ 100), + ) { + Ok(_) => { + anyhow::bail!("live holder process should keep the OAuth store lock unavailable") + } + Err(error) => error, + }; + assert!(matches!( + error.downcast_ref::(), + Some(OAuthStoreLockFailure::Timeout { .. }) + )); + + child + .kill() + .context("kill OAuth store lock holder process")?; + let status = child + .wait() + .context("wait for killed OAuth store lock holder process")?; + assert!(!status.success()); + let _lock = OAuthStoreLock::acquire_in( + env.path(), + OAuthStore::File, + Duration::from_secs(/*secs*/ 1), + )?; + Ok(()) + })(); + + if let Ok(None) = child.try_wait() { + let _ = child.kill(); + let _ = child.wait(); + } + + test_result +} + +#[test] +#[ignore = "child process for store_lock_is_released_when_holder_process_exits"] +fn store_lock_is_released_when_holder_process_exits_child() -> Result<()> { + let ready_file = match std::env::var_os(LOCK_HOLDER_READY_PATH_ENV) { + Some(path) => std::path::PathBuf::from(path), + None => return Ok(()), + }; + let _lock = OAuthStoreLock::acquire(OAuthStore::File)?; + std::fs::write(ready_file, b"ready")?; + loop { + std::thread::sleep(Duration::from_secs(/*secs*/ 60)); + } +} + +#[test] +fn auto_save_secrets_lock_failure_does_not_fall_back_to_file() -> Result<()> { + let env = TempCodexHome::new(); + let lock_dir = env.path().join("mcp-oauth-locks"); + std::fs::create_dir_all(&lock_dir)?; + // Break only the Secrets lock path. The distinct File lock remains usable, so Auto would + // successfully write fallback credentials if it mistook coordination failure for backend + // unavailability. + std::fs::create_dir(lock_dir.join("secrets-store.lock"))?; + let keyring_store = MockKeyringStore::default(); + let tokens = sample_tokens(); + + let error = save_oauth_tokens_with_keyring_with_fallback_to_file( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &tokens.server_name, + &tokens, + ) + .expect_err("aggregate-store lock failure must abort Auto persistence"); + + assert!(error.downcast_ref::().is_some()); + assert!(!fallback_file_path()?.exists()); + save_oauth_tokens_to_file(&tokens)?; + let loaded = load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)? + .expect("fallback File should remain independently writable"); + assert_tokens_match_without_expiry(&loaded, &tokens); + Ok(()) +} + +#[test] +fn auto_load_secrets_lock_failure_does_not_fall_back_to_file() -> Result<()> { + let env = TempCodexHome::new(); + let keyring_store = MockKeyringStore::default(); + let tokens = sample_tokens(); + save_oauth_tokens_to_file(&tokens)?; + + let lock_dir = env.path().join("mcp-oauth-locks"); + std::fs::create_dir(lock_dir.join("secrets-store.lock"))?; + let error = load_oauth_tokens_from_keyring_with_fallback_to_file( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &tokens.server_name, + &tokens.url, + ) + .expect_err("aggregate-store lock failure must abort Auto resolution"); + + assert!(error.downcast_ref::().is_some()); + let loaded = load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)? + .expect("fallback File should remain independently readable"); + assert_tokens_match_without_expiry(&loaded, &tokens); + Ok(()) +} + +struct LockContentionSubscriber { + contended_tx: mpsc::Sender<()>, +} + +impl Subscriber for LockContentionSubscriber { + fn enabled(&self, metadata: &Metadata<'_>) -> bool { + metadata.target() == STORE_LOCK_CONTENTION_EVENT_TARGET + } + + fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest { + if self.enabled(metadata) { + Interest::always() + } else { + Interest::never() + } + } + + fn max_level_hint(&self) -> Option { + Some(tracing::level_filters::LevelFilter::DEBUG) + } + + fn new_span(&self, _span: &Attributes<'_>) -> Id { + Id::from_u64(/*u*/ 1) + } + + fn record(&self, _span: &Id, _values: &Record<'_>) {} + + fn record_follows_from(&self, _span: &Id, _follows_from: &Id) {} + + fn event(&self, event: &Event<'_>) { + if self.enabled(event.metadata()) { + self.contended_tx + .send(()) + .expect("signal actual OAuth store lock contention"); + } + } + + fn enter(&self, _span: &Id) {} + + fn exit(&self, _span: &Id) {} +} + +fn complete_after_store_lock_contention( + codex_home: &std::path::Path, + store: OAuthStore, + operation: impl FnOnce() -> Result + Send + 'static, +) -> Result +where + T: Send + 'static, +{ + let held_lock = + OAuthStoreLock::acquire_in(codex_home, store, Duration::from_millis(/*millis*/ 100))?; + let (contended_tx, contended_rx) = mpsc::channel(); + let (result_tx, result_rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + tracing::subscriber::with_default(LockContentionSubscriber { contended_tx }, || { + result_tx + .send(operation()) + .expect("send contending OAuth store operation result"); + }); + }); + + // This event is emitted only after `try_lock()` returns WouldBlock, so the test fails if the + // operation stops acquiring the aggregate-store lock. + contended_rx.recv_timeout(Duration::from_secs(/*secs*/ 1))?; + drop(held_lock); + let result = result_rx.recv_timeout(Duration::from_secs(/*secs*/ 10))??; + worker + .join() + .expect("contending OAuth store worker should finish"); + Ok(result) +} + +#[test] +fn file_store_lock_preserves_updates_for_different_servers() -> Result<()> { + let env = TempCodexHome::new(); + let first = sample_tokens(); + let mut second = sample_tokens(); + second.server_name = "second-server".to_string(); + second.url = "https://second.example.test".to_string(); + + let held_lock = OAuthStoreLock::acquire_in( + env.path(), + OAuthStore::File, + Duration::from_millis(/*millis*/ 100), + )?; + let (contended_tx, contended_rx) = mpsc::channel(); + let (result_tx, result_rx) = mpsc::channel(); + let second_for_writer = second.clone(); + let writer = std::thread::spawn(move || { + tracing::subscriber::with_default(LockContentionSubscriber { contended_tx }, || { + result_tx + .send(save_oauth_tokens_to_file(&second_for_writer)) + .expect("send writer result"); + }); + }); + + contended_rx.recv_timeout(Duration::from_secs(/*secs*/ 1))?; + save_oauth_tokens_to_file_with_lock_held(&first)?; + drop(held_lock); + result_rx.recv_timeout(Duration::from_secs(/*secs*/ 10))??; + writer.join().expect("file store writer should finish"); + + let loaded_first = load_oauth_tokens_from_file(&first.server_name, &first.url)? + .expect("first server tokens should remain stored"); + let loaded_second = load_oauth_tokens_from_file(&second.server_name, &second.url)? + .expect("second server tokens should be stored"); + assert_tokens_match_without_expiry(&loaded_first, &first); + assert_tokens_match_without_expiry(&loaded_second, &second); + Ok(()) +} + +#[test] +fn file_store_load_and_delete_observe_aggregate_lock() -> Result<()> { + let env = TempCodexHome::new(); + let tokens = sample_tokens(); + save_oauth_tokens_to_file(&tokens)?; + + let server_name = tokens.server_name.clone(); + let url = tokens.url.clone(); + let loaded = complete_after_store_lock_contention(env.path(), OAuthStore::File, move || { + load_oauth_tokens_from_file(&server_name, &url) + })? + .expect("file credentials should remain readable after contention"); + assert_tokens_match_without_expiry(&loaded, &tokens); + + let key = crate::oauth::compute_store_key(&tokens.server_name, &tokens.url)?; + let removed = complete_after_store_lock_contention(env.path(), OAuthStore::File, move || { + crate::oauth::delete_oauth_tokens_from_file(&key) + })?; + assert!(removed); + assert!(load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)?.is_none()); + Ok(()) +} + +#[test] +fn secrets_store_lock_preserves_updates_for_different_servers() -> Result<()> { + let env = TempCodexHome::new(); + let keyring_store = MockKeyringStore::default(); + let first = sample_tokens(); + let mut second = sample_tokens(); + second.server_name = "second-server".to_string(); + second.url = "https://second.example.test".to_string(); + + let held_lock = OAuthStoreLock::acquire_in( + env.path(), + OAuthStore::Secrets, + Duration::from_millis(/*millis*/ 100), + )?; + let (contended_tx, contended_rx) = mpsc::channel(); + let (result_tx, result_rx) = mpsc::channel(); + let store_for_writer = keyring_store.clone(); + let second_for_writer = second.clone(); + let writer = std::thread::spawn(move || { + tracing::subscriber::with_default(LockContentionSubscriber { contended_tx }, || { + result_tx + .send(save_oauth_tokens_with_keyring( + &store_for_writer, + AuthKeyringBackendKind::Secrets, + &second_for_writer.server_name, + &second_for_writer, + )) + .expect("send writer result"); + }); + }); + + contended_rx.recv_timeout(Duration::from_secs(/*secs*/ 1))?; + let first_serialized = serde_json::to_string(&first)?; + save_oauth_tokens_to_secrets_keyring_with_lock_held( + &keyring_store, + &first.server_name, + &first, + &first_serialized, + )?; + drop(held_lock); + result_rx.recv_timeout(Duration::from_secs(/*secs*/ 10))??; + writer.join().expect("secrets store writer should finish"); + + let loaded_first = load_oauth_tokens_from_keyring( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &first.server_name, + &first.url, + )? + .expect("first server tokens should remain stored"); + let loaded_second = load_oauth_tokens_from_keyring( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &second.server_name, + &second.url, + )? + .expect("second server tokens should be stored"); + assert_tokens_match_without_expiry(&loaded_first, &first); + assert_tokens_match_without_expiry(&loaded_second, &second); + Ok(()) +} + +#[test] +fn secrets_store_load_and_delete_observe_aggregate_lock() -> Result<()> { + let env = TempCodexHome::new(); + let keyring_store = MockKeyringStore::default(); + let tokens = sample_tokens(); + save_oauth_tokens_with_keyring( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &tokens.server_name, + &tokens, + )?; + + let store_for_load = keyring_store.clone(); + let server_name = tokens.server_name.clone(); + let url = tokens.url.clone(); + let loaded = + complete_after_store_lock_contention(env.path(), OAuthStore::Secrets, move || { + load_oauth_tokens_from_keyring( + &store_for_load, + AuthKeyringBackendKind::Secrets, + &server_name, + &url, + ) + })? + .expect("encrypted credentials should remain readable after contention"); + assert_tokens_match_without_expiry(&loaded, &tokens); + + let store_for_delete = keyring_store.clone(); + let server_name = tokens.server_name.clone(); + let url = tokens.url.clone(); + let removed = + complete_after_store_lock_contention(env.path(), OAuthStore::Secrets, move || { + crate::oauth::delete_oauth_tokens_from_secrets_keyring( + &store_for_delete, + &server_name, + &url, + ) + })?; + assert!(removed); + assert!( + load_oauth_tokens_from_keyring( + &keyring_store, + AuthKeyringBackendKind::Secrets, + &tokens.server_name, + &tokens.url, + )? + .is_none() + ); + Ok(()) +} From d7ab20ce62e88699947d7b5efb52bc2cd19e006b Mon Sep 17 00:00:00 2001 From: jay Date: Mon, 6 Jul 2026 21:19:50 -0700 Subject: [PATCH 17/79] [codex-cli] Show reset details in redemption picker (#30488) ## Why Users can see that usage-limit reset credits are available, but not which credits they have, when each one expires, or which credit will be consumed. The TUI should use the supported rate-limit RPC for that information without maintaining a second reset-credit request path. ## What changed - load reset-credit details through the existing `account/rateLimits/read` refresh when the user opens **Redeem usage limit reset** - show available credits sorted by expiry, using the backend title when present and a scope-based fallback otherwise - consume the exact selected credit and preserve its idempotency key across retries - fall back to the existing generic reset action when the RPC returns a positive count without detail rows - remove the dedicated list-RPC event, request, response-combining, and TUI state plumbing - handle a selected credit becoming unavailable without incorrectly caching the user's total count as zero - handle forward-compatible unknown reset types with the existing scope-based fallback label ## TUI preview Rendered from the final standard-width and narrow `insta` snapshots in this PR. pr30488-reset-picker-preview ## Validation - `just test -p codex-tui chatwidget::tests::usage` (32 passed) - `just fix -p codex-tui` - no pending `insta` snapshots Uses the reset-credit details added by #30395. Fixes #29618. --- codex-rs/tui/src/app/background_requests.rs | 33 +- codex-rs/tui/src/app/event_dispatch.rs | 59 +-- codex-rs/tui/src/app_event.rs | 13 +- codex-rs/tui/src/chatwidget.rs | 1 + codex-rs/tui/src/chatwidget/reset_credits.rs | 129 +++++++ ...tests__rate_limit_reset_picker_narrow.snap | 13 + ..._tests__rate_limit_reset_popup_states.snap | 10 +- ...sage_limit_reset_confirmation_monthly.snap | 18 +- codex-rs/tui/src/chatwidget/tests/usage.rs | 362 +++++++++++------- codex-rs/tui/src/chatwidget/usage.rs | 144 ++++--- 10 files changed, 526 insertions(+), 256 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/reset_credits.rs create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 9162b2c868..6e2fd0ecbd 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -83,7 +83,8 @@ impl App { tokio::spawn(async move { let request = fetch_account_rate_limits(request_handle); let result = match origin { - RateLimitRefreshOrigin::ResetConsume { .. } => { + RateLimitRefreshOrigin::ResetConsume { .. } + | RateLimitRefreshOrigin::ResetPicker { .. } => { tokio::time::timeout(RATE_LIMIT_RESET_REQUEST_TIMEOUT, request) .await .map_err(|_| "account/rateLimits/read timed out in TUI".to_string()) @@ -118,37 +119,23 @@ impl App { }); } - pub(super) fn refresh_rate_limit_reset_credits( - &mut self, - app_server: &AppServerSession, - request_id: u64, - ) { - let request_handle = app_server.request_handle(); - let app_event_tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let result = tokio::time::timeout( - RATE_LIMIT_RESET_REQUEST_TIMEOUT, - fetch_account_rate_limits(request_handle), - ) - .await - .map_err(|_| "account/rateLimits/read timed out in TUI".to_string()) - .and_then(|result| result.map_err(|err| err.to_string())); - app_event_tx.send(AppEvent::RateLimitResetCreditsLoaded { request_id, result }); - }); - } - pub(super) fn consume_rate_limit_reset_credit( &mut self, app_server: &AppServerSession, request_id: u64, idempotency_key: String, + credit_id: Option, ) { let request_handle = app_server.request_handle(); let app_event_tx = self.app_event_tx.clone(); tokio::spawn(async move { let result = tokio::time::timeout( RATE_LIMIT_RESET_REQUEST_TIMEOUT, - consume_rate_limit_reset_credit_request(request_handle, idempotency_key.clone()), + consume_rate_limit_reset_credit_request( + request_handle, + idempotency_key.clone(), + credit_id.clone(), + ), ) .await .map_err(|_| "account/rateLimitResetCredit/consume timed out in TUI".to_string()) @@ -156,6 +143,7 @@ impl App { app_event_tx.send(AppEvent::RateLimitResetCreditConsumed { request_id, idempotency_key, + credit_id, result, }); }); @@ -793,6 +781,7 @@ pub(super) async fn fetch_account_token_activity( pub(super) async fn consume_rate_limit_reset_credit_request( request_handle: AppServerRequestHandle, idempotency_key: String, + credit_id: Option, ) -> Result { let request_id = RequestId::String(format!("consume-rate-limit-reset-{}", Uuid::new_v4())); request_handle @@ -800,7 +789,7 @@ pub(super) async fn consume_rate_limit_reset_credit_request( request_id, params: ConsumeAccountRateLimitResetCreditParams { idempotency_key, - credit_id: None, + credit_id, }, }) .await diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index afe269195a..8713537fbc 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -865,6 +865,16 @@ impl App { } RateLimitRefreshOrigin::UsageMenu { request_id } => { self.chat_widget.finish_usage_menu_rate_limit_refresh( + request_id, + snapshots, + rate_limit_reset_credits.ok_or_else(|| { + "account/rateLimits/read response did not include rateLimitResetCredits" + .to_string() + }), + ); + } + RateLimitRefreshOrigin::ResetPicker { request_id } => { + self.chat_widget.finish_rate_limit_reset_credits_refresh( request_id, snapshots, rate_limit_reset_credits.ok_or_else(|| { @@ -905,6 +915,13 @@ impl App { Err(err), ); } + RateLimitRefreshOrigin::ResetPicker { request_id } => { + self.chat_widget.finish_rate_limit_reset_credits_refresh( + request_id, + Vec::new(), + Err(err), + ); + } } } }, @@ -914,38 +931,27 @@ impl App { } AppEvent::OpenRateLimitResetCredits => { let request_id = self.chat_widget.show_rate_limit_reset_loading_popup(); - self.refresh_rate_limit_reset_credits(app_server, request_id); + self.refresh_rate_limits( + app_server, + RateLimitRefreshOrigin::ResetPicker { request_id }, + ); } - AppEvent::RateLimitResetCreditsLoaded { request_id, result } => match result { - Ok(response) => { - let rate_limit_reset_credits = response.rate_limit_reset_credits.clone(); - self.chat_widget.finish_rate_limit_reset_credits_refresh( - request_id, - app_server_rate_limit_snapshots(response), - rate_limit_reset_credits.ok_or_else(|| { - "account/rateLimits/read response did not include rateLimitResetCredits" - .to_string() - }), - ); - } - Err(err) => { - tracing::warn!( - "account/rateLimits/read failed during reset-credit refresh: {err}" - ); - self.chat_widget.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Err(err), - ); - } - }, - AppEvent::ConsumeRateLimitResetCredit { idempotency_key } => { + AppEvent::ConsumeRateLimitResetCredit { + idempotency_key, + credit_id, + } => { let request_id = self.chat_widget.show_rate_limit_reset_consuming_popup(); - self.consume_rate_limit_reset_credit(app_server, request_id, idempotency_key); + self.consume_rate_limit_reset_credit( + app_server, + request_id, + idempotency_key, + credit_id, + ); } AppEvent::RateLimitResetCreditConsumed { request_id, idempotency_key, + credit_id, result, } => { if let Err(err) = &result { @@ -956,6 +962,7 @@ impl App { if self.chat_widget.finish_rate_limit_reset_consume( request_id, idempotency_key, + credit_id, result, ) { self.refresh_rate_limits( diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 23e42ce8fe..fa2c9f29fc 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -120,7 +120,8 @@ pub(crate) struct PluginRemoteSectionError { /// invocation and must call `finish_status_rate_limit_refresh` when done so the /// card stops showing a "refreshing" state. A `UsageMenu` refreshes a cached /// zero reset count so the disabled menu entry can become available without a -/// restart. +/// restart. A `ResetPicker` refreshes the rate limits and detailed reset-credit +/// rows before showing redemption choices. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum RateLimitRefreshOrigin { /// Eagerly fetched after bootstrap for `/status` data and reset availability. @@ -130,6 +131,8 @@ pub(crate) enum RateLimitRefreshOrigin { StatusCommand { request_id: u64 }, /// User reopened `/usage` while the cached reset-credit count was zero. UsageMenu { request_id: u64 }, + /// User opened the reset-credit picker. + ResetPicker { request_id: u64 }, /// Refresh requested after a reset credit was successfully consumed. ResetConsume { request_id: u64 }, } @@ -323,21 +326,17 @@ pub(crate) enum AppEvent { /// Open the reset-credit flow selected from the `/usage` menu. OpenRateLimitResetCredits, - /// Result of reading the current reset-credit balance. - RateLimitResetCreditsLoaded { - request_id: u64, - result: Result, - }, - /// Consume one reset credit using a stable idempotency key. ConsumeRateLimitResetCredit { idempotency_key: String, + credit_id: Option, }, /// Result of consuming one reset credit. RateLimitResetCreditConsumed { request_id: u64, idempotency_key: String, + credit_id: Option, result: Result, }, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 42903d2e7f..fa745c652e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -386,6 +386,7 @@ use self::rate_limits::RateLimitWarningState; use self::rate_limits::app_server_rate_limit_error_kind; pub(crate) use self::rate_limits::fallback_limit_label; use self::rate_limits::is_app_server_cyber_policy_error; +mod reset_credits; pub(crate) use self::rate_limits::limit_label_for_window; mod reasoning_shortcuts; mod rendering; diff --git a/codex-rs/tui/src/chatwidget/reset_credits.rs b/codex-rs/tui/src/chatwidget/reset_credits.rs new file mode 100644 index 0000000000..4e58ec3518 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/reset_credits.rs @@ -0,0 +1,129 @@ +use crate::status::RateLimitSnapshotDisplay; +use chrono::DateTime; +use chrono::Local; +use chrono::Utc; +use codex_app_server_protocol::RateLimitResetCreditStatus; +use codex_app_server_protocol::RateLimitResetCreditsSummary; +use codex_app_server_protocol::RateLimitResetType; +use codex_protocol::account::PlanType; +use std::collections::BTreeMap; + +use super::rate_limits::get_limits_duration; + +pub(super) enum RateLimitResetScope { + Monthly, + WeeklyAndFiveHour, + Unknown, +} + +impl RateLimitResetScope { + pub(super) fn picker_label(&self) -> &'static str { + match self { + Self::Monthly => "Full reset (Monthly)", + Self::WeeklyAndFiveHour => "Full reset (Weekly + 5h)", + Self::Unknown => "Full reset", + } + } + + pub(super) fn usage_description(&self) -> &'static str { + match self { + Self::Monthly => "Reset your current monthly usage limit.", + Self::WeeklyAndFiveHour => "Reset your current 5-hour and weekly usage limits.", + Self::Unknown => "Reset your current usage limits.", + } + } +} + +#[derive(Debug, Eq, PartialEq)] +pub(super) struct ResetCreditOption { + pub(super) credit_id: Option, + pub(super) name: String, + pub(super) description: String, +} + +pub(super) fn rate_limit_reset_scope( + rate_limits: &BTreeMap, + plan_type: Option, +) -> RateLimitResetScope { + let window_labels = rate_limits + .iter() + .find(|(limit_id, _)| limit_id.eq_ignore_ascii_case("codex")) + .into_iter() + .flat_map(|(_, snapshot)| [snapshot.primary.as_ref(), snapshot.secondary.as_ref()]) + .flatten() + .filter_map(|window| window.window_minutes.and_then(get_limits_duration)) + .collect::>(); + + if window_labels.iter().any(|label| label == "monthly") + || matches!(plan_type, Some(PlanType::Free | PlanType::Go)) + { + RateLimitResetScope::Monthly + } else if window_labels + .iter() + .any(|label| label == "5h" || label == "weekly") + { + RateLimitResetScope::WeeklyAndFiveHour + } else { + RateLimitResetScope::Unknown + } +} + +pub(super) fn reset_credit_options( + summary: &RateLimitResetCreditsSummary, + scope: RateLimitResetScope, +) -> Vec { + let available_count = summary.available_count.max(0); + let detail_limit = usize::try_from(available_count).unwrap_or(usize::MAX); + let mut available_credits = summary + .credits + .as_deref() + .unwrap_or_default() + .iter() + .filter(|credit| credit.status == RateLimitResetCreditStatus::Available) + .collect::>(); + available_credits.sort_by_key(|credit| credit.expires_at.unwrap_or(i64::MAX)); + + let mut options = available_credits + .into_iter() + .take(detail_limit) + .map(|credit| { + let expiration = match credit.expires_at { + Some(expires_at) => DateTime::::from_timestamp(expires_at, 0) + .map(|expires_at| { + format!( + "Expires {}", + expires_at + .with_timezone(&Local) + .format("%H:%M on %-d %b %Y") + ) + }) + .unwrap_or_else(|| "Expiration unavailable".to_string()), + None => "Does not expire".to_string(), + }; + let reset_label = credit + .title + .as_deref() + .filter(|title| !title.trim().is_empty()) + .unwrap_or_else(|| match credit.reset_type { + RateLimitResetType::CodexRateLimits | RateLimitResetType::Unknown => { + scope.picker_label() + } + }); + ResetCreditOption { + credit_id: Some(credit.id.clone()), + name: reset_label.to_string(), + description: format!("{expiration}."), + } + }) + .collect::>(); + + if options.is_empty() { + options.push(ResetCreditOption { + credit_id: None, + name: "Use a reset".to_string(), + description: scope.usage_description().to_string(), + }); + } + + options +} diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap new file mode 100644 index 0000000000..d64823547f --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/chatwidget/tests/usage.rs +expression: "render_bottom_popup(&chat, 44)" +--- + Usage limit resets + 2 usage limit resets available. + +› 1. Cancel + 2. Full reset Expires 09:39 on 18 Jun + 2026. + 3. Full reset Does not expire. + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap index 12b1568f55..b018313adc 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap @@ -10,10 +10,11 @@ expression: "states.join(\"\\n---\\n\")" Press enter to confirm or esc to go back --- Usage limit resets - You have 2 usage limit resets available. + 2 usage limit resets available. - 1. Use a reset Reset your current 5-hour and weekly usage limits. -› 2. Cancel +› 1. Cancel + 2. Full reset (Weekly + 5 hr) Expires 09:39 on 18 Jun 2026. + 3. Full reset (Weekly + 5 hr) Expires 08:59 on 27 Jun 2026. Press enter to confirm or esc to go back --- @@ -27,7 +28,8 @@ expression: "states.join(\"\\n---\\n\")" Usage limit resets Couldn't load usage limit resets. Please try again. -› 1. Close +› 1. Try again + 2. Close Press enter to confirm or esc to go back --- diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_limit_reset_confirmation_monthly.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_limit_reset_confirmation_monthly.snap index 08a595d4a2..9ace222f46 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_limit_reset_confirmation_monthly.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_limit_reset_confirmation_monthly.snap @@ -4,27 +4,27 @@ expression: "states.join(\"\\n---\\n\")" --- Free: Usage limit resets - You have 1 usage limit reset available. + 1 usage limit reset available. - 1. Use a reset Reset your current monthly usage limit. -› 2. Cancel +› 1. Cancel + 2. Full reset (Monthly) Does not expire. Press enter to confirm or esc to go back --- Go: Usage limit resets - You have 1 usage limit reset available. + 1 usage limit reset available. - 1. Use a reset Reset your current monthly usage limit. -› 2. Cancel +› 1. Cancel + 2. Use a reset Reset your current monthly usage limit. Press enter to confirm or esc to go back --- Business with monthly window: Usage limit resets - You have 1 usage limit reset available. + 1 usage limit reset available. - 1. Use a reset Reset your current monthly usage limit. -› 2. Cancel +› 1. Cancel + 2. Full reset (Monthly) Does not expire. Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests/usage.rs b/codex-rs/tui/src/chatwidget/tests/usage.rs index 22908b1112..2261110b60 100644 --- a/codex-rs/tui/src/chatwidget/tests/usage.rs +++ b/codex-rs/tui/src/chatwidget/tests/usage.rs @@ -1,11 +1,81 @@ +use super::super::reset_credits::RateLimitResetScope; +use super::super::reset_credits::ResetCreditOption; +use super::super::reset_credits::reset_credit_options; use super::*; +use chrono::TimeZone; use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome; use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; +use codex_app_server_protocol::RateLimitResetCredit; +use codex_app_server_protocol::RateLimitResetCreditStatus; use codex_app_server_protocol::RateLimitResetCreditsSummary; +use codex_app_server_protocol::RateLimitResetType; +use pretty_assertions::assert_eq; use uuid::Uuid; const TEST_OVERLAY_VIEW_ID: &str = "usage-test-overlay"; +fn reset_credits(available_count: i64) -> RateLimitResetCreditsSummary { + RateLimitResetCreditsSummary { + available_count, + credits: None, + } +} + +fn detailed_reset_credits( + available_count: i64, + credits: Vec, +) -> RateLimitResetCreditsSummary { + RateLimitResetCreditsSummary { + available_count, + credits: Some(credits), + } +} + +fn reset_credit(id: &str, expires_at: Option) -> RateLimitResetCredit { + RateLimitResetCredit { + id: id.to_string(), + reset_type: RateLimitResetType::CodexRateLimits, + status: RateLimitResetCreditStatus::Available, + granted_at: 0, + expires_at, + title: None, + description: None, + } +} + +fn reset_credit_with_title(id: &str, expires_at: Option, title: &str) -> RateLimitResetCredit { + RateLimitResetCredit { + title: Some(title.to_string()), + ..reset_credit(id, expires_at) + } +} + +fn expiry_timestamp(day: u32, hour: u32, minute: u32) -> i64 { + chrono::Local + .with_ymd_and_hms(2026, 6, day, hour, minute, 0) + .single() + .expect("valid test timestamp") + .timestamp() +} + +#[test] +fn reset_credit_options_use_scope_label_for_unknown_reset_type() { + let mut credit = reset_credit("future-credit", /*expires_at*/ None); + credit.reset_type = RateLimitResetType::Unknown; + + assert_eq!( + reset_credit_options( + &detailed_reset_credits(/*available_count*/ 1, vec![credit]), + RateLimitResetScope::WeeklyAndFiveHour, + ), + vec![ResetCreditOption { + credit_id: Some("future-credit".to_string()), + name: "Full reset (Weekly + 5h)".to_string(), + description: "Does not expire.".to_string(), + }] + ); +} + #[tokio::test] async fn usage_command_opens_menu_when_reset_is_available_snapshot() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -14,10 +84,7 @@ async fn usage_command_opens_menu_when_reset_is_available_snapshot() { assert!(chat.finish_rate_limit_reset_hint_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); chat.dispatch_command(SlashCommand::Usage); @@ -38,10 +105,7 @@ async fn usage_command_disables_reset_after_cached_zero_snapshot() { assert!(chat.finish_rate_limit_reset_hint_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); chat.dispatch_command(SlashCommand::Usage); @@ -69,10 +133,7 @@ async fn usage_menu_refresh_enables_newly_available_reset() { assert!(chat.finish_rate_limit_reset_hint_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); chat.dispatch_command(SlashCommand::Usage); @@ -85,10 +146,7 @@ async fn usage_menu_refresh_enables_newly_available_reset() { chat.finish_usage_menu_rate_limit_refresh( /*request_id*/ 1, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None, - }), + Ok(reset_credits(/*available_count*/ 1)), ); chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); @@ -104,10 +162,7 @@ async fn usage_menu_refresh_failure_preserves_disabled_known_zero() { assert!(chat.finish_rate_limit_reset_hint_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); chat.dispatch_command(SlashCommand::Usage); @@ -137,10 +192,7 @@ async fn account_update_invalidates_usage_menu_refresh_when_visible_state_is_unc assert!(chat.finish_rate_limit_reset_hint_refresh( startup_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); chat.dispatch_command(SlashCommand::Usage); assert_matches!( @@ -157,10 +209,7 @@ async fn account_update_invalidates_usage_menu_refresh_when_visible_state_is_unc chat.finish_usage_menu_rate_limit_refresh( /*request_id*/ 1, vec![snapshot(/*percent*/ 92.0)], - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None, - }), + Ok(reset_credits(/*available_count*/ 2)), ); assert_eq!(chat.available_rate_limit_reset_credits, None); @@ -206,10 +255,7 @@ async fn usage_menu_rate_limit_reset_entry_opens_reset_flow() { assert!(chat.finish_rate_limit_reset_hint_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); chat.dispatch_command(SlashCommand::Usage); @@ -227,13 +273,38 @@ async fn rate_limit_reset_popup_states_snapshot() { let loading_request_id = chat.show_rate_limit_reset_loading_popup(); record_popup(&chat, &mut states); + let first_expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); + let second_expiry = expiry_timestamp(/*day*/ 27, /*hour*/ 8, /*minute*/ 59); + let mut rate_limit_snapshot = snapshot(/*percent*/ 50.0); + rate_limit_snapshot.limit_id = Some("codex".to_string()); + rate_limit_snapshot + .primary + .as_mut() + .expect("primary window") + .window_duration_mins = Some(5 * 60); + rate_limit_snapshot.secondary = Some(RateLimitWindow { + used_percent: 50, + window_duration_mins: Some(7 * 24 * 60), + resets_at: None, + }); assert!(chat.finish_rate_limit_reset_credits_refresh( loading_request_id, - Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + vec![rate_limit_snapshot], + Ok(detailed_reset_credits( + /*available_count*/ 2, + vec![ + reset_credit_with_title( + "credit-2", + Some(second_expiry), + "Full reset (Weekly + 5 hr)", + ), + reset_credit_with_title( + "credit-1", + Some(first_expiry), + "Full reset (Weekly + 5 hr)", + ), + ], + )), )); record_popup(&chat, &mut states); @@ -242,10 +313,7 @@ async fn rate_limit_reset_popup_states_snapshot() { assert!(chat.finish_rate_limit_reset_credits_refresh( empty_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); record_popup(&chat, &mut states); @@ -264,6 +332,7 @@ async fn rate_limit_reset_popup_states_snapshot() { assert!(!chat.finish_rate_limit_reset_consume( consuming_request_id, "redeem-1".to_string(), + /*credit_id*/ None, Err("request timed out".to_string()), )); record_popup(&chat, &mut states); @@ -300,16 +369,36 @@ async fn rate_limit_reset_popup_states_snapshot() { assert!(chat.finish_post_consume_reset_credits_refresh( success_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); record_popup(&chat, &mut states); assert_chatwidget_snapshot!("rate_limit_reset_popup_states", states.join("\n---\n")); } +#[tokio::test] +async fn rate_limit_reset_picker_wraps_expiry_details_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let request_id = chat.show_rate_limit_reset_loading_popup(); + let expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); + assert!(chat.finish_rate_limit_reset_credits_refresh( + request_id, + Vec::new(), + Ok(detailed_reset_credits( + /*available_count*/ 2, + vec![ + reset_credit("credit-2", /*expires_at*/ None), + reset_credit("credit-1", Some(expiry)), + ], + )), + )); + + assert_chatwidget_snapshot!( + "rate_limit_reset_picker_narrow", + render_bottom_popup(&chat, /*width*/ 44) + ); +} + #[tokio::test] async fn usage_limit_reset_confirmation_uses_monthly_copy_for_monthly_limits_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -321,10 +410,10 @@ async fn usage_limit_reset_confirmation_uses_monthly_copy_for_monthly_limits_sna assert!(chat.finish_rate_limit_reset_credits_refresh( free_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(detailed_reset_credits( + /*available_count*/ 1, + vec![reset_credit("free-credit", /*expires_at*/ None)], + )), )); states.push(format!( "Free:\n{}", @@ -337,10 +426,7 @@ async fn usage_limit_reset_confirmation_uses_monthly_copy_for_monthly_limits_sna assert!(chat.finish_rate_limit_reset_credits_refresh( go_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); states.push(format!("Go:\n{}", render_bottom_popup(&chat, /*width*/ 80))); @@ -356,10 +442,10 @@ async fn usage_limit_reset_confirmation_uses_monthly_copy_for_monthly_limits_sna assert!(chat.finish_rate_limit_reset_credits_refresh( business_request_id, vec![monthly_business_snapshot], - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(detailed_reset_credits( + /*available_count*/ 1, + vec![reset_credit("business-credit", /*expires_at*/ None)], + )), )); states.push(format!( "Business with monthly window:\n{}", @@ -379,10 +465,7 @@ async fn rate_limit_reset_confirmation_selects_cancel_by_default() { assert!(chat.finish_rate_limit_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); @@ -391,6 +474,49 @@ async fn rate_limit_reset_confirmation_selects_cancel_by_default() { assert!(rx.try_recv().is_err()); } +#[tokio::test] +async fn rate_limit_reset_picker_starts_with_soonest_expiries_and_keeps_all_rows_reachable() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.plan_type = Some(PlanType::Business); + let request_id = chat.show_rate_limit_reset_loading_popup(); + let first_expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); + let credits = (0..9) + .rev() + .map(|index| { + reset_credit( + &format!("credit-{index}"), + Some(first_expiry + i64::from(index) * 86_400), + ) + }) + .collect(); + assert!(chat.finish_rate_limit_reset_credits_refresh( + request_id, + Vec::new(), + Ok(detailed_reset_credits(/*available_count*/ 9, credits)), + )); + + let rendered = render_bottom_popup(&chat, /*width*/ 80); + assert!( + rendered.contains("Expires 09:39 on 18 Jun 2026."), + "{rendered}" + ); + assert!(!rendered.contains("Full reset ("), "{rendered}"); + + for _ in 0..9 { + chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + } + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::ConsumeRateLimitResetCredit { + idempotency_key, + credit_id, + }) if Uuid::parse_str(&idempotency_key).is_ok() + && credit_id.as_deref() == Some("credit-8") + ); +} + #[tokio::test] async fn rate_limit_reset_confirmation_can_use_reset() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -398,19 +524,18 @@ async fn rate_limit_reset_confirmation_can_use_reset() { assert!(chat.finish_rate_limit_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); - chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); assert_matches!( rx.try_recv(), - Ok(AppEvent::ConsumeRateLimitResetCredit { idempotency_key }) - if Uuid::parse_str(&idempotency_key).is_ok() + Ok(AppEvent::ConsumeRateLimitResetCredit { + idempotency_key, + credit_id, + }) if Uuid::parse_str(&idempotency_key).is_ok() && credit_id.is_none() ); } @@ -421,6 +546,7 @@ async fn rate_limit_reset_retry_reuses_idempotency_key() { assert!(!chat.finish_rate_limit_reset_consume( request_id, "stable-redeem-id".to_string(), + Some("credit-1".to_string()), Err("response lost".to_string()), )); @@ -428,8 +554,11 @@ async fn rate_limit_reset_retry_reuses_idempotency_key() { assert_matches!( rx.try_recv(), - Ok(AppEvent::ConsumeRateLimitResetCredit { idempotency_key }) - if idempotency_key == "stable-redeem-id" + Ok(AppEvent::ConsumeRateLimitResetCredit { + idempotency_key, + credit_id, + }) if idempotency_key == "stable-redeem-id" + && credit_id.as_deref() == Some("credit-1") ); } @@ -441,10 +570,7 @@ async fn no_credit_outcome_disables_reset_entry_in_usage_menu() { assert!(chat.finish_rate_limit_reset_hint_refresh( startup_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); assert!(!finish_reset_consume_outcome( @@ -466,6 +592,23 @@ async fn no_credit_outcome_disables_reset_entry_in_usage_menu() { chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); assert_matches!(rx.try_recv(), Ok(AppEvent::OpenTokenActivity)); + + chat.available_rate_limit_reset_credits = Some(2); + let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); + assert!(!chat.finish_rate_limit_reset_consume( + consume_request_id, + "redeem-selected".to_string(), + Some("stale-credit".to_string()), + Ok(consume_response( + ConsumeAccountRateLimitResetCreditOutcome::NoCredit + )), + )); + assert_eq!(chat.available_rate_limit_reset_credits, None); + assert!( + render_bottom_popup(&chat, /*width*/ 80).contains("That reset is no longer available.") + ); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); } #[tokio::test] @@ -489,10 +632,7 @@ async fn rate_limit_reset_redemption_cannot_be_dismissed_while_in_flight() { assert!(chat.finish_post_consume_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); dismiss_popup(&mut chat); assert!(chat.bottom_pane.no_modal_or_popup_active()); @@ -523,10 +663,7 @@ async fn already_redeemed_is_an_idempotent_success() { assert!(chat.finish_post_consume_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); assert!( render_bottom_popup(&chat, /*width*/ 80) @@ -542,10 +679,7 @@ async fn failed_post_consume_refresh_does_not_keep_stale_reset_count() { assert!(chat.finish_rate_limit_reset_hint_refresh( startup_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); assert!(finish_reset_consume_outcome( @@ -582,10 +716,7 @@ async fn account_change_invalidates_pending_reset_requests() { assert!(!chat.finish_rate_limit_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert!(chat.bottom_pane.no_modal_or_popup_active()); } @@ -599,10 +730,7 @@ async fn clearing_pending_reset_hint_preserves_in_flight_redemption() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); chat.clear_pending_rate_limit_reset_hint(); @@ -625,10 +753,7 @@ async fn rate_limit_reset_load_result_updates_popup_beneath_overlay() { assert!(chat.finish_rate_limit_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert_eq!( chat.bottom_pane.active_view_id(), @@ -636,10 +761,7 @@ async fn rate_limit_reset_load_result_updates_popup_beneath_overlay() { ); chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!( - render_bottom_popup(&chat, /*width*/ 80) - .contains("You have 2 usage limit resets available.") - ); + assert!(render_bottom_popup(&chat, /*width*/ 80).contains("2 usage limit resets available.")); } #[tokio::test] @@ -657,10 +779,7 @@ async fn rate_limit_reset_success_updates_popup_beneath_overlay() { assert!(chat.finish_post_consume_reset_credits_refresh( request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None - }), + Ok(reset_credits(/*available_count*/ 1)), )); assert_eq!( chat.bottom_pane.active_view_id(), @@ -703,10 +822,7 @@ async fn startup_check_shows_available_reset_hint_snapshot() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); let rendered = lines_to_single_string( &chat @@ -729,10 +845,7 @@ async fn startup_reset_hint_waits_for_active_output_snapshot() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert!(chat.usage_history_insertion_blocked()); @@ -763,10 +876,7 @@ async fn opening_rate_limit_reset_flow_invalidates_in_flight_startup_hint() { assert!(!chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert!(chat.pending_rate_limit_reset_hint().is_none()); } @@ -779,10 +889,7 @@ async fn starting_rate_limit_reset_redemption_clears_deferred_startup_hint() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert!(chat.pending_rate_limit_reset_hint().is_some()); @@ -800,10 +907,7 @@ async fn startup_check_omits_reset_hint_when_none_are_available() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None - }), + Ok(reset_credits(/*available_count*/ 0)), )); assert!(chat.pending_rate_limit_reset_hint().is_none()); } @@ -818,10 +922,7 @@ async fn startup_check_shows_reset_hint_for_workspace_account_with_credit() { assert!(chat.finish_rate_limit_reset_hint_refresh( hint_request_id, Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 2, - credits: None - }), + Ok(reset_credits(/*available_count*/ 2)), )); assert!(chat.pending_rate_limit_reset_hint().is_some()); assert_eq!(chat.available_rate_limit_reset_credits, Some(2)); @@ -842,6 +943,7 @@ fn finish_reset_consume_outcome( chat.finish_rate_limit_reset_consume( request_id, idempotency_key.to_string(), + /*credit_id*/ None, Ok(consume_response(outcome)), ) } diff --git a/codex-rs/tui/src/chatwidget/usage.rs b/codex-rs/tui/src/chatwidget/usage.rs index 53925e86d9..731c0a994a 100644 --- a/codex-rs/tui/src/chatwidget/usage.rs +++ b/codex-rs/tui/src/chatwidget/usage.rs @@ -3,7 +3,8 @@ use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; use codex_app_server_protocol::RateLimitResetCreditsSummary; use uuid::Uuid; -use super::rate_limits::get_limits_duration; +use super::reset_credits::rate_limit_reset_scope; +use super::reset_credits::reset_credit_options; use super::*; const USAGE_MENU_VIEW_ID: &str = "usage-menu"; @@ -131,18 +132,20 @@ impl ChatWidget { let params = match result { Ok(response) => { - self.available_rate_limit_reset_credits = Some(response.available_count); - if response.available_count > 0 { - self.rate_limit_reset_confirmation_params(response.available_count) + let available_count = response.available_count; + let params = if available_count > 0 { + self.rate_limit_reset_confirmation_params(&response) } else { Self::rate_limit_reset_message_params( "You don't have any usage limit resets available.", ) - } + }; + self.available_rate_limit_reset_credits = Some(available_count); + params + } + Err(_) => { + Self::reset_refresh_params("Couldn't load usage limit resets. Please try again.") } - Err(_) => Self::rate_limit_reset_message_params( - "Couldn't load usage limit resets. Please try again.", - ), }; let replaced = self .bottom_pane @@ -153,56 +156,47 @@ impl ChatWidget { replaced } - fn rate_limit_reset_confirmation_params(&self, available_count: i64) -> SelectionViewParams { - let idempotency_key = Uuid::new_v4().to_string(); - let has_monthly_window = self - .rate_limit_snapshots_by_limit_id - .iter() - .find(|(limit_id, _)| limit_id.eq_ignore_ascii_case("codex")) - .into_iter() - .flat_map(|(_, snapshot)| [snapshot.primary.as_ref(), snapshot.secondary.as_ref()]) - .flatten() - .any(|window| { - window - .window_minutes - .and_then(get_limits_duration) - .as_deref() - == Some("monthly") - }); - let reset_description = if has_monthly_window - || matches!(self.plan_type, Some(PlanType::Free | PlanType::Go)) - { - "Reset your current monthly usage limit." - } else { - "Reset your current 5-hour and weekly usage limits." - }; + fn rate_limit_reset_confirmation_params( + &self, + reset_credits: &RateLimitResetCreditsSummary, + ) -> SelectionViewParams { + let scope = rate_limit_reset_scope(&self.rate_limit_snapshots_by_limit_id, self.plan_type); + let mut items = vec![SelectionItem { + name: "Cancel".to_string(), + dismiss_on_select: true, + ..Default::default() + }]; + items.extend( + reset_credit_options(reset_credits, scope) + .into_iter() + .map(|option| { + let idempotency_key = Uuid::new_v4().to_string(); + let credit_id = option.credit_id; + SelectionItem { + name: option.name, + description: Some(option.description), + actions: vec![Box::new(move |tx| { + tx.send(AppEvent::ConsumeRateLimitResetCredit { + idempotency_key: idempotency_key.clone(), + credit_id: credit_id.clone(), + }); + })], + dismiss_on_select: true, + ..Default::default() + } + }), + ); SelectionViewParams { view_id: Some(RATE_LIMIT_RESET_VIEW_ID), title: Some("Usage limit resets".to_string()), subtitle: Some(format!( - "You have {available_count} {} available.", - reset_label(available_count) + "{} {} available.", + reset_credits.available_count, + reset_label(reset_credits.available_count) )), footer_hint: Some(standard_popup_hint_line()), - items: vec![ - SelectionItem { - name: "Use a reset".to_string(), - description: Some(reset_description.to_string()), - actions: vec![Box::new(move |tx| { - tx.send(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key: idempotency_key.clone(), - }); - })], - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "Cancel".to_string(), - dismiss_on_select: true, - ..Default::default() - }, - ], - initial_selected_idx: Some(1), + items, + initial_selected_idx: Some(0), ..Default::default() } } @@ -221,6 +215,30 @@ impl ChatWidget { } } + fn reset_refresh_params(message: &str) -> SelectionViewParams { + SelectionViewParams { + view_id: Some(RATE_LIMIT_RESET_VIEW_ID), + title: Some("Usage limit resets".to_string()), + subtitle: Some(message.to_string()), + items: vec![ + SelectionItem { + name: "Try again".to_string(), + actions: vec![Box::new(|tx| { + tx.send(AppEvent::OpenRateLimitResetCredits); + })], + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "Close".to_string(), + dismiss_on_select: true, + ..Default::default() + }, + ], + ..Default::default() + } + } + pub(crate) fn show_rate_limit_reset_consuming_popup(&mut self) -> u64 { self.clear_pending_rate_limit_reset_hint(); let request_id = self.take_next_rate_limit_reset_request_id(); @@ -245,6 +263,7 @@ impl ChatWidget { &mut self, request_id: u64, idempotency_key: String, + credit_id: Option, result: Result, ) -> bool { if self.pending_rate_limit_reset_request_id != Some(request_id) { @@ -269,6 +288,13 @@ impl ChatWidget { ConsumeAccountRateLimitResetCreditOutcome::NothingToReset => { "Your usage does not need a reset right now." } + ConsumeAccountRateLimitResetCreditOutcome::NoCredit if credit_id.is_some() => { + self.available_rate_limit_reset_credits = None; + self.replace_rate_limit_reset_popup(Self::reset_refresh_params( + "That reset is no longer available. Refresh to see your current resets.", + )); + return false; + } ConsumeAccountRateLimitResetCreditOutcome::NoCredit => { self.available_rate_limit_reset_credits = Some(0); "No usage limit resets are available." @@ -291,6 +317,7 @@ impl ChatWidget { actions: vec![Box::new(move |tx| { tx.send(AppEvent::ConsumeRateLimitResetCredit { idempotency_key: idempotency_key.clone(), + credit_id: credit_id.clone(), }); })], dismiss_on_select: true, @@ -325,11 +352,11 @@ impl ChatWidget { let message = match result { Ok(response) => { - self.available_rate_limit_reset_credits = Some(response.available_count); + let available_count = response.available_count; + self.available_rate_limit_reset_credits = Some(available_count); format!( - "Usage reset. You have {} {} left.", - response.available_count, - reset_label(response.available_count) + "Usage reset. You have {available_count} {} left.", + reset_label(available_count) ) } Err(_) => "Usage reset.".to_string(), @@ -386,8 +413,9 @@ impl ChatWidget { return false; } if let Ok(response) = result { - self.available_rate_limit_reset_credits = Some(response.available_count); - self.set_rate_limit_reset_available_hint(response.available_count); + let available_count = response.available_count; + self.available_rate_limit_reset_credits = Some(available_count); + self.set_rate_limit_reset_available_hint(available_count); } true } From cca16a10878202cb2f6e9666b6b4330329ea7e65 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Mon, 6 Jul 2026 21:22:51 -0700 Subject: [PATCH 18/79] feat(core): emit canonical command execution items (#31297) This PR depends on [#31296](https://github.com/openai/codex/pull/31296) for the canonical-to-legacy event mappings. ## Description This PR makes command execution emit canonical `TurnItem::CommandExecution` lifecycle from both the shell tool path and user `/shell` commands. App-server v2 consumes the canonical command items directly and ignores the mapped `ExecCommandBegin` / `ExecCommandEnd` compatibility events, so clients still receive one command item lifecycle. `UnifiedExecInteraction` stays on the legacy path because `TerminalInteraction` is still the v2 surface for stdin and poll events. Emitting a command item there would render the same wait twice. ## Why This is the first live producer migration after the compatibility mappings in #31296. Keeping command execution separate makes the unified exec exception reviewable without mixing in dynamic tools or multi-agent behavior. ## What changed - Emit canonical command execution items from shell tool events and user shell commands. - Preserve the existing unified exec interaction carveout. - Move app-server command deduplication and completion bookkeeping onto canonical item events. - Update unified exec coverage to assert the completed command item. --- .../app-server/src/bespoke_event_handling.rs | 105 +++++++++--------- codex-rs/core/src/tasks/user_shell.rs | 100 ++++++++--------- codex-rs/core/src/tools/events.rs | 84 +++++++++++--- .../core/src/unified_exec/process_manager.rs | 5 +- .../src/unified_exec/process_manager_tests.rs | 23 ++-- 5 files changed, 181 insertions(+), 136 deletions(-) diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index c63103161f..4bd1d6e108 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -90,6 +90,7 @@ 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::TurnItem as CoreTurnItem; use codex_protocol::items::parse_hook_prompt_message; use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile; use codex_protocol::plan_tool::UpdatePlanArgs; @@ -1027,10 +1028,37 @@ pub(crate) async fn apply_bespoke_event_handling( .send_server_notification(ServerNotification::ItemCompleted(completed)) .await; } - msg @ (EventMsg::ItemStarted(_) - | EventMsg::ItemCompleted(_) - | EventMsg::PatchApplyUpdated(_) - | EventMsg::TerminalInteraction(_)) => { + EventMsg::ItemStarted(event) => { + let should_emit = match &event.item { + // Approval and guardian flows can emit the command start notification before core + // emits the canonical item. Reuse the same set to suppress that duplicate. + CoreTurnItem::CommandExecution(item) => thread_state + .lock() + .await + .turn_summary + .command_execution_started + .insert(item.id.clone()), + _ => true, + }; + if should_emit { + let notification = item_event_to_server_notification( + EventMsg::ItemStarted(event), + &conversation_id.to_string(), + &event_turn_id, + ); + outgoing.send_server_notification(notification).await; + } + } + EventMsg::ItemCompleted(event) => { + apply_canonical_item_completed_side_effects(&thread_state, &event.item).await; + let notification = item_event_to_server_notification( + EventMsg::ItemCompleted(event), + &conversation_id.to_string(), + &event_turn_id, + ); + outgoing.send_server_notification(notification).await; + } + msg @ (EventMsg::PatchApplyUpdated(_) | EventMsg::TerminalInteraction(_)) => { let notification = item_event_to_server_notification( msg, &conversation_id.to_string(), @@ -1106,32 +1134,10 @@ pub(crate) async fn apply_bespoke_event_handling( // Core still fans out these deprecated events for legacy clients; // v2 clients receive the canonical FileChange item instead. } - EventMsg::ExecCommandBegin(exec_command_begin_event) => { - if matches!( - exec_command_begin_event.source, - codex_protocol::protocol::ExecCommandSource::UnifiedExecInteraction - ) { - // TerminalInteraction is the v2 surface for unified exec - // stdin/poll events. Suppress the legacy CommandExecution - // item so clients do not render the same wait twice. - return; - } - let item_id = exec_command_begin_event.call_id.clone(); - let first_start = { - let mut state = thread_state.lock().await; - state - .turn_summary - .command_execution_started - .insert(item_id.clone()) - }; - if first_start { - let notification = item_event_to_server_notification( - EventMsg::ExecCommandBegin(exec_command_begin_event), - &conversation_id.to_string(), - &event_turn_id, - ); - outgoing.send_server_notification(notification).await; - } + EventMsg::ExecCommandBegin(_) | EventMsg::ExecCommandEnd(_) => { + // Deprecated command-execution events are still fanned out for raw-event and rollout + // compatibility consumers. App-server v2 receives the canonical CommandExecution + // item lifecycle instead. } EventMsg::ExecCommandOutputDelta(exec_command_output_delta_event) => { let notification = item_event_to_server_notification( @@ -1141,31 +1147,6 @@ pub(crate) async fn apply_bespoke_event_handling( ); outgoing.send_server_notification(notification).await; } - EventMsg::ExecCommandEnd(exec_command_end_event) => { - let call_id = exec_command_end_event.call_id.clone(); - { - let mut state = thread_state.lock().await; - state - .turn_summary - .command_execution_started - .remove(&call_id); - } - if matches!( - exec_command_end_event.source, - codex_protocol::protocol::ExecCommandSource::UnifiedExecInteraction - ) { - // The paired begin event is suppressed above; keep the - // completion out of v2 as well so no orphan legacy item is - // emitted for unified exec interactions. - return; - } - let notification = item_event_to_server_notification( - EventMsg::ExecCommandEnd(exec_command_end_event), - &conversation_id.to_string(), - &event_turn_id, - ); - outgoing.send_server_notification(notification).await; - } // If this is a TurnAborted, reply to any pending interrupt requests. EventMsg::TurnAborted(turn_aborted_event) => { // All per-thread requests are bound to a turn, so abort them. @@ -1369,6 +1350,20 @@ async fn emit_turn_completed_with_status( .await; } +async fn apply_canonical_item_completed_side_effects( + thread_state: &Arc>, + item: &CoreTurnItem, +) { + if let CoreTurnItem::CommandExecution(item) = item { + thread_state + .lock() + .await + .turn_summary + .command_execution_started + .remove(&item.id); + } +} + #[allow(clippy::too_many_arguments)] async fn start_command_execution_item( conversation_id: &ThreadId, diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index d588e5a356..a15c53e16b 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -25,16 +25,15 @@ use crate::tools::runtimes::RuntimePathPrepends; use crate::tools::runtimes::apply_package_path_prepend; use crate::tools::runtimes::maybe_wrap_shell_lc_with_snapshot; use crate::tools::runtimes::strip_managed_proxy_env; -use crate::turn_timing::now_unix_timestamp_ms; use crate::user_shell_command::user_shell_command_record_item; use codex_protocol::exec_output::ExecToolCallOutput; use codex_protocol::exec_output::StreamOutput; +use codex_protocol::items::CommandExecutionItem; +use codex_protocol::items::CommandExecutionStatus; +use codex_protocol::items::TurnItem; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::ExecCommandBeginEvent; -use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ExecCommandSource; -use codex_protocol::protocol::ExecCommandStatus; use codex_protocol::protocol::TurnStartedEvent; use codex_sandboxing::SandboxType; use codex_shell_command::parse_command::parse_command; @@ -181,18 +180,23 @@ pub(crate) async fn execute_user_shell_command( let parsed_cmd = parse_command(&display_command); session - .send_event( + .emit_turn_item_started( turn_context.as_ref(), - EventMsg::ExecCommandBegin(ExecCommandBeginEvent { - call_id: call_id.clone(), + &TurnItem::CommandExecution(CommandExecutionItem { + id: call_id.clone(), process_id: None, - turn_id: turn_context.sub_id.clone(), - started_at_ms: now_unix_timestamp_ms(), command: display_command.clone(), cwd: cwd.clone().into(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::UserShell, interaction_input: None, + status: CommandExecutionStatus::InProgress, + stdout: None, + stderr: None, + aggregated_output: None, + exit_code: None, + duration: None, + formatted_output: None, }), ) .await; @@ -259,57 +263,53 @@ pub(crate) async fn execute_user_shell_command( ) .await; session - .send_event( + .emit_turn_item_completed( turn_context.as_ref(), - EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id, + TurnItem::CommandExecution(CommandExecutionItem { + id: call_id, process_id: None, - turn_id: turn_context.sub_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), command: display_command.clone(), cwd: cwd.clone().into(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::UserShell, interaction_input: None, - stdout: String::new(), - stderr: aborted_message.clone(), - aggregated_output: aborted_message.clone(), - exit_code: -1, - duration: Duration::ZERO, - formatted_output: aborted_message, - status: ExecCommandStatus::Failed, + status: CommandExecutionStatus::Failed, + stdout: Some(String::new()), + stderr: Some(aborted_message.clone()), + aggregated_output: Some(aborted_message.clone()), + exit_code: Some(-1), + duration: Some(Duration::ZERO), + formatted_output: Some(aborted_message), }), ) .await; } Ok(Ok(output)) => { session - .send_event( + .emit_turn_item_completed( turn_context.as_ref(), - EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id: call_id.clone(), + TurnItem::CommandExecution(CommandExecutionItem { + id: call_id.clone(), process_id: None, - turn_id: turn_context.sub_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), command: display_command.clone(), cwd: cwd.clone().into(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::UserShell, interaction_input: None, - stdout: output.stdout.text.clone(), - stderr: output.stderr.text.clone(), - aggregated_output: output.aggregated_output.text.clone(), - exit_code: output.exit_code, - duration: output.duration, - formatted_output: format_exec_output_str( + status: if output.exit_code == 0 { + CommandExecutionStatus::Completed + } else { + CommandExecutionStatus::Failed + }, + stdout: Some(output.stdout.text.clone()), + stderr: Some(output.stderr.text.clone()), + aggregated_output: Some(output.aggregated_output.text.clone()), + exit_code: Some(output.exit_code), + duration: Some(output.duration), + formatted_output: Some(format_exec_output_str( &output, turn_context.model_info.truncation_policy.into(), - ), - status: if output.exit_code == 0 { - ExecCommandStatus::Completed - } else { - ExecCommandStatus::Failed - }, + )), }), ) .await; @@ -329,28 +329,26 @@ pub(crate) async fn execute_user_shell_command( timed_out: false, }; session - .send_event( + .emit_turn_item_completed( turn_context.as_ref(), - EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id, + TurnItem::CommandExecution(CommandExecutionItem { + id: call_id, process_id: None, - turn_id: turn_context.sub_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), command: display_command, cwd: cwd.into(), parsed_cmd, source: ExecCommandSource::UserShell, interaction_input: None, - stdout: exec_output.stdout.text.clone(), - stderr: exec_output.stderr.text.clone(), - aggregated_output: exec_output.aggregated_output.text.clone(), - exit_code: exec_output.exit_code, - duration: exec_output.duration, - formatted_output: format_exec_output_str( + status: CommandExecutionStatus::Failed, + stdout: Some(exec_output.stdout.text.clone()), + stderr: Some(exec_output.stderr.text.clone()), + aggregated_output: Some(exec_output.aggregated_output.text.clone()), + exit_code: Some(exec_output.exit_code), + duration: Some(exec_output.duration), + formatted_output: Some(format_exec_output_str( &exec_output, turn_context.model_info.truncation_policy.into(), - ), - status: ExecCommandStatus::Failed, + )), }), ) .await; diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 757125a03d..5b30c6a156 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -8,6 +8,8 @@ use codex_apply_patch::AppliedPatchDelta; use codex_protocol::error::CodexErr; use codex_protocol::error::SandboxErr; use codex_protocol::exec_output::ExecToolCallOutput; +use codex_protocol::items::CommandExecutionItem; +use codex_protocol::items::CommandExecutionStatus; use codex_protocol::items::FileChangeItem; use codex_protocol::items::TurnItem; use codex_protocol::parse_command::ParsedCommand; @@ -102,19 +104,43 @@ pub(crate) async fn emit_exec_command_begin( interaction_input: Option, process_id: Option<&str>, ) { + if matches!(source, ExecCommandSource::UnifiedExecInteraction) { + ctx.session + .send_event( + ctx.turn, + EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: ctx.call_id.to_string(), + process_id: process_id.map(str::to_owned), + turn_id: ctx.turn.sub_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + command: command.to_vec(), + cwd: cwd.clone(), + parsed_cmd: parsed_cmd.to_vec(), + source, + interaction_input, + }), + ) + .await; + return; + } ctx.session - .send_event( + .emit_turn_item_started( ctx.turn, - EventMsg::ExecCommandBegin(ExecCommandBeginEvent { - call_id: ctx.call_id.to_string(), + &TurnItem::CommandExecution(CommandExecutionItem { + id: ctx.call_id.to_string(), process_id: process_id.map(str::to_owned), - turn_id: ctx.turn.sub_id.clone(), - started_at_ms: now_unix_timestamp_ms(), command: command.to_vec(), cwd: cwd.clone(), parsed_cmd: parsed_cmd.to_vec(), source, interaction_input, + status: CommandExecutionStatus::InProgress, + stdout: None, + stderr: None, + aggregated_output: None, + exit_code: None, + duration: None, + formatted_output: None, }), ) .await; @@ -542,26 +568,50 @@ async fn emit_exec_end( exec_input: ExecCommandInput<'_>, exec_result: ExecCommandResult, ) { + if matches!(exec_input.source, ExecCommandSource::UnifiedExecInteraction) { + ctx.session + .send_event( + ctx.turn, + EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id: ctx.call_id.to_string(), + process_id: exec_input.process_id.map(str::to_owned), + turn_id: ctx.turn.sub_id.clone(), + completed_at_ms: now_unix_timestamp_ms(), + command: exec_input.command.to_vec(), + cwd: exec_input.cwd.clone(), + parsed_cmd: exec_input.parsed_cmd.to_vec(), + source: exec_input.source, + interaction_input: exec_input.interaction_input.map(str::to_owned), + stdout: exec_result.stdout, + stderr: exec_result.stderr, + aggregated_output: exec_result.aggregated_output, + exit_code: exec_result.exit_code, + duration: exec_result.duration, + formatted_output: exec_result.formatted_output, + status: exec_result.status, + }), + ) + .await; + return; + } ctx.session - .send_event( + .emit_turn_item_completed( ctx.turn, - EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id: ctx.call_id.to_string(), + TurnItem::CommandExecution(CommandExecutionItem { + id: ctx.call_id.to_string(), process_id: exec_input.process_id.map(str::to_owned), - turn_id: ctx.turn.sub_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), command: exec_input.command.to_vec(), cwd: exec_input.cwd.clone(), parsed_cmd: exec_input.parsed_cmd.to_vec(), source: exec_input.source, interaction_input: exec_input.interaction_input.map(str::to_owned), - stdout: exec_result.stdout, - stderr: exec_result.stderr, - aggregated_output: exec_result.aggregated_output, - exit_code: exec_result.exit_code, - duration: exec_result.duration, - formatted_output: exec_result.formatted_output, - status: exec_result.status, + status: exec_result.status.into(), + stdout: Some(exec_result.stdout), + stderr: Some(exec_result.stderr), + aggregated_output: Some(exec_result.aggregated_output), + exit_code: Some(exec_result.exit_code), + duration: Some(exec_result.duration), + formatted_output: Some(exec_result.formatted_output), }), ) .await; diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index a895708f79..fe3ec45759 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -573,9 +573,8 @@ impl UnifiedExecProcessManager { } } } else { - // Short‑lived command: emit ExecCommandEnd immediately using the - // same helper as the background watcher, so all end events share - // one implementation. + // Short-lived command: emit the completed command item immediately + // using the same helper as the background watcher. let finish_result = finish_deferred_network_approval_after_process_exit_for_session( Some(&context.session), deferred_network_approval.take(), diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index 096cbe0a13..20a930b552 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -315,21 +315,24 @@ async fn failed_initial_end_for_unstored_process_uses_fallback_output() { let event = tokio::time::timeout(Duration::from_secs(1), rx_event.recv()) .await - .expect("timed out waiting for failed exec end event") + .expect("timed out waiting for failed command execution item") .expect("event channel closed"); - let codex_protocol::protocol::EventMsg::ExecCommandEnd(end_event) = event.msg else { - panic!("expected ExecCommandEnd event"); + let codex_protocol::protocol::EventMsg::ItemCompleted(completed_event) = event.msg else { + panic!("expected ItemCompleted event"); }; - assert_eq!(end_event.call_id, "call-unified-denied"); + let codex_protocol::items::TurnItem::CommandExecution(item) = completed_event.item else { + panic!("expected CommandExecution item"); + }; + assert_eq!(item.id, "call-unified-denied"); assert_eq!( - end_event.status, - codex_protocol::protocol::ExecCommandStatus::Failed + item.status, + codex_protocol::items::CommandExecutionStatus::Failed ); - assert_eq!(end_event.exit_code, -1); - assert_eq!(end_event.process_id.as_deref(), Some("123")); + assert_eq!(item.exit_code, Some(-1)); + assert_eq!(item.process_id.as_deref(), Some("123")); assert_eq!( - end_event.aggregated_output, - "PRE_DENIAL_MARKER\nNetwork access denied" + item.aggregated_output.as_deref(), + Some("PRE_DENIAL_MARKER\nNetwork access denied") ); } From f659eb12bc8cecb976d92db192d9b2983c8053ff Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 7 Jul 2026 08:32:14 -0700 Subject: [PATCH 19/79] feat(core): emit canonical dynamic tool call items (#31298) This PR depends on [#31296](https://github.com/openai/codex/pull/31296) for the canonical-to-legacy event mappings. ## Description This PR makes dynamic tools emit canonical `TurnItem::DynamicToolCall` lifecycle instead of `DynamicToolCallRequest` / `DynamicToolCallResponse` directly. App-server v2 now sends the client `DynamicToolCall` request from the canonical item start. It ignores the mapped legacy request/response events, so clients receive one item start and one tool request. ## Why Dynamic tools are a separate migration boundary because their start event also drives a client request. Keeping that routing change isolated makes it easier to verify that the request still happens exactly once. ## What changed - Emit in-progress and completed/failed dynamic tool items from the dynamic tool handler. - Move app-server client request dispatch onto canonical dynamic item starts. - Add focused app-server coverage for the canonical start notification and client request. --- .../app-server/src/bespoke_event_handling.rs | 158 +++++++++++++----- codex-rs/core/src/tools/handlers/dynamic.rs | 74 ++++---- 2 files changed, 157 insertions(+), 75 deletions(-) diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 4bd1d6e108..863aeac79b 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -22,7 +22,6 @@ use codex_app_server_protocol::CommandExecutionSource; use codex_app_server_protocol::CommandExecutionStatus; use codex_app_server_protocol::DeprecationNoticeNotification; use codex_app_server_protocol::DynamicToolCallParams; -use codex_app_server_protocol::DynamicToolCallStatus; use codex_app_server_protocol::ErrorNotification; use codex_app_server_protocol::ExecPolicyAmendment as V2ExecPolicyAmendment; use codex_app_server_protocol::FileChangeApprovalDecision; @@ -823,52 +822,16 @@ pub(crate) async fn apply_bespoke_event_handling( on_request_permissions_response(pending_response, conversation, thread_state).await; }); } - EventMsg::DynamicToolCallRequest(request) => { - let call_id = request.call_id; - let turn_id = request.turn_id; - let namespace = request.namespace; - let tool = request.tool; - let arguments = request.arguments; - let item = ThreadItem::DynamicToolCall { - id: call_id.clone(), - namespace: namespace.clone(), - tool: tool.clone(), - arguments: arguments.clone(), - status: DynamicToolCallStatus::InProgress, - content_items: None, - success: None, - duration_ms: None, - }; - let notification = ItemStartedNotification { - thread_id: conversation_id.to_string(), - turn_id: turn_id.clone(), - started_at_ms: request.started_at_ms, - item, - }; - outgoing - .send_server_notification(ServerNotification::ItemStarted(notification)) - .await; - let params = DynamicToolCallParams { - thread_id: conversation_id.to_string(), - turn_id: turn_id.clone(), - call_id: call_id.clone(), - namespace, - tool: tool.clone(), - arguments: arguments.clone(), - }; - let (_pending_request_id, rx) = outgoing - .send_request(ServerRequestPayload::DynamicToolCall(params)) - .await; - tokio::spawn(async move { - crate::dynamic_tools::on_call_response(call_id, rx, conversation).await; - }); + EventMsg::DynamicToolCallRequest(_) | EventMsg::DynamicToolCallResponse(_) => { + // Deprecated dynamic-tool events are still fanned out for raw-event and rollout + // compatibility consumers. App-server v2 receives the canonical DynamicToolCall + // item lifecycle and dispatches client requests from canonical starts instead. } EventMsg::McpToolCallBegin(_) | EventMsg::McpToolCallEnd(_) => { // Deprecated MCP tool-call events are still fanned out for legacy clients. // App-server v2 receives the canonical TurnItem::McpToolCall lifecycle instead. } - msg @ (EventMsg::DynamicToolCallResponse(_) - | EventMsg::CollabAgentSpawnBegin(_) + msg @ (EventMsg::CollabAgentSpawnBegin(_) | EventMsg::CollabAgentSpawnEnd(_) | EventMsg::CollabAgentInteractionBegin(_) | EventMsg::CollabAgentInteractionEnd(_) @@ -1040,6 +1003,17 @@ pub(crate) async fn apply_bespoke_event_handling( .insert(item.id.clone()), _ => true, }; + let dynamic_tool_call_params = match &event.item { + CoreTurnItem::DynamicToolCall(item) => Some(DynamicToolCallParams { + thread_id: conversation_id.to_string(), + turn_id: event.turn_id.clone(), + call_id: item.id.clone(), + namespace: item.namespace.clone(), + tool: item.tool.clone(), + arguments: item.arguments.clone(), + }), + _ => None, + }; if should_emit { let notification = item_event_to_server_notification( EventMsg::ItemStarted(event), @@ -1048,6 +1022,15 @@ pub(crate) async fn apply_bespoke_event_handling( ); outgoing.send_server_notification(notification).await; } + if let Some(params) = dynamic_tool_call_params { + let call_id = params.call_id.clone(); + let (_pending_request_id, rx) = outgoing + .send_request(ServerRequestPayload::DynamicToolCall(params)) + .await; + tokio::spawn(async move { + crate::dynamic_tools::on_call_response(call_id, rx, conversation).await; + }); + } } EventMsg::ItemCompleted(event) => { apply_canonical_item_completed_side_effects(&thread_state, &event.item).await; @@ -2185,10 +2168,14 @@ mod tests { use codex_app_server_protocol::AutoReviewDecisionSource; use codex_app_server_protocol::GuardianApprovalReviewStatus; use codex_app_server_protocol::JSONRPCErrorError; + use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::TurnPlanStepStatus; use codex_login::CodexAuth; 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::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; @@ -2205,6 +2192,7 @@ mod tests { use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::GuardianAssessmentEvent; use codex_protocol::protocol::GuardianAssessmentStatus; + use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::RateLimitSnapshot; use codex_protocol::protocol::RateLimitWindow; use codex_protocol::protocol::RolloutItem; @@ -3482,6 +3470,92 @@ mod tests { Ok(()) } + #[tokio::test] + async fn canonical_dynamic_tool_start_emits_item_and_requests_client() -> Result<()> { + let codex_home = TempDir::new()?; + let config = load_default_config_for_test(&codex_home).await; + let thread_manager = Arc::new( + codex_core::test_support::thread_manager_with_models_provider_and_home( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + config.model_provider.clone(), + config.codex_home.to_path_buf(), + Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), + ), + ); + let codex_core::NewThread { + thread_id: conversation_id, + thread: conversation, + .. + } = thread_manager.start_thread(config).await?; + let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); + let outgoing = Arc::new(OutgoingMessageSender::new( + tx, + codex_analytics::AnalyticsEventsClient::disabled(), + )); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + conversation_id, + ); + + apply_bespoke_event_handling( + Event { + id: "turn-1".to_string(), + msg: EventMsg::ItemStarted(ItemStartedEvent { + thread_id: conversation_id, + turn_id: "turn-1".to_string(), + item: CoreTurnItem::DynamicToolCall(DynamicToolCallItem { + id: "dynamic-1".to_string(), + namespace: Some("apps".to_string()), + tool: "lookup".to_string(), + arguments: json!({"id": "123"}), + status: CoreDynamicToolCallStatus::InProgress, + content_items: None, + success: None, + error: None, + duration: None, + }), + started_at_ms: 42, + }), + }, + conversation_id, + conversation, + thread_manager, + outgoing, + new_thread_state(), + ThreadWatchManager::new(), + Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)), + "test-provider".to_string(), + ) + .await; + + let item_started = recv_broadcast_message(&mut rx).await?; + let OutgoingMessage::AppServerNotification(ServerNotification::ItemStarted(payload)) = + item_started + else { + bail!("unexpected message: {item_started:?}"); + }; + assert_eq!(payload.item.id(), "dynamic-1"); + + let request = recv_broadcast_message(&mut rx).await?; + let OutgoingMessage::Request(ServerRequest::DynamicToolCall { params, .. }) = request + else { + bail!("unexpected message: {request:?}"); + }; + assert_eq!( + params, + DynamicToolCallParams { + thread_id: conversation_id.to_string(), + turn_id: "turn-1".to_string(), + call_id: "dynamic-1".to_string(), + namespace: Some("apps".to_string()), + tool: "lookup".to_string(), + arguments: json!({"id": "123"}), + } + ); + Ok(()) + } + #[tokio::test] async fn test_handle_turn_complete_emits_completed_without_error() -> Result<()> { let conversation_id = ThreadId::new(); diff --git a/codex-rs/core/src/tools/handlers/dynamic.rs b/codex-rs/core/src/tools/handlers/dynamic.rs index 28af3434ff..4b8fa03797 100644 --- a/codex-rs/core/src/tools/handlers/dynamic.rs +++ b/codex-rs/core/src/tools/handlers/dynamic.rs @@ -9,14 +9,13 @@ use crate::tools::handlers::parse_arguments; use crate::tools::registry::CoreToolRuntime; use crate::tools::registry::ToolExecutor; use crate::tools::registry::ToolExposure; -use crate::turn_timing::now_unix_timestamp_ms; -use codex_protocol::dynamic_tools::DynamicToolCallRequest; use codex_protocol::dynamic_tools::DynamicToolFunctionSpec; use codex_protocol::dynamic_tools::DynamicToolNamespaceSpec; use codex_protocol::dynamic_tools::DynamicToolResponse; +use codex_protocol::items::DynamicToolCallItem; +use codex_protocol::items::DynamicToolCallStatus; +use codex_protocol::items::TurnItem; use codex_protocol::models::FunctionCallOutputContentItem; -use codex_protocol::protocol::DynamicToolCallResponseEvent; -use codex_protocol::protocol::EventMsg; use codex_tools::ResponsesApiNamespace; use codex_tools::ResponsesApiNamespaceTool; use codex_tools::ToolName; @@ -178,7 +177,6 @@ async fn request_dynamic_tool( ) -> Option { let namespace = tool_name.namespace; let tool = tool_name.name; - let turn_id = turn_context.sub_id.clone(); let (tx_response, rx_response) = oneshot::channel(); let event_id = call_id.clone(); let prev_entry = { @@ -196,45 +194,55 @@ async fn request_dynamic_tool( } let started_at = Instant::now(); - let started_at_ms = now_unix_timestamp_ms(); - let event = EventMsg::DynamicToolCallRequest(DynamicToolCallRequest { - call_id: call_id.clone(), - turn_id: turn_id.clone(), - started_at_ms, - namespace: namespace.clone(), - tool: tool.clone(), - arguments: arguments.clone(), - }); - session.send_event(turn_context, event).await; + session + .emit_turn_item_started( + turn_context, + &TurnItem::DynamicToolCall(DynamicToolCallItem { + id: call_id.clone(), + namespace: namespace.clone(), + tool: tool.clone(), + arguments: arguments.clone(), + status: DynamicToolCallStatus::InProgress, + content_items: None, + success: None, + error: None, + duration: None, + }), + ) + .await; let response = rx_response.await.ok(); - let response_event = match &response { - Some(response) => EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { - call_id, - turn_id, - completed_at_ms: now_unix_timestamp_ms(), + let item = match &response { + Some(response) => DynamicToolCallItem { + id: call_id, namespace, tool, arguments, - content_items: response.content_items.clone(), - success: response.success, + status: if response.success { + DynamicToolCallStatus::Completed + } else { + DynamicToolCallStatus::Failed + }, + content_items: Some(response.content_items.clone()), + success: Some(response.success), error: None, - duration: started_at.elapsed(), - }), - None => EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { - call_id, - turn_id, - completed_at_ms: now_unix_timestamp_ms(), + duration: Some(started_at.elapsed()), + }, + None => DynamicToolCallItem { + id: call_id, namespace, tool, arguments, - content_items: Vec::new(), - success: false, + status: DynamicToolCallStatus::Failed, + content_items: Some(Vec::new()), + success: Some(false), error: Some("dynamic tool call was cancelled before receiving a response".to_string()), - duration: started_at.elapsed(), - }), + duration: Some(started_at.elapsed()), + }, }; - session.send_event(turn_context, response_event).await; + session + .emit_turn_item_completed(turn_context, TurnItem::DynamicToolCall(item)) + .await; response } From 42156ba007278d9068f1518ac1f627b56c136ef6 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Tue, 7 Jul 2026 09:28:52 -0700 Subject: [PATCH 20/79] test(skills): cover plugin namespace loading (#31369) ## Why Before changing plugin namespace loading performance, lock down the existing behavior so the same cases can be validated before and after the optimization. ## What - cover mixed plain and nested plugin skills under one scan root - cover inherited, nested, and invalid-manifest namespace precedence - cover symlinked plugin skill directories, symlinked plain directories, and scan-root ancestor symlinks ## Validation - just test -p codex-core-skills namespace on unmodified main: 12 passed --- codex-rs/core-skills/src/loader_tests.rs | 275 +++++++++++++++++++++++ 1 file changed, 275 insertions(+) diff --git a/codex-rs/core-skills/src/loader_tests.rs b/codex-rs/core-skills/src/loader_tests.rs index 8cd371c9a7..1bdfe39520 100644 --- a/codex-rs/core-skills/src/loader_tests.rs +++ b/codex-rs/core-skills/src/loader_tests.rs @@ -388,6 +388,41 @@ fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { write_skill_metadata_at(skill_dir, contents) } +fn write_plugin_manifest(plugin_root: &Path, contents: &str) { + let manifest_path = plugin_root.join(".codex-plugin/plugin.json"); + fs::create_dir_all(manifest_path.parent().expect("manifest parent")).unwrap(); + fs::write(manifest_path, contents).unwrap(); +} + +async fn load_user_skills_root(root: &Path) -> SkillLoadOutcome { + load_skills_from_roots( + [SkillRoot { + path: root.abs(), + scope: SkillScope::User, + file_system: Arc::clone(&LOCAL_FS), + plugin_id: None, + plugin_namespace: None, + plugin_root: None, + }], + /*plugin_skill_snapshots*/ None, + ) + .await +} + +fn expected_user_skill(path: &Path, name: &str, description: &str) -> SkillMetadata { + SkillMetadata { + name: name.to_string(), + description: description.to_string(), + short_description: None, + interface: None, + dependencies: None, + policy: None, + path_to_skills_md: normalized(path), + scope: SkillScope::User, + plugin_id: None, + } +} + #[tokio::test] async fn loads_skill_dependencies_metadata_from_yaml() { let codex_home = tempfile::tempdir().expect("tempdir"); @@ -1326,6 +1361,246 @@ async fn namespaces_plugin_skills_using_provided_namespace() { ); } +#[tokio::test] +async fn namespaces_nested_plugin_skills_without_namespacing_plain_siblings() { + let root = tempfile::tempdir().expect("tempdir"); + let skills_root = root.path().join("skills"); + let plain_skill_path = + write_skill_at(&skills_root, "plain", "plain-skill", "plain description"); + let plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"nested"}"#); + let plugin_skill_path = write_skill_at( + &plugin_root.join("skills"), + "search", + "plugin-skill", + "plugin description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![ + expected_user_skill( + &plugin_skill_path, + "nested:plugin-skill", + "plugin description" + ), + expected_user_skill(&plain_skill_path, "plain-skill", "plain description"), + ] + ); +} + +#[tokio::test] +async fn inherits_plugin_namespace_from_above_scanned_skills_root() { + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let skill_path = write_skill_at(&skills_root, "search", "search-skill", "search description"); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:search-skill", + "search description", + )] + ); +} + +#[tokio::test] +async fn nearest_valid_nested_plugin_namespace_overrides_outer_namespace() { + let root = tempfile::tempdir().expect("tempdir"); + let outer_plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&outer_plugin_root, r#"{"name":"outer"}"#); + let skills_root = outer_plugin_root.join("skills"); + let nested_plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&nested_plugin_root, r#"{"name":"nested"}"#); + let skill_path = write_skill_at( + &nested_plugin_root.join("skills"), + "search", + "search-skill", + "search description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "nested:search-skill", + "search description", + )] + ); +} + +#[tokio::test] +async fn invalid_nested_plugin_manifest_falls_back_to_outer_namespace() { + let root = tempfile::tempdir().expect("tempdir"); + let outer_plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&outer_plugin_root, r#"{"name":"outer"}"#); + let skills_root = outer_plugin_root.join("skills"); + let nested_plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&nested_plugin_root, "not json"); + let skill_path = write_skill_at( + &nested_plugin_root.join("skills"), + "search", + "search-skill", + "search description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:search-skill", + "search description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn namespaces_skills_in_symlinked_plugin_skills_dir() { + // skills/ + // └── linked-plugin -> shared-plugin/skills/ + // shared-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/search/SKILL.md + let root = tempfile::tempdir().expect("tempdir"); + let shared_plugin_root = tempfile::tempdir().expect("tempdir"); + write_plugin_manifest(shared_plugin_root.path(), r#"{"name":"linked"}"#); + let skill_path = write_skill_at( + &shared_plugin_root.path().join("skills"), + "search", + "search-skill", + "search description", + ); + let skills_root = root.path().join("skills"); + fs::create_dir_all(&skills_root).unwrap(); + symlink_dir( + &shared_plugin_root.path().join("skills"), + &skills_root.join("linked-plugin"), + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "linked:search-skill", + "search description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn does_not_inherit_namespace_for_skills_in_symlinked_plain_dir() { + // outer-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/linked-plain -> plain-root/ + // plain-root/ + // └── search/SKILL.md + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let plain_root = tempfile::tempdir().expect("tempdir"); + let skill_path = write_skill_at( + plain_root.path(), + "search", + "plain-skill", + "plain description", + ); + fs::create_dir_all(&skills_root).unwrap(); + symlink_dir(plain_root.path(), &skills_root.join("linked-plain")); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "plain-skill", + "plain description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn keeps_inherited_namespace_when_symlink_target_is_scan_root_ancestor() { + // temp-root/ + // └── a/b/c/d/e/f/outer-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/ + // ├── root/SKILL.md + // └── link -> temp-root/ + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("a/b/c/d/e/f/outer-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let skill_path = write_skill_at(&skills_root, "root", "root-skill", "root description"); + symlink_dir(root.path(), &skills_root.join("link")); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:root-skill", + "root description", + )] + ); +} + #[tokio::test] async fn plugin_skill_name_length_limit_allows_max_qualified_name() { let root = tempfile::tempdir().expect("tempdir"); From f363ed70cc1c6e2cae15fc1b8711f7e0d7b96cf1 Mon Sep 17 00:00:00 2001 From: malsamiri-oai Date: Tue, 7 Jul 2026 09:47:21 -0700 Subject: [PATCH 21/79] fix(release): add missing Intel V8 signing entitlement (#30953) ## Why Intel macOS release binaries crash on the first Code Mode tool call while V8 creates its code range. The x86_64 V8 allocator later makes a non-`MAP_JIT` reservation executable, which Hardened Runtime rejects when the signature contains only `com.apple.security.cs.allow-jit`. Tracks [SE-8006](https://linear.app/openai/issue/SE-8006/intel-macos-codex-cli-crashes-in-v8-startup-on-gpt-56-sol-tool-calls). Fixes #28390. ## What - add an expanded entitlement profile only for x86_64 `codex` and `codex-app-server`, the release binaries that link V8 - keep arm64 and `codex-responses-api-proxy` on the existing narrower profile - share one fail-closed target/binary selector between signing and final verification - verify the expected Mach-O architecture and exact entitlement dictionary for the signed binary, tar.gz, zstd, package, and DMG copies ## Verification - `just test-github-scripts` (34 tests) - `UV_CACHE_DIR=/private/tmp/codex-uv-cache just fmt-check` - `bash -n .github/scripts/macos-signing/select_codex_entitlements.sh` - `plutil -lint` on both entitlement profiles - parsed `rust-release.yml` as YAML - `git diff --check` - ad-hoc Hardened Runtime signing smoke on an x86_64 Mach-O slice: strict `codesign` verification passed; the Codex profile contained exactly both keys and the proxy profile retained exactly `allow-jit` ## Release validation Run a native Intel smoke of the final Developer ID-signed x86_64 Codex binary through V8 isolate creation before shipping. PR #30849 is diagnostic scaffolding, but its non-sandbox release job currently fails in the harness before V8 starts, so it is not counted as coverage here. --- .../codex-app-server.entitlements.plist | 10 +++++ .../codex-code-mode-host.entitlements.plist | 10 +++++ ...dex-responses-api-proxy.entitlements.plist | 8 ++++ .../macos-signing/codex.entitlements.plist | 2 + .../test_macos_signing_entitlements.py | 37 ++++++++++++++++++ .github/workflows/rust-release.yml | 38 ++++++++++++++----- 6 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 .github/scripts/macos-signing/codex-app-server.entitlements.plist create mode 100644 .github/scripts/macos-signing/codex-code-mode-host.entitlements.plist create mode 100644 .github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist create mode 100644 .github/scripts/test_macos_signing_entitlements.py diff --git a/.github/scripts/macos-signing/codex-app-server.entitlements.plist b/.github/scripts/macos-signing/codex-app-server.entitlements.plist new file mode 100644 index 0000000000..26b12f2886 --- /dev/null +++ b/.github/scripts/macos-signing/codex-app-server.entitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist b/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist new file mode 100644 index 0000000000..26b12f2886 --- /dev/null +++ b/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist b/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist new file mode 100644 index 0000000000..d35e43ae58 --- /dev/null +++ b/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist @@ -0,0 +1,8 @@ + + + + + com.apple.security.cs.allow-jit + + + diff --git a/.github/scripts/macos-signing/codex.entitlements.plist b/.github/scripts/macos-signing/codex.entitlements.plist index d35e43ae58..26b12f2886 100644 --- a/.github/scripts/macos-signing/codex.entitlements.plist +++ b/.github/scripts/macos-signing/codex.entitlements.plist @@ -4,5 +4,7 @@ com.apple.security.cs.allow-jit + com.apple.security.cs.allow-unsigned-executable-memory + diff --git a/.github/scripts/test_macos_signing_entitlements.py b/.github/scripts/test_macos_signing_entitlements.py new file mode 100644 index 0000000000..e56d5f3a1b --- /dev/null +++ b/.github/scripts/test_macos_signing_entitlements.py @@ -0,0 +1,37 @@ +import plistlib +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +SIGNING_DIR = ROOT / ".github" / "scripts" / "macos-signing" +ALLOW_JIT = "com.apple.security.cs.allow-jit" +ALLOW_UNSIGNED_EXECUTABLE_MEMORY = ( + "com.apple.security.cs.allow-unsigned-executable-memory" +) + + +class MacosSigningEntitlementsTest(unittest.TestCase): + def load(self, binary: str) -> dict[str, bool]: + path = SIGNING_DIR / f"{binary}.entitlements.plist" + with path.open("rb") as file: + return plistlib.load(file) + + def test_v8_binaries_allow_unsigned_executable_memory(self) -> None: + expected = { + ALLOW_JIT: True, + ALLOW_UNSIGNED_EXECUTABLE_MEMORY: True, + } + for binary in ["codex", "codex-app-server", "codex-code-mode-host"]: + with self.subTest(binary=binary): + self.assertEqual(self.load(binary), expected) + + def test_responses_proxy_keeps_existing_entitlements(self) -> None: + self.assertEqual( + self.load("codex-responses-api-proxy"), + {ALLOW_JIT: True}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 93f03e63d1..9fdd66637b 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -573,6 +573,12 @@ jobs: zstd -d --stdout "$unsigned_path" >"$signed_path" chmod 0755 "$signed_path" + entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/${binary}.entitlements.plist" + if [[ ! -f "$entitlements" ]]; then + echo "Entitlements file $entitlements not found" + exit 1 + fi + .github/scripts/macos-signing/sign_macos_code.sh \ --target "$signed_path" \ --identity unused \ @@ -580,7 +586,7 @@ jobs: --identifier "$binary" \ --options runtime \ --timestamp true \ - --entitlements .github/scripts/macos-signing/codex.entitlements.plist + --entitlements "$entitlements" mkdir -p "${report_dir}/${binary}" rcodesign print-signature-info "$signed_path" \ @@ -974,15 +980,29 @@ jobs: target="${{ matrix.target }}" packaged_dir="dist/${target}" - expected_entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/codex.entitlements.plist" + case "$target" in + aarch64-apple-darwin) expected_arch="arm64" ;; + x86_64-apple-darwin) expected_arch="x86_64" ;; + *) + echo "Unexpected macOS target: $target" + exit 1 + ;; + esac verify_signed_binary() { local path="$1" - local actual_entitlements normalized_actual normalized_expected + local binary="$2" + local actual_entitlements expected_entitlements normalized_actual normalized_expected chmod 0755 "$path" + lipo "$path" -verify_arch "$expected_arch" codesign --verify --strict --verbose=2 "$path" + expected_entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/${binary}.entitlements.plist" + if [[ ! -f "$expected_entitlements" ]]; then + echo "Expected entitlements file $expected_entitlements not found" + exit 1 + fi actual_entitlements="$(mktemp)" normalized_actual="$(mktemp)" normalized_expected="$(mktemp)" @@ -995,7 +1015,7 @@ jobs: for binary in ${{ matrix.binaries }}; do binary_path="${RUNNER_TEMP}/signed-binaries/${binary}" - verify_signed_binary "$binary_path" + verify_signed_binary "$binary_path" "$binary" # The app-server package contains the host, but its standalone archives # are omitted above to avoid duplicate release asset names. @@ -1007,11 +1027,11 @@ jobs: rm -rf "$direct_archive_dir" mkdir -p "$direct_archive_dir" tar -xzf "${packaged_dir}/${binary}-${target}.tar.gz" -C "$direct_archive_dir" - verify_signed_binary "${direct_archive_dir}/${binary}-${target}" + verify_signed_binary "${direct_archive_dir}/${binary}-${target}" "$binary" direct_zstd_path="${RUNNER_TEMP}/${binary}-${target}-from-zstd" zstd -d --stdout "${packaged_dir}/${binary}-${target}.zst" >"$direct_zstd_path" - verify_signed_binary "$direct_zstd_path" + verify_signed_binary "$direct_zstd_path" "$binary" done case "${{ matrix.bundle }}" in @@ -1033,8 +1053,8 @@ jobs: rm -rf "$package_dir" mkdir -p "$package_dir" tar -xzf "${packaged_dir}/${package_stem}-${target}.tar.gz" -C "$package_dir" - verify_signed_binary "${package_dir}/bin/${package_entrypoint}" - verify_signed_binary "${package_dir}/bin/codex-code-mode-host" + verify_signed_binary "${package_dir}/bin/${package_entrypoint}" "$package_entrypoint" + verify_signed_binary "${package_dir}/bin/codex-code-mode-host" "codex-code-mode-host" if [[ "${{ matrix.verify_dmg }}" != "true" ]]; then exit 0 @@ -1060,7 +1080,7 @@ jobs: trap cleanup_mount EXIT for binary in ${{ matrix.binaries }}; do - verify_signed_binary "${mount_dir}/${binary}" + verify_signed_binary "${mount_dir}/${binary}" "$binary" done cleanup_mount From a3f8b0b33284054133474e7b1cc5fa7600221d97 Mon Sep 17 00:00:00 2001 From: lt-oai Date: Tue, 7 Jul 2026 09:47:41 -0700 Subject: [PATCH 22/79] refactor: make ExternalAuth return CodexAuth (#31355) ## Summary - refactor `ExternalAuth` to return `CodexAuth` directly - remove the parallel `ExternalAuthTokens` wrapper - preserve existing external bearer and app-server refresh behavior This is a mechanical precursor refactor; it does not add auth capabilities or change recovery behavior. ## Testing - `cargo fmt --all` - `cargo test -q -p codex-login --lib` - `cargo test -q -p codex-app-server --test all external_auth_refreshes_on_unauthorized` --- codex-rs/app-server/src/message_processor.rs | 19 ++- codex-rs/login/src/auth/auth_tests.rs | 13 -- codex-rs/login/src/auth/external_bearer.rs | 24 ++-- codex-rs/login/src/auth/manager.rs | 134 ++++++++----------- codex-rs/login/src/lib.rs | 2 - codex-rs/models-manager/src/manager_tests.rs | 19 +-- 6 files changed, 76 insertions(+), 135 deletions(-) diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 6ae73784ff..29ace7d99f 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -74,10 +74,10 @@ use codex_feedback::CodexFeedback; use codex_goal_extension::GoalService; use codex_home::CodexHomeUserInstructionsProvider; use codex_login::AuthManager; +use codex_login::CodexAuth; use codex_login::auth::ExternalAuth; use codex_login::auth::ExternalAuthRefreshContext; use codex_login::auth::ExternalAuthRefreshReason; -use codex_login::auth::ExternalAuthTokens; use codex_protocol::ThreadId; use codex_protocol::auth::AuthMode as LoginAuthMode; use codex_protocol::protocol::SessionSource; @@ -121,10 +121,7 @@ impl ExternalAuthRefreshBridge { } } - async fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> std::io::Result { + async fn refresh(&self, context: ExternalAuthRefreshContext) -> std::io::Result { let params = ChatgptAuthTokensRefreshParams { reason: Self::map_reason(context.reason), previous_account_id: context.previous_account_id, @@ -162,11 +159,11 @@ impl ExternalAuthRefreshBridge { let response: ChatgptAuthTokensRefreshResponse = serde_json::from_value(result).map_err(std::io::Error::other)?; - Ok(ExternalAuthTokens::chatgpt( - response.access_token, - response.chatgpt_account_id, - response.chatgpt_plan_type, - )) + CodexAuth::from_external_chatgpt_tokens( + response.access_token.as_str(), + response.chatgpt_account_id.as_str(), + response.chatgpt_plan_type.as_deref(), + ) } } @@ -178,7 +175,7 @@ impl ExternalAuth for ExternalAuthRefreshBridge { fn refresh( &self, context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { Box::pin(ExternalAuthRefreshBridge::refresh(self, context)) } } diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index 9509cab456..77d8c4fdfb 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -1015,19 +1015,6 @@ async fn refresh_failure_is_scoped_to_the_matching_auth_snapshot() { assert_eq!(manager.refresh_failure_for_auth(&updated_auth), None); } -#[test] -fn external_auth_tokens_without_chatgpt_metadata_cannot_seed_chatgpt_auth() { - let err = AuthDotJson::from_external_tokens(&ExternalAuthTokens::access_token_only( - "test-access-token", - )) - .expect_err("bearer-only external auth should not seed ChatGPT auth"); - - assert_eq!( - err.to_string(), - "external auth tokens are missing ChatGPT metadata" - ); -} - #[tokio::test] async fn external_bearer_only_auth_manager_uses_cached_provider_token() { let script = ProviderAuthScript::new(&["provider-token", "next-token"]).unwrap(); diff --git a/codex-rs/login/src/auth/external_bearer.rs b/codex-rs/login/src/auth/external_bearer.rs index f30d52f434..1dbd2c3eee 100644 --- a/codex-rs/login/src/auth/external_bearer.rs +++ b/codex-rs/login/src/auth/external_bearer.rs @@ -1,7 +1,7 @@ +use super::manager::CodexAuth; use super::manager::ExternalAuth; use super::manager::ExternalAuthFuture; use super::manager::ExternalAuthRefreshContext; -use super::manager::ExternalAuthTokens; use codex_protocol::auth::AuthMode; use codex_protocol::config_types::ModelProviderAuthInfo; use std::fmt; @@ -30,7 +30,7 @@ impl BearerTokenRefresher { clippy::await_holding_invalid_type, reason = "external bearer cache misses intentionally hold cached_token across the provider command to avoid duplicate refreshes" )] - async fn resolve(&self) -> io::Result> { + async fn resolve(&self) -> io::Result> { let access_token = { let mut cached = self.state.cached_token.lock().await; if let Some(cached_token) = cached.as_ref() { @@ -39,8 +39,8 @@ impl BearerTokenRefresher { None => true, }; if should_use_cached_token { - return Ok(Some(ExternalAuthTokens::access_token_only( - cached_token.access_token.clone(), + return Ok(Some(CodexAuth::from_api_key( + cached_token.access_token.as_str(), ))); } } @@ -52,20 +52,17 @@ impl BearerTokenRefresher { }); access_token }; - Ok(Some(ExternalAuthTokens::access_token_only(access_token))) + Ok(Some(CodexAuth::from_api_key(access_token.as_str()))) } - async fn refresh( - &self, - _context: ExternalAuthRefreshContext, - ) -> io::Result { + async fn refresh(&self, _context: ExternalAuthRefreshContext) -> io::Result { let access_token = run_provider_auth_command(&self.state.config).await?; let mut cached = self.state.cached_token.lock().await; *cached = Some(CachedExternalBearerToken { access_token: access_token.clone(), fetched_at: Instant::now(), }); - Ok(ExternalAuthTokens::access_token_only(access_token)) + Ok(CodexAuth::from_api_key(access_token.as_str())) } } @@ -74,14 +71,11 @@ impl ExternalAuth for BearerTokenRefresher { AuthMode::ApiKey } - fn resolve(&self) -> ExternalAuthFuture<'_, Option> { + fn resolve(&self) -> ExternalAuthFuture<'_, Option> { Box::pin(BearerTokenRefresher::resolve(self)) } - fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> ExternalAuthFuture<'_, ExternalAuthTokens> { + fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { Box::pin(BearerTokenRefresher::refresh(self, context)) } } diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index a2d005dfa6..06d125422c 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -198,45 +198,6 @@ pub enum RefreshTokenError { Transient(#[from] std::io::Error), } -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ExternalAuthTokens { - pub access_token: String, - pub chatgpt_metadata: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ExternalAuthChatgptMetadata { - pub account_id: String, - pub plan_type: Option, -} - -impl ExternalAuthTokens { - pub fn access_token_only(access_token: impl Into) -> Self { - Self { - access_token: access_token.into(), - chatgpt_metadata: None, - } - } - - pub fn chatgpt( - access_token: impl Into, - chatgpt_account_id: impl Into, - chatgpt_plan_type: Option, - ) -> Self { - Self { - access_token: access_token.into(), - chatgpt_metadata: Some(ExternalAuthChatgptMetadata { - account_id: chatgpt_account_id.into(), - plan_type: chatgpt_plan_type, - }), - } - } - - pub fn chatgpt_metadata(&self) -> Option<&ExternalAuthChatgptMetadata> { - self.chatgpt_metadata.as_ref() - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExternalAuthRefreshReason { Unauthorized, @@ -251,22 +212,19 @@ pub struct ExternalAuthRefreshContext { /// Pluggable auth provider used by `AuthManager` for externally managed auth flows. /// /// Implementations may either resolve auth eagerly via `resolve()` or provide refreshed -/// credentials on demand via `refresh()`. +/// auth on demand via `refresh()`. pub trait ExternalAuth: Send + Sync { /// Indicates which top-level auth mode this external provider supplies. fn auth_mode(&self) -> AuthMode; /// Returns cached or immediately available auth, if this provider can resolve it synchronously /// from the caller's perspective. - fn resolve(&self) -> ExternalAuthFuture<'_, Option> { + fn resolve(&self) -> ExternalAuthFuture<'_, Option> { Box::pin(async { Ok(None) }) } /// Refreshes auth in response to a manager-driven refresh attempt. - fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> ExternalAuthFuture<'_, ExternalAuthTokens>; + fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth>; } pub type ExternalAuthFuture<'a, T> = Pin> + Send + 'a>>; @@ -747,6 +705,24 @@ impl CodexAuth { Self::Chatgpt(ChatgptAuth { state, storage }) } + /// Constructs in-memory ChatGPT auth from externally managed tokens. + pub fn from_external_chatgpt_tokens( + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, + ) -> std::io::Result { + let auth_dot_json = AuthDotJson::from_external_access_token( + access_token, + chatgpt_account_id, + chatgpt_plan_type, + )?; + let state = ChatgptAuthState { + auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), + client: create_client(), + }; + Ok(Self::ChatgptAuthTokens(ChatgptAuthTokens { state })) + } + pub fn from_api_key(api_key: &str) -> Self { Self::ApiKey(ApiKeyAuth { api_key: api_key.to_owned(), @@ -1456,26 +1432,23 @@ fn refresh_token_endpoint() -> String { } impl AuthDotJson { - fn from_external_tokens(external: &ExternalAuthTokens) -> std::io::Result { - let Some(chatgpt_metadata) = external.chatgpt_metadata() else { - return Err(std::io::Error::other( - "external auth tokens are missing ChatGPT metadata", - )); - }; + fn from_external_access_token( + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, + ) -> std::io::Result { let mut token_info = - parse_chatgpt_jwt_claims(&external.access_token).map_err(std::io::Error::other)?; - token_info.chatgpt_account_id = Some(chatgpt_metadata.account_id.clone()); - token_info.chatgpt_plan_type = chatgpt_metadata - .plan_type - .as_deref() + parse_chatgpt_jwt_claims(access_token).map_err(std::io::Error::other)?; + token_info.chatgpt_account_id = Some(chatgpt_account_id.to_string()); + token_info.chatgpt_plan_type = chatgpt_plan_type .map(InternalPlanType::from_raw_value) .or(token_info.chatgpt_plan_type) .or(Some(InternalPlanType::Unknown("unknown".to_string()))); let tokens = TokenData { id_token: token_info, - access_token: external.access_token.clone(), + access_token: access_token.to_string(), refresh_token: String::new(), - account_id: Some(chatgpt_metadata.account_id.clone()), + account_id: Some(chatgpt_account_id.to_string()), }; Ok(Self { @@ -1489,19 +1462,6 @@ impl AuthDotJson { }) } - fn from_external_access_token( - access_token: &str, - chatgpt_account_id: &str, - chatgpt_plan_type: Option<&str>, - ) -> std::io::Result { - let external = ExternalAuthTokens::chatgpt( - access_token, - chatgpt_account_id, - chatgpt_plan_type.map(str::to_string), - ); - Self::from_external_tokens(&external) - } - pub(super) fn resolved_mode(&self) -> AuthMode { if let Some(mode) = self.auth_mode { return mode; @@ -2361,7 +2321,14 @@ impl AuthManager { let external_auth = self.external_auth()?; match external_auth.resolve().await { - Ok(Some(tokens)) => Some(CodexAuth::from_api_key(&tokens.access_token)), + Ok(Some(auth)) if auth.api_auth_mode() == AuthMode::ApiKey => Some(auth), + Ok(Some(auth)) => { + tracing::error!( + resolved_mode = ?auth.api_auth_mode(), + "ignoring non-API-key auth from external API key provider" + ); + None + } Ok(None) => None, Err(err) => { tracing::error!("Failed to resolve external API key auth: {err}"); @@ -2567,23 +2534,30 @@ impl AuthManager { if external_auth.auth_mode() == AuthMode::ApiKey { return Ok(()); } - let Some(chatgpt_metadata) = refreshed.chatgpt_metadata() else { + if refreshed.api_auth_mode() != AuthMode::ChatgptAuthTokens { return Err(RefreshTokenError::Transient(std::io::Error::other( - "external auth refresh did not return ChatGPT metadata", + "external auth refresh did not return ChatGPT auth tokens", ))); - }; + } + let account_id = refreshed.get_account_id().ok_or_else(|| { + RefreshTokenError::Transient(std::io::Error::other( + "external ChatGPT auth tokens are missing an account id", + )) + })?; if let Some(expected_workspace_ids) = forced_chatgpt_workspace_id.as_deref() - && !expected_workspace_ids.contains(&chatgpt_metadata.account_id) + && !expected_workspace_ids.contains(&account_id) { return Err(RefreshTokenError::Transient(std::io::Error::other( format!( - "external auth refresh returned workspace {:?}, expected one of {:?}", - chatgpt_metadata.account_id, expected_workspace_ids, + "external auth refresh returned workspace {account_id:?}, expected one of {expected_workspace_ids:?}" ), ))); } - let auth_dot_json = - AuthDotJson::from_external_tokens(&refreshed).map_err(RefreshTokenError::Transient)?; + let auth_dot_json = refreshed.get_current_auth_json().ok_or_else(|| { + RefreshTokenError::Transient(std::io::Error::other( + "external ChatGPT auth tokens are missing auth state", + )) + })?; save_auth( &self.codex_home, &auth_dot_json, diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 7ea415fcc5..8a08ddeadb 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -30,11 +30,9 @@ pub use auth::CODEX_ACCESS_TOKEN_ENV_VAR; pub use auth::CODEX_API_KEY_ENV_VAR; pub use auth::CodexAuth; pub use auth::ExternalAuth; -pub use auth::ExternalAuthChatgptMetadata; pub use auth::ExternalAuthFuture; pub use auth::ExternalAuthRefreshContext; pub use auth::ExternalAuthRefreshReason; -pub use auth::ExternalAuthTokens; pub use auth::OPENAI_API_KEY_ENV_VAR; pub use auth::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; pub use auth::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR; diff --git a/codex-rs/models-manager/src/manager_tests.rs b/codex-rs/models-manager/src/manager_tests.rs index e7d1691a3a..2e97dfac43 100644 --- a/codex-rs/models-manager/src/manager_tests.rs +++ b/codex-rs/models-manager/src/manager_tests.rs @@ -7,7 +7,6 @@ use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::ExternalAuth; use codex_login::ExternalAuthRefreshContext; -use codex_login::ExternalAuthTokens; use codex_login::TokenData; use codex_protocol::auth::AuthMode; use codex_protocol::openai_models::ModelsResponse; @@ -122,23 +121,15 @@ impl ExternalAuth for TestExternalApiKeyAuth { AuthMode::ApiKey } - fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, Option> { - Box::pin(async { - Ok(Some(ExternalAuthTokens::access_token_only( - "test-external-api-key", - ))) - }) + fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, Option> { + Box::pin(async { Ok(Some(CodexAuth::from_api_key("test-external-api-key"))) }) } fn refresh( &self, _context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { - Box::pin(async { - Ok(ExternalAuthTokens::access_token_only( - "test-external-api-key", - )) - }) + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { + Box::pin(async { Ok(CodexAuth::from_api_key("test-external-api-key")) }) } } @@ -153,7 +144,7 @@ impl ExternalAuth for TestUnresolvedExternalApiKeyAuth { fn refresh( &self, _context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { Box::pin(async { Err(std::io::Error::other("unresolved test auth")) }) } } From 8841f506c07ccdb773ca012f2271b852c43fbf52 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Tue, 7 Jul 2026 09:55:27 -0700 Subject: [PATCH 23/79] ci: increase Windows Bazel local test jobs (#31352) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why Windows Bazel test shards currently cap local test actions at 4. Controlled forced-test-execution measurements in #31339 found that 8 local jobs reduced Bazel elapsed time on every shard by 19–29%, including the slow shard from 835.5s to 609.3s, while 12 jobs regressed. ## What Set `common:ci-windows-cross --local_test_jobs=8` in `.bazelrc`. ## Manual validation - `git diff --check` - `just fmt` - [8-job CI experiment](https://github.com/openai/codex/actions/runs/28838387129) --- .bazelrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.bazelrc b/.bazelrc index de01a87443..93fcb0c164 100644 --- a/.bazelrc +++ b/.bazelrc @@ -190,7 +190,7 @@ common:ci-windows-cross --strategy=TestRunner=local # V8 embeds IsolateData offsets in snapshot builtins; Windows snapshots must be # generated by a Windows mksnapshot binary rather than the Linux RBE host tool. common:ci-windows-cross --strategy=V8Mksnapshot=local -common:ci-windows-cross --local_test_jobs=4 +common:ci-windows-cross --local_test_jobs=8 common:ci-windows-cross --test_env=RUST_TEST_THREADS=1 # Native Windows CI still covers the PowerShell parser-process tests. The # cross-built gnullvm binaries currently hang in those tests when run on the From f6e251c3ac6573a4d6eccddea6ad12587868485f Mon Sep 17 00:00:00 2001 From: Alex Zamoshchin Date: Tue, 7 Jul 2026 13:13:59 -0400 Subject: [PATCH 24/79] [codex-rs] Add writes app approval mode (#30482) ## Summary - Adds `writes` to `AppToolApproval` and exposes it through config and app-server schemas, including `[apps._default].default_tools_approval_mode`. - In `writes`, tools with `readOnlyHint = true` skip approval; all other tools prompt, including non-destructive writes and tools without annotations. - Prevents session or persistent approval choices in this mode so later writes still prompt. ## Why `auto` only prompts for risk-hinted actions, while `prompt` also interrupts reads. Apps need a middle mode that gates writes without prompting for declared read-only actions. ## Validation - `just write-config-schema` - `just write-app-server-schema` - `just fmt` - `just test -p codex-core mcp_turn_metadata` (4 passed) - `just test -p codex-core writes_mode` (2 passed) - `just test -p codex-app-server config_read_includes_apps` (1 passed) - `just test -p codex-app-server-protocol` (251 passed) - `just test -p codex-config` (200 passed) - `just test -p codex-cli` (300 passed) - `just fix -p codex-core -p codex-config -p codex-app-server-protocol -p codex-app-server -p codex-cli` --- .../codex_app_server_protocol.schemas.json | 1 + .../codex_app_server_protocol.v2.schemas.json | 1 + .../schema/json/v2/ConfigReadResponse.json | 1 + .../schema/typescript/v2/AppToolApproval.ts | 2 +- .../src/protocol/v2/config.rs | 1 + codex-rs/app-server/README.md | 4 +- .../app-server/tests/suite/v2/config_rpc.rs | 4 +- codex-rs/cli/src/mcp_cmd.rs | 1 + codex-rs/config/src/mcp_edit.rs | 2 + codex-rs/config/src/mcp_types.rs | 1 + codex-rs/core/config.schema.json | 1 + .../core/src/config/edit/document_helpers.rs | 2 + codex-rs/core/src/mcp_tool_call.rs | 30 +++-- codex-rs/core/src/mcp_tool_call_tests.rs | 46 +++++-- .../core/tests/suite/mcp_turn_metadata.rs | 124 ++++++++++++++++++ 15 files changed, 198 insertions(+), 23 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 2ffff2f96f..53bd7cef4e 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -6728,6 +6728,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index dc6e2c9693..11540d40c7 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -854,6 +854,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 16f8363416..19863dd1f3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -78,6 +78,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts index e92cd8e28b..6704ef0fde 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type AppToolApproval = "auto" | "prompt" | "approve"; +export type AppToolApproval = "auto" | "prompt" | "writes" | "approve"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index f615b25d44..24d574a935 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -163,6 +163,7 @@ pub struct AnalyticsConfig { pub enum AppToolApproval { Auto, Prompt, + Writes, Approve, } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 8300c70d94..d52f1bd168 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1879,7 +1879,9 @@ review when allowed by configuration requirements. Use `apps._default.default_tools_approval_mode` to set the approval mode for tools without a per-app or per-tool override. Supported values are `"auto"`, -`"prompt"`, and `"approve"`. Tool-level `approval_mode` takes precedence over +`"prompt"`, `"writes"`, and `"approve"`. The `"writes"` mode prompts for tools +that do not advertise `readOnlyHint = true` and skips declared read-only tools. +Tool-level `approval_mode` takes precedence over the per-app `default_tools_approval_mode`, which takes precedence over the `apps._default` value. Managed tool requirements take precedence over all of these settings. When none are configured, the mode defaults to `"auto"`. diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index 07b8ccc2e8..945ab16d7e 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -400,7 +400,7 @@ async fn config_read_includes_apps() -> Result<()> { r#" [apps._default] approvals_reviewer = "auto_review" -default_tools_approval_mode = "approve" +default_tools_approval_mode = "writes" [apps.app1] enabled = false @@ -440,7 +440,7 @@ default_tools_approval_mode = "prompt" approvals_reviewer: Some(ApprovalsReviewer::AutoReview), destructive_enabled: true, open_world_enabled: true, - default_tools_approval_mode: Some(AppToolApproval::Approve), + default_tools_approval_mode: Some(AppToolApproval::Writes), }), apps: std::collections::HashMap::from([( "app1".to_string(), diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index fd0b1a0e4f..848180a517 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -963,6 +963,7 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; println!(" default_tools_approval_mode: {approval_mode}"); diff --git a/codex-rs/config/src/mcp_edit.rs b/codex-rs/config/src/mcp_edit.rs index 16b3904917..ef0d8eae48 100644 --- a/codex-rs/config/src/mcp_edit.rs +++ b/codex-rs/config/src/mcp_edit.rs @@ -198,6 +198,7 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { entry["default_tools_approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } @@ -242,6 +243,7 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { tool_entry["approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } diff --git a/codex-rs/config/src/mcp_types.rs b/codex-rs/config/src/mcp_types.rs index 550de84a0c..7043e0cb69 100644 --- a/codex-rs/config/src/mcp_types.rs +++ b/codex-rs/config/src/mcp_types.rs @@ -22,6 +22,7 @@ pub enum AppToolApproval { #[default] Auto, Prompt, + Writes, Approve, } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 0a48882b09..fb4d8740ba 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -150,6 +150,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/core/src/config/edit/document_helpers.rs b/codex-rs/core/src/config/edit/document_helpers.rs index 308eb9922f..871ca0e41e 100644 --- a/codex-rs/core/src/config/edit/document_helpers.rs +++ b/codex-rs/core/src/config/edit/document_helpers.rs @@ -121,6 +121,7 @@ fn serialize_mcp_server_table(config: &McpServerConfig) -> TomlTable { entry["default_tools_approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } @@ -173,6 +174,7 @@ fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> TomlItem { entry["approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index d03f232d12..63d21504b9 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1223,8 +1223,7 @@ async fn maybe_request_mcp_tool_approval( } let annotations = metadata.and_then(|metadata| metadata.annotations.as_ref()); - let approval_required = requires_mcp_tool_approval(annotations); - if !approval_required && approval_mode != AppToolApproval::Prompt { + if !requires_mcp_tool_approval_for_mode(annotations, approval_mode) { return None; } @@ -1927,12 +1926,13 @@ fn normalize_approval_decision_for_mode( decision: McpToolApprovalDecision, approval_mode: AppToolApproval, ) -> McpToolApprovalDecision { - if approval_mode == AppToolApproval::Prompt - && matches!( - decision, - McpToolApprovalDecision::AcceptForSession | McpToolApprovalDecision::AcceptAndRemember - ) - { + if matches!( + approval_mode, + AppToolApproval::Prompt | AppToolApproval::Writes + ) && matches!( + decision, + McpToolApprovalDecision::AcceptForSession | McpToolApprovalDecision::AcceptAndRemember + ) { McpToolApprovalDecision::Accept } else { decision @@ -2179,6 +2179,20 @@ fn requires_mcp_tool_approval(annotations: Option<&ToolAnnotations>) -> bool { .unwrap_or(true) } +fn requires_mcp_tool_approval_for_mode( + annotations: Option<&ToolAnnotations>, + approval_mode: AppToolApproval, +) -> bool { + match approval_mode { + AppToolApproval::Auto => requires_mcp_tool_approval(annotations), + AppToolApproval::Prompt => true, + AppToolApproval::Writes => !annotations + .and_then(|annotations| annotations.read_only_hint) + .unwrap_or(false), + AppToolApproval::Approve => false, + } +} + async fn notify_mcp_tool_call_skip( sess: &Session, turn_context: &TurnContext, diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index f68d32ff4e..336eecbfdf 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -398,23 +398,47 @@ fn approval_not_required_when_read_only_and_other_hints_are_absent() { } #[test] -fn prompt_mode_does_not_allow_persistent_remember() { +fn writes_mode_requires_approval_for_non_read_only_tools() { + let annotations = annotations(Some(false), Some(false), Some(false)); assert_eq!( - normalize_approval_decision_for_mode( - McpToolApprovalDecision::AcceptForSession, - AppToolApproval::Prompt, - ), - McpToolApprovalDecision::Accept + requires_mcp_tool_approval_for_mode(Some(&annotations), AppToolApproval::Writes), + true ); assert_eq!( - normalize_approval_decision_for_mode( - McpToolApprovalDecision::AcceptAndRemember, - AppToolApproval::Prompt, - ), - McpToolApprovalDecision::Accept + requires_mcp_tool_approval_for_mode(/*annotations*/ None, AppToolApproval::Writes), + true ); } +#[test] +fn writes_mode_does_not_require_approval_for_read_only_tools() { + let annotations = annotations(Some(true), Some(true), Some(true)); + assert_eq!( + requires_mcp_tool_approval_for_mode(Some(&annotations), AppToolApproval::Writes), + false + ); +} + +#[test] +fn prompting_modes_do_not_allow_persistent_remember() { + for approval_mode in [AppToolApproval::Prompt, AppToolApproval::Writes] { + assert_eq!( + normalize_approval_decision_for_mode( + McpToolApprovalDecision::AcceptForSession, + approval_mode, + ), + McpToolApprovalDecision::Accept + ); + assert_eq!( + normalize_approval_decision_for_mode( + McpToolApprovalDecision::AcceptAndRemember, + approval_mode, + ), + McpToolApprovalDecision::Accept + ); + } +} + #[tokio::test] async fn mcp_tool_call_span_records_expected_fields() { let buffer: &'static std::sync::Mutex> = diff --git a/codex-rs/core/tests/suite/mcp_turn_metadata.rs b/codex-rs/core/tests/suite/mcp_turn_metadata.rs index 0d403180d7..0ecaa80274 100644 --- a/codex-rs/core/tests/suite/mcp_turn_metadata.rs +++ b/codex-rs/core/tests/suite/mcp_turn_metadata.rs @@ -20,6 +20,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::PathExt; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL; +use core_test_support::apps_test_server::SEARCH_CALENDAR_LIST_TOOL; use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE; use core_test_support::apps_test_server::recorded_apps_tool_call_by_call_id; use core_test_support::apps_test_server::search_capable_apps_builder; @@ -45,6 +46,7 @@ fn set_calendar_approval_mode(config: &mut Config, approval_mode: AppToolApprova let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; let user_config_path = config.codex_home.join("config.toml").abs(); @@ -68,6 +70,7 @@ fn set_default_app_approval_mode_and_reviewer( let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; let user_config_path = config.codex_home.join("config.toml").abs(); @@ -333,6 +336,127 @@ async fn apps_default_prompt_with_auto_review_routes_actual_mcp_approval_to_guar Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apps_default_writes_prompts_for_writes_but_not_reads() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let apps_server = AppsTestServer::mount(&server).await?; + let read_call_id = "calendar-read"; + let write_call_id = "calendar-write"; + let list_args = serde_json::to_string(&json!({}))?; + let create_args = serde_json::to_string(&json!({ + "title": "Lunch", + "starts_at": "2026-03-10T12:00:00Z" + }))?; + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-read"), + ev_function_call_with_namespace( + read_call_id, + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_LIST_TOOL, + &list_args, + ), + ev_completed("resp-read"), + ]), + sse(vec![ + ev_response_created("resp-write"), + ev_function_call_with_namespace( + write_call_id, + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_CREATE_TOOL, + &create_args, + ), + ev_completed("resp-write"), + ]), + sse(vec![ + ev_response_created("resp-done"), + ev_assistant_message("msg-done", "done"), + ev_completed("resp-done"), + ]), + ], + ) + .await; + + let mut builder = search_capable_apps_builder(apps_server.chatgpt_base_url.clone()) + .with_config(|config| { + config + .features + .enable(Feature::ToolCallMcpElicitation) + .expect("test config should allow feature update"); + set_default_app_approval_mode_and_reviewer( + config, + AppToolApproval::Writes, + ApprovalsReviewer::User, + ); + }); + let test = builder.build(&server).await?; + + submit_user_turn( + &test, + "Use [$calendar](app://calendar) to list events, then create one.", + AskForApproval::OnRequest, + /*collaboration_mode*/ None, + ) + .await?; + + let EventMsg::McpToolCallBegin(read_begin) = wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::McpToolCallBegin(_)) + }) + .await + else { + unreachable!("event guard guarantees McpToolCallBegin"); + }; + assert_eq!(read_begin.call_id, read_call_id); + + let next_route = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::McpToolCallBegin(_) | EventMsg::ElicitationRequest(_) + ) + }) + .await; + let EventMsg::McpToolCallBegin(write_begin) = next_route else { + panic!("read-only app action should not prompt in writes mode"); + }; + assert_eq!(write_begin.call_id, write_call_id); + + let EventMsg::ElicitationRequest(request) = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::ElicitationRequest(_) | EventMsg::TurnComplete(_) + ) + }) + .await + else { + panic!("write app action should prompt in writes mode"); + }; + + test.codex + .submit(Op::ResolveElicitation { + server_name: request.server_name, + request_id: request.id, + decision: ElicitationAction::Accept, + content: None, + meta: None, + }) + .await?; + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + assert_eq!(responses.requests().len(), 3); + recorded_apps_tool_call_by_call_id(&server, read_call_id).await; + recorded_apps_tool_call_by_call_id(&server, write_call_id).await; + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn mcp_tool_call_metadata_records_prior_request_user_input_tool() -> Result<()> { skip_if_no_network!(Ok(())); From 78df1237d1a7a3b5d9d383acffbf7d3664b5acc7 Mon Sep 17 00:00:00 2001 From: Francis Chalissery Date: Tue, 7 Jul 2026 10:33:42 -0700 Subject: [PATCH 25/79] Handle bio policy errors in Codex (#31439) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Treat streamed Responses `bio_policy` failures as terminal invalid requests instead of retryable stream errors. - Recognize the new biology policy code and message in the TUI while preserving the legacy `invalid_prompt` contract. - Keep the existing dedicated biology safety notice and add regression/snapshot coverage for all supported error shapes. ## Why [openai/openai#1068559](https://github.com/openai/openai/pull/1068559) gates a Responses API contract change from `invalid_prompt` and the legacy message to `bio_policy` and new biology copy. Without this compatibility change, streamed blocks are retried as transient failures and the OSS TUI falls back to a generic/raw error instead of the dedicated safety notice. ## Validation - `just test -p codex-api` — 137 passed - `just test -p codex-tui app_server_safety_access_errors_render_dedicated_notice` — passed - `just fix -p codex-api` - `just fix -p codex-tui` - `just fmt` - `just test -p codex-tui` — 2,957 passed; two reproducible failures remain in untouched Guardian feature-flag persistence tests: - `update_feature_flags_disabling_guardian_clears_review_policy_and_restores_default` - `update_feature_flags_disabling_guardian_clears_manual_review_policy_without_history` --- codex-rs/codex-api/src/sse/responses.rs | 54 ++++++++++++------- .../tui/src/chatwidget/tests/app_server.rs | 36 ++++++++++--- ...policy_error_renders_dedicated_notice.snap | 11 ++++ codex-rs/tui/src/chatwidget/turn_runtime.rs | 18 +++++-- 4 files changed, 89 insertions(+), 30 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 265d3ced5c..70f96cb855 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -398,7 +398,8 @@ pub fn process_responses_event( } else if is_cyber_policy_error(&error) { let message = cyber_policy_message(error.message); response_error = ApiError::CyberPolicy { message }; - } else if is_invalid_prompt_error(&error) { + } else if matches!(error.code.as_deref(), Some("invalid_prompt" | "bio_policy")) + { let message = error .message .unwrap_or_else(|| "Invalid request.".to_string()); @@ -632,10 +633,6 @@ fn is_usage_not_included(error: &Error) -> bool { error.code.as_deref() == Some("usage_not_included") } -fn is_invalid_prompt_error(error: &Error) -> bool { - error.code.as_deref() == Some("invalid_prompt") -} - fn is_cyber_policy_error(error: &Error) -> bool { error.code.as_deref() == Some("cyber_policy") } @@ -1076,23 +1073,42 @@ mod tests { } #[tokio::test] - async fn invalid_prompt_without_type_is_invalid_request() { - let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_invalid_prompt_no_type","object":"response","created_at":1759771628,"status":"failed","background":false,"error":{"code":"invalid_prompt","message":"Invalid prompt: we've limited access to this content for safety reasons."},"incomplete_details":null}}"#; + async fn content_policy_errors_without_type_are_invalid_requests() { + for (code, expected_message) in [ + ( + "invalid_prompt", + "Invalid prompt: we've limited access to this content for safety reasons.", + ), + ( + "bio_policy", + "This content was flagged for possible biological risk.", + ), + ] { + let raw_error = json!({ + "type": "response.failed", + "sequence_number": 3, + "response": { + "id": "resp_content_policy_no_type", + "object": "response", + "created_at": 1759771628, + "status": "failed", + "background": false, + "error": { "code": code, "message": expected_message }, + "incomplete_details": null, + }, + }) + .to_string(); + let sse1 = format!("event: response.failed\ndata: {raw_error}\n\n"); - let sse1 = format!("event: response.failed\ndata: {raw_error}\n\n"); + let events = collect_events(&[sse1.as_bytes()]).await; - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Err(ApiError::InvalidRequest { message }) => { - assert_eq!( - message, - "Invalid prompt: we've limited access to this content for safety reasons." - ); + assert_eq!(events.len(), 1); + match &events[0] { + Err(ApiError::InvalidRequest { message }) => { + assert_eq!(message, expected_message); + } + other => panic!("unexpected event for {code}: {other:?}"), } - other => panic!("unexpected event: {other:?}"), } } diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index 952aff9f95..28e3cbae3e 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -1182,11 +1182,26 @@ async fn live_app_server_cyber_policy_error_renders_dedicated_notice() { #[tokio::test] async fn app_server_safety_access_errors_render_dedicated_notice() { - let message = "Invalid prompt: we've limited access to this content for safety reasons."; - for message in [ - message.to_string(), - json!({ "error": { "message": message } }).to_string(), - ] { + let legacy_message = "Invalid prompt: we've limited access to this content for safety reasons."; + let bio_policy_message = "This content was flagged for possible biological risk."; + let cases = [ + ("legacy plain message", legacy_message.to_string()), + ( + "legacy JSON message", + json!({ "error": { "message": legacy_message } }).to_string(), + ), + ("bio policy plain message", bio_policy_message.to_string()), + ( + "bio policy JSON message", + json!({ "error": { "message": bio_policy_message } }).to_string(), + ), + ( + "bio policy code", + json!({ "error": { "code": "bio_policy", "message": "copy may change" } }).to_string(), + ), + ]; + let mut rendered_cases = Vec::new(); + for (case, message) in cases { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; chat.handle_non_retry_error(message, /*codex_error_info*/ None); @@ -1195,8 +1210,17 @@ async fn app_server_safety_access_errors_render_dedicated_notice() { let rendered = lines_to_single_string(&cells[0]); assert!(rendered.contains("This content can't be shown")); assert!(rendered.contains("biological research")); - assert!(!rendered.contains("Invalid prompt:")); + rendered_cases.push((case, rendered)); } + + let canonical = &rendered_cases[0].1; + for (case, rendered) in &rendered_cases[1..] { + assert_eq!(rendered, canonical, "unexpected rendering for {case}"); + } + insta::assert_snapshot!( + "app_server_bio_policy_error_renders_dedicated_notice", + rendered_cases.last().unwrap().1.as_str() + ); } #[tokio::test] diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap new file mode 100644 index 0000000000..3149943b64 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests/app_server.rs +expression: rendered_cases.last().unwrap().1.as_str() +--- +ⓘ This content can't be shown + We take extra caution with requests involving biological research and + applications that could pose safety risks. Eligible researchers can apply + for Trusted Access. + Trusted Access: https://www.openai.com/form/trusted-access-for-biology- + research/ + Learn more: https://help.openai.com/en/articles/20001326 diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs index fdfad7f6d8..d71a60820e 100644 --- a/codex-rs/tui/src/chatwidget/turn_runtime.rs +++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs @@ -5,8 +5,15 @@ use super::*; -const SAFETY_ACCESS_BLOCK_PREFIX: &str = +const LEGACY_SAFETY_ACCESS_BLOCK_PREFIX: &str = "Invalid prompt: we've limited access to this content for safety reasons."; +const BIO_POLICY_SAFETY_ACCESS_BLOCK_PREFIX: &str = + "This content was flagged for possible biological risk."; + +fn is_safety_access_block_message(message: &str) -> bool { + message.starts_with(LEGACY_SAFETY_ACCESS_BLOCK_PREFIX) + || message.starts_with(BIO_POLICY_SAFETY_ACCESS_BLOCK_PREFIX) +} impl ChatWidget { /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. @@ -430,11 +437,12 @@ impl ChatWidget { .is_some_and(is_app_server_cyber_policy_error) { self.on_cyber_policy_error(); - } else if message.starts_with(SAFETY_ACCESS_BLOCK_PREFIX) + } else if is_safety_access_block_message(&message) || serde_json::from_str::(&message).is_ok_and(|response| { - response["error"]["message"] - .as_str() - .is_some_and(|message| message.starts_with(SAFETY_ACCESS_BLOCK_PREFIX)) + response["error"]["code"].as_str() == Some("bio_policy") + || response["error"]["message"] + .as_str() + .is_some_and(is_safety_access_block_message) }) { self.input_queue.submit_pending_steers_after_interrupt = false; From 1345c16dd79849eafc5b4a826fa7e534df424810 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Tue, 7 Jul 2026 10:49:06 -0700 Subject: [PATCH 26/79] [codex] add connector runtime latency metrics (#31319) ## Summary - measure successful legacy `app/list` latency with `codex.apps.installed.duration_ms`, segmented by `path=legacy` and `reload` - measure successful host-owned `codex_apps` startup and explicit refresh latency with `codex.apps.refresh.duration_ms` - add the refresh trigger to successful `codex.mcp.tools.fetch_uncached.duration_ms` samples for `codex_apps` without changing other MCP-server samples ## Why This establishes a small latency baseline for the current connector path before `ConnectorRuntimeManager`, `app/installed`, and `app/read` land. Error-rate and broader runtime-state instrumentation are intentionally deferred. This is telemetry-only and does not change connector behavior. ## Validation - `just test -p codex-mcp` (94 passed) - `just test -p codex-app-server list_apps` (13 passed) - `just fix -p codex-mcp` - `just fix -p codex-app-server` - `just fmt` - `git diff --check` --- .../src/request_processors/apps_processor.rs | 35 ++++++++++++++++--- codex-rs/codex-mcp/src/connection_manager.rs | 21 ++++++----- codex-rs/codex-mcp/src/rmcp_client.rs | 33 +++++++++++++---- 3 files changed, 68 insertions(+), 21 deletions(-) diff --git a/codex-rs/app-server/src/request_processors/apps_processor.rs b/codex-rs/app-server/src/request_processors/apps_processor.rs index 67d768fa57..5ff7ec40db 100644 --- a/codex-rs/app-server/src/request_processors/apps_processor.rs +++ b/codex-rs/app-server/src/request_processors/apps_processor.rs @@ -47,6 +47,8 @@ impl AppsRequestProcessor { request_id: &ConnectionRequestId, params: AppsListParams, ) -> Result, JSONRPCErrorError> { + let installed_start = Instant::now(); + let reload = params.force_refetch; let thread = if let Some(thread_id) = params.thread_id.as_deref() { let (_, loaded_thread) = self.load_thread(thread_id).await?; Some(loaded_thread) @@ -70,20 +72,24 @@ impl AppsRequestProcessor { .features .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) { - return Ok(Some(AppsListResponse { + let response = AppsListResponse { data: Vec::new(), next_cursor: None, - })); + }; + record_legacy_apps_installed_duration(installed_start, reload); + return Ok(Some(response)); } if !self .workspace_codex_plugins_enabled(&config, auth.as_ref()) .await { - return Ok(Some(AppsListResponse { + let response = AppsListResponse { data: Vec::new(), next_cursor: None, - })); + }; + record_legacy_apps_installed_duration(installed_start, reload); + return Ok(Some(response)); } let request = request_id.clone(); @@ -103,6 +109,7 @@ impl AppsRequestProcessor { environment_manager, mcp_manager, plugins_manager, + installed_start, ) => {} } }); @@ -113,6 +120,7 @@ impl AppsRequestProcessor { self.shutdown_token.cancel(); } + #[allow(clippy::too_many_arguments)] async fn apps_list_task( outgoing: Arc, request_id: ConnectionRequestId, @@ -121,7 +129,9 @@ impl AppsRequestProcessor { environment_manager: Arc, mcp_manager: Arc, plugins_manager: Arc, + installed_start: Instant, ) { + let reload = params.force_refetch; let retry_params = params.clone(); let retry_config = config.clone(); let retry_environment_manager = Arc::clone(&environment_manager); @@ -136,6 +146,9 @@ impl AppsRequestProcessor { plugins_manager, ) .await; + if result.is_ok() { + record_legacy_apps_installed_duration(installed_start, reload); + } let should_retry = result .as_ref() .is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready); @@ -363,6 +376,20 @@ impl AppsRequestProcessor { } const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90); +// `app/list` is the legacy request-path baseline for the future `app/installed` endpoint; +// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards. +const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms"; + +fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) { + let reload = if reload { "true" } else { "false" }; + if let Some(metrics) = codex_otel::global() { + let _ = metrics.record_duration( + APPS_INSTALLED_DURATION_METRIC, + started_at.elapsed(), + &[("path", "legacy"), ("reload", reload)], + ); + } +} enum AppListLoadResult { Accessible(Result), diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index 2143e3b577..223d4296d5 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -23,8 +23,8 @@ use crate::elicitation::ElicitationReviewerHandle; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::ToolPluginProvenance; use crate::rmcp_client::AsyncManagedClient; +use crate::rmcp_client::CODEX_APPS_REFRESH_DURATION_METRIC; use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT; -use crate::rmcp_client::MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC; use crate::rmcp_client::MCP_TOOLS_LIST_DURATION_METRIC; use crate::rmcp_client::ManagedClient; use crate::rmcp_client::StartupOutcomeError; @@ -530,6 +530,7 @@ impl McpConnectionManager { /// cache is enabled and the latest filtered tools are returned directly to /// the caller. On failure, existing shared cache contents remain unchanged. pub async fn hard_refresh_codex_apps_tools_cache(&self) -> Result> { + let refresh_start = Instant::now(); let managed_client = self .clients .get(CODEX_APPS_MCP_SERVER_NAME) @@ -539,7 +540,6 @@ impl McpConnectionManager { .context("failed to get client")?; let list_start = Instant::now(); - let fetch_start = Instant::now(); let fetch_ticket = managed_client .codex_apps_tools_cache_context .as_ref() @@ -547,6 +547,7 @@ impl McpConnectionManager { let tools = list_tools_for_client_uncached( CODEX_APPS_MCP_SERVER_NAME, /*is_codex_apps_mcp_server*/ true, + /*codex_apps_refresh_trigger*/ "explicit", &managed_client.client, managed_client.tool_timeout, managed_client.server_instructions.as_deref(), @@ -555,11 +556,6 @@ impl McpConnectionManager { .with_context(|| { format!("failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'") })?; - emit_duration( - MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, - fetch_start.elapsed(), - &[], - ); let tools = match ( @@ -582,10 +578,13 @@ impl McpConnectionManager { tool.tool = tool_with_model_visible_input_schema(&tool.tool); self.with_server_metadata(tool) }); - Ok(normalize_tools_for_model_with_prefix( - tools, - self.prefix_mcp_tool_names, - )) + let tools = normalize_tools_for_model_with_prefix(tools, self.prefix_mcp_tool_names); + emit_duration( + CODEX_APPS_REFRESH_DURATION_METRIC, + refresh_start.elapsed(), + &[("path", "legacy"), ("trigger", "explicit")], + ); + Ok(tools) } /// Returns resources from servers selected by `include_server`. Each key diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index 37819203f6..6fe820b4fe 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -82,6 +82,7 @@ pub const OPENAI_FORM_CAPABILITY: &str = "openai/form"; pub(crate) const MCP_TOOLS_LIST_DURATION_METRIC: &str = "codex.mcp.tools.list.duration_ms"; pub(crate) const MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC: &str = "codex.mcp.tools.fetch_uncached.duration_ms"; +pub(crate) const CODEX_APPS_REFRESH_DURATION_METRIC: &str = "codex.apps.refresh.duration_ms"; pub(crate) const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(30); pub(crate) const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(300); @@ -304,6 +305,7 @@ impl ManagedClientStartup { .unwrap_or_default(); let cancel_token_for_fut = cancel_token; async move { + let refresh_start = is_codex_apps_mcp_server.then(Instant::now); let outcome = match async { if let Err(error) = validate_mcp_server_name(&server_name) { return Err(error.into()); @@ -349,6 +351,15 @@ impl ManagedClientStartup { Ok(result) => result, Err(CancelErr::Cancelled) => Err(StartupOutcomeError::Cancelled), }; + if outcome.is_ok() + && let Some(refresh_start) = refresh_start + { + emit_duration( + CODEX_APPS_REFRESH_DURATION_METRIC, + refresh_start.elapsed(), + &[("path", "legacy"), ("trigger", "initial")], + ); + } startup_complete.store(true, Ordering::Release); outcome @@ -564,10 +575,12 @@ impl From for StartupOutcomeError { pub(crate) async fn list_tools_for_client_uncached( server_name: &str, is_codex_apps_mcp_server: bool, + codex_apps_refresh_trigger: &'static str, client: &Arc, timeout: Option, server_instructions: Option<&str>, ) -> Result> { + let fetch_start = Instant::now(); let resp = client .list_tools_with_connector_ids(/*params*/ None, timeout) .await?; @@ -583,6 +596,19 @@ pub(crate) async fn list_tools_for_client_uncached( ) }) .collect(); + if is_codex_apps_mcp_server { + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[("trigger", codex_apps_refresh_trigger)], + ); + } else { + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[], + ); + } Ok(tools) } @@ -820,24 +846,19 @@ async fn start_server_task( .and_then(|exp| exp.get(MCP_SANDBOX_STATE_META_CAPABILITY)) .is_some(); let list_start = Instant::now(); - let fetch_start = Instant::now(); let fetch_ticket = codex_apps_tools_cache_context .as_ref() .map(|cache_context| cache_context.begin_fetch(CodexAppsToolsFetchSource::Startup)); let tools = list_tools_for_client_uncached( &server_name, is_codex_apps_mcp_server, + /*codex_apps_refresh_trigger*/ "initial", &client, startup_timeout, initialize_result.instructions.as_deref(), ) .await .map_err(StartupOutcomeError::from)?; - emit_duration( - MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, - fetch_start.elapsed(), - &[], - ); let server_info = mcp_server_info_from_implementation(initialize_result.server_info); let tools = match (codex_apps_tools_cache_context.as_ref(), fetch_ticket) { (Some(cache_context), Some(fetch_ticket)) => { From 358575465c65182cf77e6a1e6da395eb00ba51cf Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Tue, 7 Jul 2026 10:52:38 -0700 Subject: [PATCH 27/79] Use model catalog approval messages (#31312) ## Why Approval guidance is currently assembled entirely by the client. Model Messages V2 needs model catalogs to provide model-specific `on_request` guidance for both user-reviewed and auto-reviewed approval flows while retaining the existing generated prompt as a compatibility fallback. ## What changed - add nullable `on_request` and `on_request_auto_review` catalog messages - select the message matching the active approvals reviewer for `on_request` policies - replace the complete legacy approval section when the selected catalog value exists, including support for an empty string that suppresses the section - retain legacy rendering when the object or selected key is absent, and for non-`on_request` policies - preserve approval messages when base-instruction or personality overrides clear instruction templates - refresh permissions instructions when the active model changes - pass catalog messages through initial and incremental permissions construction ## Relationship to reviewer persistence PR #31309 independently persists the approvals reviewer in turn context and refreshes permissions when that reviewer changes. This PR is based directly on `main` and does not duplicate that rollout migration; once both land, reviewer switches will also select and append the new catalog variant. ## Testing - `just test -p codex-protocol` - `just test -p codex-prompts` - `just test -p codex-models-manager` - `just test -p codex-core permissions_messages` --- codex-rs/core/src/context/mod.rs | 1 + .../src/context/permissions_instructions.rs | 1 + codex-rs/core/src/context_manager/updates.rs | 10 +- codex-rs/core/src/session/mod.rs | 10 +- codex-rs/core/src/session/tests.rs | 17 +-- .../core/tests/suite/permissions_messages.rs | 130 +++++++++++++++++- codex-rs/core/tests/suite/personality.rs | 2 + codex-rs/models-manager/src/model_info.rs | 15 +- .../models-manager/src/model_info_tests.rs | 63 +++++++++ codex-rs/prompts/src/lib.rs | 1 + .../prompts/src/permissions_instructions.rs | 33 ++++- .../src/permissions_instructions_tests.rs | 114 ++++++++++++++- codex-rs/protocol/src/openai_models.rs | 42 ++++++ 13 files changed, 419 insertions(+), 20 deletions(-) diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index da7db0b373..20b35e7af3 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -62,6 +62,7 @@ pub(crate) use legacy_unified_exec_process_limit_warning::LegacyUnifiedExecProce pub(crate) use model_switch_instructions::ModelSwitchInstructions; pub(crate) use multi_agent_mode_instructions::MultiAgentModeInstructions; pub(crate) use network_rule_saved::NetworkRuleSaved; +pub use permissions_instructions::ApprovalPromptContext; pub use permissions_instructions::PermissionsInstructions; pub(crate) use personality_spec_instructions::PersonalitySpecInstructions; pub(crate) use plugin_instructions::PluginInstructions; diff --git a/codex-rs/core/src/context/permissions_instructions.rs b/codex-rs/core/src/context/permissions_instructions.rs index 73629a3d53..3dd1bbac92 100644 --- a/codex-rs/core/src/context/permissions_instructions.rs +++ b/codex-rs/core/src/context/permissions_instructions.rs @@ -1 +1,2 @@ +pub use codex_prompts::ApprovalPromptContext; pub use codex_prompts::PermissionsInstructions; diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index a520e6f595..d4cf65e86d 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -1,3 +1,4 @@ +use crate::context::ApprovalPromptContext; use crate::context::CollaborationModeInstructions; use crate::context::ContextualUserFragment; use crate::context::ModelSwitchInstructions; @@ -30,6 +31,7 @@ fn build_permissions_update_item( let prev = previous?; if prev.permission_profile() == next.permission_profile() && prev.approval_policy == next.approval_policy.value() + && prev.model == next.model_info.slug { return None; } @@ -38,7 +40,13 @@ fn build_permissions_update_item( PermissionsInstructions::from_permission_profile( &next.permission_profile, next.approval_policy.value(), - next.config.approvals_reviewer, + ApprovalPromptContext::new( + next.config.approvals_reviewer, + next.model_info + .model_messages + .as_ref() + .and_then(|messages| messages.approvals.as_ref()), + ), exec_policy, #[allow(deprecated)] &next.cwd, diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index fa240b890b..af2412e5c4 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -21,6 +21,7 @@ use crate::build_available_skills; use crate::compact; use crate::config::ManagedFeatures; use crate::config::resolve_tool_suggest_config_from_layer_stack; +use crate::context::ApprovalPromptContext; use crate::context::ApprovedCommandPrefixSaved; use crate::context::AvailableSkillsInstructions; use crate::context::CollaborationModeInstructions; @@ -3206,7 +3207,14 @@ impl Session { PermissionsInstructions::from_permission_profile( &turn_context.permission_profile, turn_context.approval_policy.value(), - turn_context.config.approvals_reviewer, + ApprovalPromptContext::new( + turn_context.config.approvals_reviewer, + turn_context + .model_info + .model_messages + .as_ref() + .and_then(|messages| messages.approvals.as_ref()), + ), self.services.exec_policy.current().as_ref(), #[allow(deprecated)] &turn_context.cwd, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5ebce9aa42..ac8f9d049e 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -9041,18 +9041,13 @@ async fn record_context_updates_and_set_reference_context_item_reinjects_full_co #[tokio::test] async fn record_context_updates_and_set_reference_context_item_persists_baseline_without_emitting_diffs() { - let (mut session, previous_context) = make_session_and_context().await; - let next_model = if previous_context.model_info.slug == "gpt-5.4" { - "gpt-5.2" - } else { - "gpt-5.4" - }; - let turn_context = previous_context - .with_model(next_model.to_string(), &session.services.models_manager) - .await; - let previous_context_item = previous_context.to_turn_context_item(); - let previous_context = Arc::new(previous_context); + let (mut session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let previous_context = Arc::new(turn_context); let world_state = build_world_state_from_turn_context(&session, &previous_context).await; + let mut turn_context = Arc::try_unwrap(previous_context) + .unwrap_or_else(|_| panic!("previous turn context should have no remaining references")); + turn_context.sub_id = format!("{}-next", turn_context.sub_id); { let mut state = session.state.lock().await; state.set_reference_context_item(Some(previous_context_item.clone())); diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index e5a69962bc..7f42ba893c 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -2,10 +2,15 @@ use anyhow::Result; use codex_config::ConfigLayerStack; use codex_core::ForkSnapshot; use codex_core::config::Constrained; +use codex_core::context::ApprovalPromptContext; use codex_core::context::ContextualUserFragment; use codex_core::context::PermissionsInstructions; use codex_core::load_exec_policy; +use codex_models_manager::model_info::model_info_from_slug; use codex_protocol::models::PermissionProfile; +use codex_protocol::openai_models::ApprovalMessages; +use codex_protocol::openai_models::ModelMessages; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -33,6 +38,129 @@ fn permissions_texts(request: &ResponsesRequest) -> Vec { .collect() } +fn model_with_approval_messages( + slug: &str, + on_request: &str, + on_request_auto_review: &str, +) -> codex_protocol::openai_models::ModelInfo { + let mut model = model_info_from_slug(slug); + model.model_messages = Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(ApprovalMessages { + on_request: Some(on_request.to_string()), + on_request_auto_review: Some(on_request_auto_review.to_string()), + }), + }); + model +} + +async fn submit_text_turn( + test: &core_test_support::test_codex::TestCodex, + text: &str, +) -> Result<()> { + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn catalog_approval_message_is_sent_in_initial_permissions() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let req = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + ) + .await; + let model_slug = "catalog-approvals-model"; + let model = model_with_approval_messages( + model_slug, + "catalog user approval instructions", + "catalog auto-review approval instructions", + ); + let mut builder = test_codex() + .with_model(model_slug) + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + }); + let test = builder.build(&server).await?; + + submit_text_turn(&test, "hello").await?; + + let permissions = permissions_texts(&req.single_request()); + assert_eq!(permissions.len(), 1); + assert!(permissions[0].contains("catalog user approval instructions")); + assert!(permissions[0].contains("Filesystem sandboxing defines")); + assert!(!permissions[0].contains("How to request escalation")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn model_change_appends_new_catalog_approval_message() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let _req1 = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + ) + .await; + let req2 = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]), + ) + .await; + let first_slug = "catalog-approvals-model-a"; + let second_slug = "catalog-approvals-model-b"; + let first = model_with_approval_messages(first_slug, "model A approvals", "model A auto"); + let second = model_with_approval_messages(second_slug, "model B approvals", "model B auto"); + let mut builder = test_codex() + .with_model(first_slug) + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config.model_catalog = Some(ModelsResponse { + models: vec![first, second], + }); + }); + let test = builder.build(&server).await?; + submit_text_turn(&test, "first").await?; + + core_test_support::submit_thread_settings( + &test.codex, + codex_protocol::protocol::ThreadSettingsOverrides { + model: Some(second_slug.to_string()), + ..Default::default() + }, + ) + .await?; + submit_text_turn(&test, "second").await?; + + let permissions = permissions_texts(&req2.single_request()); + assert_eq!(permissions.len(), 2); + assert!( + permissions + .last() + .is_some_and(|text| text.contains("model B approvals")) + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn permissions_message_sent_once_on_start() -> Result<()> { skip_if_no_network!(Ok(())); @@ -563,7 +691,7 @@ async fn permissions_message_includes_writable_roots() -> Result<()> { let expected = PermissionsInstructions::from_permission_profile( &permission_profile, AskForApproval::OnRequest, - test.config.approvals_reviewer, + ApprovalPromptContext::new(test.config.approvals_reviewer, /*messages*/ None), &exec_policy, test.config.cwd.as_path(), /*exec_permission_approvals_enabled*/ false, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index e74695b59d..88733b4666 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -573,6 +573,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow personality_friendly: Some(friendly_personality_message.to_string()), personality_pragmatic: Some("Pragmatic variant".to_string()), }), + approvals: None, }), include_skills_usage_instructions: false, supports_reasoning_summaries: false, @@ -689,6 +690,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - personality_friendly: Some(remote_friendly_message.to_string()), personality_pragmatic: Some(remote_pragmatic_message.to_string()), }), + approvals: None, }), include_skills_usage_instructions: false, supports_reasoning_summaries: false, diff --git a/codex-rs/models-manager/src/model_info.rs b/codex-rs/models-manager/src/model_info.rs index 573403b728..75d333efe3 100644 --- a/codex-rs/models-manager/src/model_info.rs +++ b/codex-rs/models-manager/src/model_info.rs @@ -54,14 +54,24 @@ pub fn with_config_overrides(mut model: ModelInfo, config: &ModelsManagerConfig) if let Some(base_instructions) = &config.base_instructions { model.base_instructions = base_instructions.clone(); - model.model_messages = None; + clear_instruction_messages(&mut model); } else if !config.personality_enabled { - model.model_messages = None; + clear_instruction_messages(&mut model); } model } +fn clear_instruction_messages(model: &mut ModelInfo) { + if let Some(model_messages) = &mut model.model_messages { + model_messages.instructions_template = None; + model_messages.instructions_variables = None; + if model_messages.approvals.is_none() { + model.model_messages = None; + } + } +} + /// Build a minimal fallback model descriptor for missing/unknown slugs. pub fn model_info_from_slug(slug: &str) -> ModelInfo { warn!("Unknown model {slug} is used. This will use fallback model metadata."); @@ -119,6 +129,7 @@ fn local_personality_messages_for_slug(slug: &str) -> Option { personality_friendly: Some(LOCAL_FRIENDLY_TEMPLATE.to_string()), personality_pragmatic: Some(LOCAL_PRAGMATIC_TEMPLATE.to_string()), }), + approvals: None, }), _ => None, } diff --git a/codex-rs/models-manager/src/model_info_tests.rs b/codex-rs/models-manager/src/model_info_tests.rs index 70ad3da8df..2240f0a391 100644 --- a/codex-rs/models-manager/src/model_info_tests.rs +++ b/codex-rs/models-manager/src/model_info_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::ModelsManagerConfig; +use codex_protocol::openai_models::ApprovalMessages; use pretty_assertions::assert_eq; #[test] @@ -44,6 +45,68 @@ fn reasoning_summaries_override_false_is_noop_when_model_is_false() { assert_eq!(updated, model); } +#[test] +fn base_instruction_override_preserves_catalog_approval_messages() { + let mut model = model_info_from_slug("unknown-model"); + let approvals = ApprovalMessages { + on_request: Some("user approvals".to_string()), + on_request_auto_review: Some("auto approvals".to_string()), + }; + model.model_messages = Some(ModelMessages { + instructions_template: Some("template".to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: Some("default".to_string()), + personality_friendly: Some("friendly".to_string()), + personality_pragmatic: Some("pragmatic".to_string()), + }), + approvals: Some(approvals.clone()), + }); + let config = ModelsManagerConfig { + base_instructions: Some("override".to_string()), + ..Default::default() + }; + + let updated = with_config_overrides(model, &config); + + assert_eq!( + updated.model_messages, + Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(approvals), + }) + ); +} + +#[test] +fn disabled_personality_preserves_catalog_approval_messages() { + let mut model = model_info_from_slug("unknown-model"); + let approvals = ApprovalMessages { + on_request: Some("user approvals".to_string()), + on_request_auto_review: None, + }; + model.model_messages = Some(ModelMessages { + instructions_template: Some("template".to_string()), + instructions_variables: None, + approvals: Some(approvals.clone()), + }); + let config = ModelsManagerConfig { + personality_enabled: false, + ..Default::default() + }; + + let updated = with_config_overrides(model, &config); + + assert_eq!( + updated.model_messages, + Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(approvals), + }) + ); +} + #[test] fn model_context_window_override_clamps_to_max_context_window() { let mut model = model_info_from_slug("unknown-model"); diff --git a/codex-rs/prompts/src/lib.rs b/codex-rs/prompts/src/lib.rs index 5a30358393..c598b2d765 100644 --- a/codex-rs/prompts/src/lib.rs +++ b/codex-rs/prompts/src/lib.rs @@ -12,6 +12,7 @@ pub use compact::SUMMARY_PREFIX; pub use goals::budget_limit_prompt; pub use goals::continuation_prompt; pub use goals::objective_updated_prompt; +pub use permissions_instructions::ApprovalPromptContext; pub use permissions_instructions::PermissionsInstructions; pub use realtime::BACKEND_PROMPT; pub use realtime::END_INSTRUCTIONS; diff --git a/codex-rs/prompts/src/permissions_instructions.rs b/codex-rs/prompts/src/permissions_instructions.rs index c382b804a0..1c19d008cf 100644 --- a/codex-rs/prompts/src/permissions_instructions.rs +++ b/codex-rs/prompts/src/permissions_instructions.rs @@ -4,6 +4,7 @@ use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::SandboxMode; use codex_protocol::models::PermissionProfile; use codex_protocol::models::format_allow_prefixes; +use codex_protocol::openai_models::ApprovalMessages; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; @@ -47,6 +48,7 @@ static SANDBOX_MODE_READ_ONLY_TEMPLATE: LazyLock