From 083bf59b6b01582f62171249f6a6ff0686928229 Mon Sep 17 00:00:00 2001 From: ssetty-oai Date: Thu, 19 Nov 2026 06:15:22 +0000 Subject: [PATCH] Send authorized connector results over Responses WebSockets (#62474) ## Why HTTP sampling can attach private connector result bodies, but Responses WebSocket sampling leaves them out. WebSocket requests need the same destination and account checks before sending those bodies. ## What changed Apply the existing HTTP eligibility checks to each WebSocket attempt and attach only result bodies that belong to the current account and match the input being sent, including when that input is an incremental update. Keep prewarm requests free of private result bodies. Update `tungstenite` and `tokio-tungstenite` to keep sensitive payload bytes out of frame diagnostics. ## Testing Add regression coverage for connector results reaching the server while staying out of request observers and client logs. Cover custom-provider requests and retries across an account change with results from both Code Mode `exec` and `wait`. GitOrigin-RevId: df5ec8608e59bb3a0444fafd5268279e669ccb55 --- MODULE.bazel.lock | 8 +- codex-rs/Cargo.lock | 5 +- codex-rs/Cargo.toml | 6 +- codex-rs/codex-api/Cargo.toml | 1 + .../tests/responses_websocket_logging.rs | 208 ++++++++++++++++++ codex-rs/core/src/client.rs | 17 ++ codex-rs/core/tests/suite/code_mode.rs | 207 +++++++++++++++++ 7 files changed, 443 insertions(+), 9 deletions(-) create mode 100644 codex-rs/codex-api/tests/responses_websocket_logging.rs diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index ed89062c4d..314db22558 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1389,8 +1389,8 @@ "git+https://github.com/modelcontextprotocol/rust-sdk?rev=b11a40d889e022087d7f2b8cd23aa28e19ceaf5b#b11a40d889e022087d7f2b8cd23aa28e19ceaf5b_rmcp-macros": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"darling\",\"optional\":false,\"req\":\"0.24\"},{\"name\":\"proc-macro2\",\"req\":\"1\"},{\"name\":\"quote\",\"req\":\"1\"},{\"name\":\"serde_json\",\"req\":\"1.0\"},{\"default_features\":true,\"features\":[\"full\"],\"name\":\"syn\",\"optional\":false,\"req\":\"3\"}],\"features\":{\"local\":[]},\"strip_prefix\":\"./crates/rmcp-macros\"}", "git+https://github.com/openai-oss-forks/crossterm?rev=37ca4a27a9424ec5dbe6451f48c339d7b45f8d63#37ca4a27a9424ec5dbe6451f48c339d7b45f8d63_crossterm": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"base64\",\"optional\":true,\"req\":\"0.23\"},{\"default_features\":true,\"features\":[],\"name\":\"bitflags\",\"optional\":false,\"req\":\"2.9\"},{\"default_features\":true,\"features\":[\"is_variant\"],\"name\":\"derive_more\",\"optional\":true,\"req\":\"2.0.0\"},{\"default_features\":true,\"features\":[],\"name\":\"document-features\",\"optional\":true,\"req\":\"0.2.11\"},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":true,\"req\":\"0.3.31\"},{\"name\":\"parking_lot\",\"req\":\"0.12.1\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"1.0.103\"},{\"default_features\":true,\"features\":[],\"name\":\"filedescriptor\",\"optional\":true,\"req\":\"0.8\",\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[],\"name\":\"libc\",\"optional\":true,\"req\":\"0.2.168\",\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"os-poll\"],\"name\":\"mio\",\"optional\":true,\"req\":\"1.0.1\",\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[\"std\",\"stdio\",\"termios\"],\"name\":\"rustix\",\"optional\":false,\"req\":\"1\",\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"signal-hook\",\"optional\":true,\"req\":\"0.3.17\",\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"support-v1_0\"],\"name\":\"signal-hook-mio\",\"optional\":true,\"req\":\"0.2.4\",\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"crossterm_winapi\",\"optional\":true,\"req\":\"0.9.1\",\"target\":\"cfg(windows)\"},{\"default_features\":true,\"features\":[\"winuser\",\"winerror\"],\"name\":\"winapi\",\"optional\":true,\"req\":\"0.3.9\",\"target\":\"cfg(windows)\"}],\"features\":{\"bracketed-paste\":[],\"default\":[\"bracketed-paste\",\"derive-more\",\"events\",\"windows\"],\"derive-more\":[\"dep:derive_more\"],\"document-features\":[\"dep:document-features\"],\"event-stream\":[\"dep:futures-core\",\"events\"],\"events\":[\"dep:mio\",\"dep:signal-hook\",\"dep:signal-hook-mio\"],\"osc52\":[\"dep:base64\"],\"serde\":[\"dep:serde\",\"bitflags/serde\"],\"use-dev-tty\":[\"filedescriptor\",\"rustix/process\"],\"windows\":[\"dep:winapi\",\"dep:crossterm_winapi\"]},\"strip_prefix\":\"\"}", "git+https://github.com/openai-oss-forks/rusty_v8.git?rev=90a65f887a0c0f048f3784afbcb320b373c8a2e0#90a65f887a0c0f048f3784afbcb320b373c8a2e0_v8": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"2.5\"},{\"name\":\"paste\",\"req\":\"1.0\"},{\"default_features\":true,\"features\":[\"zoneinfo64\"],\"name\":\"temporal_capi\",\"optional\":false,\"req\":\"0.2.3\"},{\"kind\":\"build\",\"name\":\"bindgen\",\"req\":\"0.72\"},{\"kind\":\"build\",\"name\":\"fslock\",\"req\":\"0.2\"},{\"kind\":\"build\",\"name\":\"gzip-header\",\"req\":\"1.0.0\"},{\"kind\":\"build\",\"name\":\"home\",\"req\":\"0\"},{\"kind\":\"build\",\"name\":\"miniz_oxide\",\"req\":\"0.8.8\"},{\"kind\":\"build\",\"name\":\"which\",\"req\":\"6\"}],\"features\":{\"default\":[\"use_custom_libcxx\"],\"simdutf\":[],\"use_custom_libcxx\":[],\"v8_enable_pointer_compression\":[],\"v8_enable_sandbox\":[\"v8_enable_pointer_compression\"],\"v8_enable_v8_checks\":[]},\"strip_prefix\":\"\"}", - "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7447c427513cfe685f236e1ac0513c4ea3dd9c0b#7447c427513cfe685f236e1ac0513c4ea3dd9c0b_tokio-tungstenite": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"sink\",\"std\"],\"name\":\"futures-util\",\"optional\":false,\"req\":\"0.3.28\"},{\"name\":\"log\",\"req\":\"0.4.17\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"0.2.11\"},{\"default_features\":false,\"features\":[],\"name\":\"rustls\",\"optional\":true,\"req\":\"0.23.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"0.8.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":false,\"features\":[\"io-util\"],\"name\":\"tokio\",\"optional\":false,\"req\":\"1.0.0\"},{\"default_features\":true,\"features\":[],\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"0.3.1\"},{\"default_features\":false,\"features\":[],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"0.26.0\"},{\"default_features\":false,\"features\":[],\"name\":\"tungstenite\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"0.26.0\"}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\",\"tokio-rustls\",\"stream\",\"tungstenite/__rustls-tls\",\"handshake\"],\"connect\":[\"stream\",\"tokio/net\",\"tokio/time\",\"handshake\"],\"default\":[\"connect\",\"handshake\"],\"handshake\":[\"tungstenite/handshake\"],\"native-tls\":[\"native-tls-crate\",\"tokio-native-tls\",\"stream\",\"tungstenite/native-tls\",\"handshake\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\",\"tungstenite/native-tls-vendored\"],\"proxy\":[\"tungstenite/proxy\",\"tokio/net\",\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"stream\":[],\"url\":[\"tungstenite/url\"]},\"strip_prefix\":\"\"}", - "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=bc589d684755a8c02da0fc7e58d0861cbfc306f1#bc589d684755a8c02da0fc7e58d0861cbfc306f1_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"1.9.0\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"optional\":true,\"req\":\"2\"},{\"default_features\":false,\"features\":[\"zlib-rs\"],\"name\":\"flate2\",\"optional\":true,\"req\":\"1.1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"headers\",\"optional\":true,\"req\":\"0.4.0\"},{\"default_features\":true,\"features\":[],\"name\":\"http\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"httparse\",\"optional\":true,\"req\":\"1.3.4\"},{\"name\":\"log\",\"req\":\"0.4.8\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"0.2.3\"},{\"name\":\"rand\",\"req\":\"0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"0.23.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"0.8.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"sha1\",\"optional\":true,\"req\":\"0.10\"},{\"name\":\"thiserror\",\"req\":\"2.0.7\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":true,\"req\":\"2.1.0\"},{\"name\":\"utf-8\",\"req\":\"0.7.5\"},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"0.26\"}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\"],\"default\":[\"handshake\"],\"deflate\":[\"headers\",\"flate2\"],\"handshake\":[\"data-encoding\",\"headers\",\"httparse\",\"sha1\"],\"headers\":[\"http\",\"dep:headers\"],\"native-tls\":[\"native-tls-crate\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"proxy\":[\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"url\":[\"dep:url\"]},\"strip_prefix\":\"\"}", + "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7a920470d62138955446b64220c7609e46ad770e#7a920470d62138955446b64220c7609e46ad770e_tokio-tungstenite": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"sink\",\"std\"],\"name\":\"futures-util\",\"optional\":false,\"req\":\"0.3.28\"},{\"name\":\"log\",\"req\":\"0.4.17\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"0.2.11\"},{\"default_features\":false,\"features\":[],\"name\":\"rustls\",\"optional\":true,\"req\":\"0.23.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"0.8.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":false,\"features\":[\"io-util\"],\"name\":\"tokio\",\"optional\":false,\"req\":\"1.0.0\"},{\"default_features\":true,\"features\":[],\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"0.3.1\"},{\"default_features\":false,\"features\":[],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"0.26.0\"},{\"default_features\":false,\"features\":[],\"name\":\"tungstenite\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"0.26.0\"}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\",\"tokio-rustls\",\"stream\",\"tungstenite/__rustls-tls\",\"handshake\"],\"connect\":[\"stream\",\"tokio/net\",\"tokio/time\",\"handshake\"],\"default\":[\"connect\",\"handshake\"],\"handshake\":[\"tungstenite/handshake\"],\"native-tls\":[\"native-tls-crate\",\"tokio-native-tls\",\"stream\",\"tungstenite/native-tls\",\"handshake\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\",\"tungstenite/native-tls-vendored\"],\"proxy\":[\"tungstenite/proxy\",\"tokio/net\",\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"stream\":[],\"url\":[\"tungstenite/url\"]},\"strip_prefix\":\"\"}", + "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=e19950ef7828cb311e6d51a6bedcebf0192e055c#e19950ef7828cb311e6d51a6bedcebf0192e055c_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"1.9.0\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"optional\":true,\"req\":\"2\"},{\"default_features\":false,\"features\":[\"zlib-rs\"],\"name\":\"flate2\",\"optional\":true,\"req\":\"1.1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"headers\",\"optional\":true,\"req\":\"0.4.0\"},{\"default_features\":true,\"features\":[],\"name\":\"http\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"httparse\",\"optional\":true,\"req\":\"1.3.4\"},{\"name\":\"log\",\"req\":\"0.4.8\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"0.2.3\"},{\"name\":\"rand\",\"req\":\"0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"0.23.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"0.8.0\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"1.0\"},{\"default_features\":true,\"features\":[],\"name\":\"sha1\",\"optional\":true,\"req\":\"0.10\"},{\"name\":\"thiserror\",\"req\":\"2.0.7\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":true,\"req\":\"2.1.0\"},{\"name\":\"utf-8\",\"req\":\"0.7.5\"},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"0.26\"}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\"],\"default\":[\"handshake\"],\"deflate\":[\"headers\",\"flate2\"],\"handshake\":[\"data-encoding\",\"headers\",\"httparse\",\"sha1\"],\"headers\":[\"http\",\"dep:headers\"],\"native-tls\":[\"native-tls-crate\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"proxy\":[\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"url\":[\"dep:url\"]},\"strip_prefix\":\"\"}", "git+https://github.com/rust-lang/rust-clippy?rev=21baba9c10c5d179915cae82e6247bc2337872fb#21baba9c10c5d179915cae82e6247bc2337872fb_clippy_utils": "{\"dependencies\":[{\"default_features\":false,\"features\":[],\"name\":\"arrayvec\",\"optional\":false,\"req\":\"0.7\"},{\"name\":\"itertools\",\"req\":\"0.15\"},{\"name\":\"rustc_apfloat\",\"req\":\"0.2.0\"}],\"features\":{},\"strip_prefix\":\"clippy_utils\"}", "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c_sqlx-core": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"async-fs\",\"optional\":true,\"req\":\"2.1\"},{\"default_features\":false,\"features\":[\"async-io\"],\"name\":\"async-global-executor\",\"optional\":true,\"req\":\"3.1\"},{\"default_features\":true,\"features\":[],\"name\":\"async-io\",\"optional\":true,\"req\":\"2.4.1\"},{\"default_features\":true,\"features\":[],\"name\":\"async-std\",\"optional\":true,\"req\":\"1.13\"},{\"default_features\":true,\"features\":[],\"name\":\"async-task\",\"optional\":true,\"req\":\"4.7.1\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"base64\",\"optional\":false,\"req\":\"0.22.1\"},{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"0.4.0\"},{\"name\":\"bit-vec\",\"optional\":true,\"req\":\"0.8\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"bstr\",\"optional\":true,\"req\":\"1.0.1\"},{\"name\":\"bytes\",\"req\":\"1.2.0\"},{\"name\":\"cfg-if\",\"req\":\"1.0.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"0.4.34\"},{\"default_features\":true,\"features\":[],\"name\":\"crc\",\"optional\":true,\"req\":\"3\"},{\"name\":\"crossbeam-queue\",\"req\":\"0.3.2\"},{\"name\":\"either\",\"req\":\"1.6.1\"},{\"name\":\"event-listener\",\"req\":\"5.2.0\"},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":false,\"req\":\"0.3.32\"},{\"name\":\"futures-intrusive\",\"req\":\"0.5.0\"},{\"name\":\"futures-io\",\"req\":\"0.3.32\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"optional\":false,\"req\":\"0.3.32\"},{\"name\":\"hashbrown\",\"req\":\"0.16.0\"},{\"name\":\"hashlink\",\"req\":\"0.11.0\"},{\"name\":\"indexmap\",\"req\":\"2.0\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"2.3.0\"},{\"name\":\"ipnetwork\",\"optional\":true,\"req\":\"0.21.1\"},{\"default_features\":false,\"features\":[],\"name\":\"log\",\"optional\":false,\"req\":\"0.4.18\"},{\"name\":\"mac_address\",\"optional\":true,\"req\":\"1.1.5\"},{\"default_features\":false,\"features\":[],\"name\":\"memchr\",\"optional\":false,\"req\":\"2.5.0\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls\",\"optional\":true,\"req\":\"0.2.10\"},{\"name\":\"percent-encoding\",\"req\":\"2.3.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"1.36.0\"},{\"default_features\":false,\"features\":[\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"0.23.24\"},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"0.8.0\"},{\"default_features\":true,\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"1.0.219\"},{\"default_features\":true,\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"1.0.142\"},{\"default_features\":false,\"features\":[],\"name\":\"sha2\",\"optional\":true,\"req\":\"0.11.0\"},{\"name\":\"smallvec\",\"req\":\"1.13.1\"},{\"default_features\":false,\"features\":[],\"name\":\"smol\",\"optional\":true,\"req\":\"2.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"optional\":false,\"req\":\"2.0.18\"},{\"default_features\":true,\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"0.3.48\"},{\"default_features\":false,\"features\":[\"time\",\"net\",\"sync\",\"fs\",\"io-util\",\"rt\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"1.25.0\"},{\"default_features\":true,\"features\":[\"fs\"],\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"0.1.8\"},{\"default_features\":true,\"features\":[],\"name\":\"toml\",\"optional\":true,\"req\":\"0.8.16\"},{\"default_features\":true,\"features\":[\"log\"],\"name\":\"tracing\",\"optional\":false,\"req\":\"0.1.37\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":false,\"req\":\"2.2.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"1.12.1\"},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"1\"}],\"features\":{\"_rt-async-global-executor\":[\"async-global-executor\",\"_rt-async-io\",\"_rt-async-task\"],\"_rt-async-io\":[\"async-io\",\"async-fs\"],\"_rt-async-std\":[\"async-std\",\"_rt-async-io\"],\"_rt-async-task\":[\"async-task\"],\"_rt-smol\":[\"smol\",\"_rt-async-io\",\"_rt-async-task\"],\"_rt-tokio\":[\"tokio\",\"tokio-stream\"],\"_tls-native-tls\":[\"native-tls\"],\"_tls-none\":[],\"_tls-rustls\":[\"rustls\"],\"_tls-rustls-aws-lc-rs\":[\"_tls-rustls\",\"rustls/aws-lc-rs\",\"webpki-roots\"],\"_tls-rustls-ring-native-roots\":[\"_tls-rustls\",\"rustls/ring\",\"rustls-native-certs\"],\"_tls-rustls-ring-webpki\":[\"_tls-rustls\",\"rustls/ring\",\"webpki-roots\"],\"_unstable-doc\":[\"sqlx-toml\"],\"any\":[],\"default\":[],\"json\":[\"serde\",\"serde_json\"],\"migrate\":[\"sha2\",\"crc\"],\"offline\":[\"serde\",\"either/serde\"],\"sqlx-toml\":[\"serde\",\"toml/parse\"]},\"strip_prefix\":\"sqlx-core\"}", "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c_sqlx-sqlite": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"2.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"0.4.34\"},{\"default_features\":false,\"features\":[\"async\"],\"name\":\"flume\",\"optional\":false,\"req\":\"0.12.0\"},{\"name\":\"form_urlencoded\",\"req\":\"1.2.2\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":true,\"features\":[],\"name\":\"futures-executor\",\"optional\":false,\"req\":\"0.3.32\"},{\"name\":\"futures-intrusive\",\"req\":\"0.5.0\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"name\":\"futures-util\",\"optional\":false,\"req\":\"0.3.32\"},{\"default_features\":false,\"features\":[\"pkg-config\",\"vcpkg\"],\"name\":\"libsqlite3-sys\",\"optional\":false,\"req\":\">=0.30.1, <0.40.0\"},{\"name\":\"log\",\"req\":\"0.4.18\"},{\"name\":\"percent-encoding\",\"req\":\"2.3.0\"},{\"default_features\":true,\"features\":[],\"name\":\"regex\",\"optional\":true,\"req\":\"1.6.0\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"1.0.219\"},{\"default_features\":true,\"features\":[],\"name\":\"sqlx-core\",\"optional\":false,\"req\":\"=0.9.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"thiserror\",\"optional\":false,\"req\":\"2.0.18\"},{\"default_features\":true,\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"0.3.48\"},{\"default_features\":true,\"features\":[\"log\"],\"name\":\"tracing\",\"optional\":false,\"req\":\"0.1.37\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":false,\"req\":\"2.2.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"1.12.1\"}],\"features\":{\"_unstable-all-sqlite-features\":[\"deserialize\",\"load-extension\",\"preupdate-hook\",\"unlock-notify\"],\"_unstable-all-types\":[\"json\",\"chrono\",\"time\",\"uuid\"],\"_unstable-docs\":[\"bundled\",\"any\",\"_unstable-all-types\",\"_unstable-all-sqlite-features\"],\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[],\"bundled\":[\"libsqlite3-sys/bundled\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"deserialize\":[],\"json\":[\"sqlx-core/json\",\"serde\"],\"load-extension\":[],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\",\"serde\"],\"preupdate-hook\":[\"libsqlite3-sys/preupdate_hook\"],\"regexp\":[\"dep:regex\"],\"rust_decimal\":[],\"sqlx-toml\":[\"sqlx-core/sqlx-toml\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"unbundled\":[\"libsqlite3-sys/buildtime_bindgen\"],\"unlock-notify\":[\"libsqlite3-sys/unlock_notify\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]},\"strip_prefix\":\"sqlx-sqlite\"}", @@ -1402,8 +1402,8 @@ "git_archive_integrity:https://codeload.github.com/modelcontextprotocol/rust-sdk/tar.gz/b11a40d889e022087d7f2b8cd23aa28e19ceaf5b": "sha256-XnxwrRom1XXDnqU9ncs0vl6FAGjugZOqqNTMcjIhjF4=", "git_archive_integrity:https://codeload.github.com/openai-oss-forks/crossterm/tar.gz/37ca4a27a9424ec5dbe6451f48c339d7b45f8d63": "sha256-fV3gck+w2FAgr+WN25mjmjYXiz4FYdMifrFXIDHc1dw=", "git_archive_integrity:https://codeload.github.com/openai-oss-forks/rusty_v8/tar.gz/90a65f887a0c0f048f3784afbcb320b373c8a2e0": "sha256-sLGI0fHYUavXgzeBiiihXoTxQ7CCzpZpdukgZhdoQ3M=", - "git_archive_integrity:https://codeload.github.com/openai-oss-forks/tokio-tungstenite/tar.gz/7447c427513cfe685f236e1ac0513c4ea3dd9c0b": "sha256-RqW7OJVRvLIWfDNmNfxOcxrYW1dy5M6LrBwvXdCqfLw=", - "git_archive_integrity:https://codeload.github.com/openai-oss-forks/tungstenite-rs/tar.gz/bc589d684755a8c02da0fc7e58d0861cbfc306f1": "sha256-1wR/jnCUwIJevFAotK6wvvee02nkOj4lCzLhdV29c18=", + "git_archive_integrity:https://codeload.github.com/openai-oss-forks/tokio-tungstenite/tar.gz/7a920470d62138955446b64220c7609e46ad770e": "sha256-6mQQ73y6iQH8fELwe23XzAk+bKejYYN7fE2mFR2yZIY=", + "git_archive_integrity:https://codeload.github.com/openai-oss-forks/tungstenite-rs/tar.gz/e19950ef7828cb311e6d51a6bedcebf0192e055c": "sha256-JQKcQPDLvwscwVKsp4/gExLCQVt8kMjWiz15t7K5YsE=", "git_archive_integrity:https://codeload.github.com/rust-lang/rust-clippy/tar.gz/21baba9c10c5d179915cae82e6247bc2337872fb": "sha256-hoAjPoWso23OSqakAcd6ghJRUEZp1CiOnHQPZpRNFS4=", "git_archive_integrity:https://codeload.github.com/transact-rs/sqlx/tar.gz/10462fa4414c6c7f1ed1d39bb31678e3b726878c": "sha256-jFe976E+ztpfve0rVarAyR59YIlWuCD4HS7GstpgFN4=", "gix-actor_0.44.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"std\",\"unicode\"],\"name\":\"bstr\",\"req\":\"^1.12.0\"},{\"name\":\"document-features\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"gix-date\",\"req\":\"^0.18.0\"},{\"features\":[\"bstr\"],\"name\":\"gix-error\",\"req\":\"^0.5.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.46.3\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.114\"}],\"features\":{\"serde\":[\"dep:serde\",\"bstr/serde\",\"gix-date/serde\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 24f580f9cd..fedfd070ea 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2075,6 +2075,7 @@ dependencies = [ "eventsource-stream", "futures", "http 1.4.0", + "log", "pretty_assertions", "rcgen", "regex-lite", @@ -16248,7 +16249,7 @@ dependencies = [ [[package]] name = "tokio-tungstenite" version = "0.28.0" -source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7447c427513cfe685f236e1ac0513c4ea3dd9c0b#7447c427513cfe685f236e1ac0513c4ea3dd9c0b" +source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7a920470d62138955446b64220c7609e46ad770e#7a920470d62138955446b64220c7609e46ad770e" dependencies = [ "futures-util", "log", @@ -16741,7 +16742,7 @@ dependencies = [ [[package]] name = "tungstenite" version = "0.27.0" -source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=bc589d684755a8c02da0fc7e58d0861cbfc306f1#bc589d684755a8c02da0fc7e58d0861cbfc306f1" +source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=e19950ef7828cb311e6d51a6bedcebf0192e055c#e19950ef7828cb311e6d51a6bedcebf0192e055c" dependencies = [ "bytes", "data-encoding", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index b7dc8f3003..6461ebe703 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -686,12 +686,12 @@ crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "37ca # the same reviewed source until a release includes transact-rs/sqlx#4502. sqlx-core = { git = "https://github.com/transact-rs/sqlx", rev = "10462fa4414c6c7f1ed1d39bb31678e3b726878c" } sqlx-sqlite = { git = "https://github.com/transact-rs/sqlx", rev = "10462fa4414c6c7f1ed1d39bb31678e3b726878c" } -tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7447c427513cfe685f236e1ac0513c4ea3dd9c0b" } -tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "bc589d684755a8c02da0fc7e58d0861cbfc306f1" } +tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7a920470d62138955446b64220c7609e46ad770e" } +tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "e19950ef7828cb311e6d51a6bedcebf0192e055c" } v8 = { git = "https://github.com/openai-oss-forks/rusty_v8.git", rev = "90a65f887a0c0f048f3784afbcb320b373c8a2e0" } # Uncomment to debug local changes. # rmcp = { path = "../../rust-sdk/crates/rmcp" } [patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"] -tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "bc589d684755a8c02da0fc7e58d0861cbfc306f1" } +tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "e19950ef7828cb311e6d51a6bedcebf0192e055c" } diff --git a/codex-rs/codex-api/Cargo.toml b/codex-rs/codex-api/Cargo.toml index bc82dd0b92..856d1e6c08 100644 --- a/codex-rs/codex-api/Cargo.toml +++ b/codex-rs/codex-api/Cargo.toml @@ -35,6 +35,7 @@ uuid = { workspace = true } [dev-dependencies] anyhow = { workspace = true } assert_matches = { workspace = true } +log = { workspace = true } pretty_assertions = { workspace = true } rcgen = { workspace = true } tempfile = { workspace = true } diff --git a/codex-rs/codex-api/tests/responses_websocket_logging.rs b/codex-rs/codex-api/tests/responses_websocket_logging.rs new file mode 100644 index 0000000000..d96d2473d0 --- /dev/null +++ b/codex-rs/codex-api/tests/responses_websocket_logging.rs @@ -0,0 +1,208 @@ +//! Private connector results must reach the wire without entering native frame logs. + +#![allow(clippy::expect_used)] + +use std::net::TcpListener; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::OnceLock; +use std::thread::ThreadId; +use std::time::Duration; + +use anyhow::Result; +use codex_api::AuthProvider; +use codex_api::Provider; +use codex_api::ResponseCreateWsRequest; +use codex_api::ResponseEvent; +use codex_api::ResponsesWebsocketClient; +use codex_api::ResponsesWsRequest; +use codex_api::RetryConfig; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; +use codex_protocol::models::ExecutedToolCall; +use codex_protocol::models::ResponseItem; +use codex_protocol::models::ToolResultBody; +use futures::StreamExt; +use http::HeaderMap; +use pretty_assertions::assert_eq; +use serde_json::Value; +use serde_json::json; + +struct NoAuth; + +impl AuthProvider for NoAuth { + fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> { + Ok(()) + } +} + +struct ClientLogs { + thread: ThreadId, + records: Mutex>, +} + +impl log::Log for ClientLogs { + fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool { + true + } + + fn log(&self, record: &log::Record<'_>) { + // The mock server receives private bytes too; only inspect the client's diagnostics. + if std::thread::current().id() == self.thread { + self.records + .lock() + .expect("log recorder lock") + .push((record.target().to_owned(), record.args().to_string())); + } + } + + fn flush(&self) {} +} + +#[tokio::test(flavor = "current_thread")] +async fn connector_results_reach_websocket_without_payload_logs() -> Result<()> { + // Keep this in its own integration binary: log's logger is process-global. + static LOGS: OnceLock = OnceLock::new(); + let logs = LOGS.get_or_init(|| ClientLogs { + thread: std::thread::current().id(), + records: Mutex::new(Vec::new()), + }); + log::set_logger(logs).expect("install independent log-facade recorder"); + log::set_max_level(log::LevelFilter::Trace); + tracing::dispatcher::with_default(&tracing::Dispatch::none(), || { + log::trace!("independent logger control"); + }); + + const TIMEOUT: Duration = Duration::from_secs(5); + const RESULT: &str = "PRIVATE_CONNECTOR_FRAME_RESULT"; + const CALL_ID: &str = "exec-abcd1234-bcde-4123-9abc-123456789abc"; + let listener = TcpListener::bind("127.0.0.1:0")?; + let address = listener.local_addr()?; + let server = std::thread::spawn(move || -> Result { + let (stream, _) = listener.accept()?; + stream.set_read_timeout(Some(TIMEOUT))?; + stream.set_write_timeout(Some(TIMEOUT))?; + // Decline optional compression so leaked payload bytes remain recognizable. + let mut socket = tungstenite::accept_with_config( + stream, + Some(tungstenite::protocol::WebSocketConfig::default()), + )?; + let request = serde_json::from_str(&socket.read()?.into_text()?)?; + socket.send(tungstenite::Message::text( + json!({"type": "response.completed", "response": {"id": "resp_test"}}).to_string(), + ))?; + Ok(request) + }); + let client = ResponsesWebsocketClient::new( + Provider { + name: "logging fixture".into(), + base_url: format!("http://{address}"), + query_params: None, + headers: HeaderMap::new(), + retry: RetryConfig { + max_attempts: 1, + base_delay: Duration::from_millis(/*millis*/ 1), + retry_429: false, + retry_5xx: false, + retry_transport: false, + }, + stream_idle_timeout: TIMEOUT, + }, + Arc::new(NoAuth), + ); + let connection = tokio::time::timeout( + TIMEOUT, + client.connect( + &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + HeaderMap::new(), + HeaderMap::new(), + /*turn_state*/ None, + /*telemetry*/ None, + ), + ) + .await??; + let mut item: ResponseItem = serde_json::from_value(json!({ + "type": "function_call_output", "call_id": "outer", "output": "one match", + }))?; + item.append_executed_tool_calls(vec![ExecutedToolCall::new( + "mcp__codex_apps__search".into(), + json!({}), + )]); + let result = json!({"content": [{"type": "text", "text": RESULT}]}); + let mut body = ToolResultBody::from_mcp_result(&serde_json::from_value(result.clone())?) + .expect("eligible connector result"); + body.set_nested_call_id(CALL_ID); + let input = [item]; + let request = ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { + model: "gpt-test", + stream: true, + service_tier: None, + previous_response_id: None, + input: &input, + tool_results: vec![(0, 0, Arc::new(body))], + tools: None, + tool_choice: "auto", + parallel_tool_calls: false, + reasoning: None, + store: false, + stream_options: None, + include: &[], + prompt_cache_key: None, + prompt_cache_options: None, + text: None, + generate: None, + client_metadata: None, + access_programs: None, + request_country: &Default::default(), + }); + let canonical = serde_json::to_value(&request)?; + let mut expected = canonical.clone(); + let call = &mut expected["input"][0]["internal_chat_message_metadata_passthrough"]["executed_tool_calls"] + [0]; + call["tool_result"] = result; + call["tool_result_call_id"] = json!(CALL_ID); + let mut observed = bytes::Bytes::new(); + let mut events = connection + .stream_request_with_observer( + request, + /*connection_reused*/ false, + /*turn_state*/ None, + |json| observed = json.clone(), + ) + .await?; + assert_eq!(serde_json::from_slice::(&observed)?, canonical); + let completed = tokio::time::timeout(TIMEOUT, async { + let mut completed = false; + while let Some(event) = events.next().await { + completed |= matches!(event?, ResponseEvent::Completed { .. }); + } + Ok::<_, codex_api::ApiError>(completed) + }) + .await??; + assert!(completed, "native client must receive completion"); + assert_eq!(server.join().expect("server thread")?, expected); + + let records = logs.records.lock().expect("log recorder lock"); + assert!( + records + .iter() + .any(|(_, text)| text == "independent logger control") + ); + for (target, prefix) in [ + ("tungstenite::protocol", "Sending frame"), + ("tungstenite::protocol::frame", "writing frame"), + ] { + assert!( + records + .iter() + .any(|(name, text)| name == target && text.starts_with(prefix)) + ); + } + let diagnostics = format!("{records:?}"); + for marker in [RESULT, CALL_ID] { + let hex: String = marker.bytes().map(|byte| format!("{byte:02x}")).collect(); + assert!(!diagnostics.contains(marker), "frame log exposed plaintext"); + assert!(!diagnostics.contains(&hex), "frame log exposed hex payload"); + } + Ok(()) +} diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index a28986adfd..9fa408ad5a 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -2377,6 +2377,11 @@ impl ModelClientSession { let responses_headers = self .client .responses_headers(client_setup.auth.as_ref(), &model_info.slug); + let result_body_destination = sampling_result_destination( + &client_setup, + include_internal && self.client.captures_result_bodies(), + &responses_headers, + ); tracing::Span::current().record("api.path", "/responses"); let request_auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), @@ -2629,6 +2634,18 @@ impl ModelClientSession { ), ], ); + // Prewarm selects the inference route but never carries private result bodies. + let result_body_destination = if warmup { + None + } else { + result_body_destination + }; + let ResponsesWsRequest::ResponseCreate(payload) = &mut ws_request; + payload.tool_results = self.client.sampling_result_bodies( + responses_metadata, + result_body_destination.as_ref(), + payload.input, + ); let stream_result = websocket_connection .stream_request_with_observer( ws_request, diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 017ef5d31f..0b8cbdf86e 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -2376,6 +2376,213 @@ fn assert_nested_apps_call_ids(rpcs: &[Value]) { } } +#[tokio::test] +async fn websocket_custom_provider_omits_private_exec_and_late_wait_results_on_retry() -> Result<()> +{ + let case = ResultBodyCase::Shared(None); + skip_if_no_network!(Ok(())); + use tracing_subscriber::util::SubscriberInitExt; + // Keep the socket pump on this thread so its trace subscriber is local to the test. + let trace = tempfile::NamedTempFile::new()?; + let _subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_env_filter("tungstenite::protocol=trace") + .with_writer(trace.reopen()?) + .finish() + .set_default(); + let apps = responses::start_mock_server().await; + let apps_server = AppsTestServer::mount(&apps).await?; + // Hold the third RPC until the model has already received its call inventory. + let (reached, admitted) = oneshot::channel(); + let (release_result, held) = std::sync::mpsc::channel(); + let gate = Mutex::new(Some((reached, held))); + let result = serde_json::json!({"content": [{"type":"text", "text":"late private result"}]}); + Mock::given(body_partial_json( + serde_json::json!({"method":"tools/call","params":{"arguments":{"title":"late"}}}), + )) + .respond_with(move |request: &Request| { + let (reached, held) = gate.lock().unwrap().take().unwrap(); + reached.send(()).unwrap(); + held.recv_timeout(Duration::from_secs(30)).unwrap(); + let rpc: Value = serde_json::from_slice(&request.body).unwrap(); + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"jsonrpc":"2.0", "id":rpc["id"], "result":result})) + }) + .with_priority(/*p*/ 1) + .mount(&apps) + .await; + let code = "const t = ALL_TOOLS.find(t => t.name.endsWith('create_event')); \ + for (const title of ['first', 'second']) await tools[t.name]({title, starts_at: 'noon'}); \ + const pending = tools[t.name]({title:'late', starts_at:'noon'}); \ + yield_control(); await pending; text('done')"; + let mut exec = ev_custom_tool_call("call-events", "exec", code); + exec["item"]["id"] = "exec-events".into(); + let wait = |id, ms| { + let args = serde_json::json!({"cell_id":"1", "yield_time_ms":ms}); + let call = responses::ev_function_call(id, "wait", &args.to_string()); + vec![ev_response_created(id), call, ev_completed(id)] + }; + // Each of the first two sockets closes before completing the tool-output request. + let switch = ev_response_created("interrupted"); + let server = responses::start_websocket_server(vec![ + vec![ + vec![ev_response_created("warmup"), ev_completed("warmup")], + vec![ev_response_created("resp-1"), exec, ev_completed("resp-1")], + wait("poll", /*ms*/ 1), + wait("wait", /*ms*/ 10_000), + vec![], + ], + vec![vec![switch.clone()]], + vec![vec![ev_response_created("resp-2"), ev_completed("resp-2")]], + ]) + .await; + let release = server.gate_response_event(&switch); + let poll = server.gate_response_event(&ev_response_created("poll")); + let mut builder = case + .builder(apps_server.chatgpt_base_url, AuthMode::Headers) + .with_config(|config| { + // This test isolates result authorization across retries with full inventory enabled. + config + .features + .enable(Feature::ExecutedToolCallMetadata) + .unwrap(); + config.model_provider.stream_max_retries = Some(2); + }); + let test = builder.build_with_websocket_server(&server).await?; + let rotate = async { + // Yield can precede admission. Poll while the admitted result is still held. + admitted.await?; + poll.send(()).unwrap(); + server + .wait_for_request(/*connection_index*/ 0, /*request_index*/ 3) + .await; + release_result.send(())?; + tokio::time::timeout( + Duration::from_secs(30), + server.wait_for_request(/*connection_index*/ 1, /*request_index*/ 0), + ) + .await?; + struct OtherAccount; + impl codex_login::ExternalAuth for OtherAccount { + fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { + Box::pin(async { Ok(hosted_result_auth("other-account")) }) + } + fn refresh( + &self, + _: codex_login::ExternalAuthRefreshContext, + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { + self.resolve() + } + } + test.thread_manager + .auth_manager() + .set_external_auth(Arc::new(OtherAccount)) + .await?; + release.send(()).expect("release retry under second owner"); + anyhow::Ok(()) + }; + tokio::try_join!(test.submit_turn("Create calendar events"), rotate)?; + + let connections = server.connections(); + assert_eq!( + connections.iter().map(Vec::len).collect::>(), + [5, 1, 1] + ); + assert_eq!(connections[0][0].body_json()["generate"], false); + let delta = connections[0][2].body_json(); + assert_eq!(delta["previous_response_id"], "resp-1"); + let retry = connections[1][0].body_json(); + // Retrying across owners must preserve only the ordinary conversation on this provider. + let mut expected = connections[2][0].body_json(); + assert!(expected.get("previous_response_id").is_none()); + assert!(expected.get("tool_results").is_none()); + let private_prefix = "called calendar_create_event for"; + let log = fs::read_to_string(trace.path())?; + // Match each received request to its send. Clear server sends when their responses arrive. + let mut logged = false; + let mut received = 0; + for line in log.lines() { + logged |= line.starts_with("TRACE tungstenite::protocol: Sending frame: opcode=TEXT,"); + if line.starts_with( + r#"TRACE tungstenite::protocol: Received message {"type":"response.create","#, + ) { + received += 1; + assert_eq!(std::mem::take(&mut logged), !line.contains(private_prefix)); + } else if line.starts_with("TRACE tungstenite::protocol: Received message ") { + logged = false; + } + } + assert_eq!(received, connections.iter().map(Vec::len).sum::()); + // The lower-level writer also emits metadata for each traced frame. + assert_eq!( + log.matches("TRACE tungstenite::protocol::frame: writing frame") + .count(), + log.matches("TRACE tungstenite::protocol: Sending frame:") + .count(), + ); + assert!(!expected.to_string().contains(private_prefix)); + assert!(!expected.to_string().contains("tool_result_call_id")); + let timestamp = "x-codex-ws-stream-request-start-ms"; + expected["client_metadata"][timestamp] = retry["client_metadata"][timestamp].clone(); + let input = expected["input"].as_array_mut().unwrap(); + assert!(input.last().unwrap()["output"].to_string().contains("done")); + let output = input + .iter_mut() + .find(|item| item["type"] == "custom_tool_call_output") + .unwrap(); + assert_eq!(output["call_id"], "call-events"); + let calls = output["internal_chat_message_metadata_passthrough"]["executed_tool_calls"] + .as_array_mut() + .unwrap(); + let executed = recorded_apps_tool_calls(&apps).await; + assert_eq!(executed.len(), 3); + assert_nested_apps_call_ids(&executed); + for (call, title) in calls[..2].iter().zip(["first", "second"]) { + assert_eq!( + call["arguments"], + serde_json::json!({"title": title, "starts_at": "noon"}) + ); + assert!(call.get("tool_result").is_none()); + assert!(call.get("tool_result_call_id").is_none()); + } + let late_on_exec = calls.len() == 3; + assert_eq!(delta["input"], serde_json::json!([output])); + let polled = connections[0][3].body_json(); + // A call first reported after the exec yields belongs to the poll output. + let before = if late_on_exec { &delta } else { &polled }; + let bound = before["input"].as_array().unwrap().last().unwrap(); + let origin = input + .iter_mut() + .find(|item| **item == *bound) + .expect("original pending output"); + let calls = &mut origin["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]; + let call = calls.as_array_mut().unwrap().last_mut().unwrap(); + assert_eq!(call["arguments"]["title"], "late"); + assert!(call.get("tool_result").is_none()); + assert!(call.get("tool_result_call_id").is_none()); + assert!(!retry.to_string().contains("late private result")); + assert_eq!(retry, expected); + let completed = connections[0][4].body_json(); + let wait_output = expected["input"].as_array().unwrap().last().unwrap(); + assert_eq!(wait_output["call_id"], "wait"); + if completed.get("previous_response_id").is_some() { + expected["input"] = serde_json::json!([wait_output]); + expected["previous_response_id"] = "wait".into(); + } + expected["client_metadata"][timestamp] = completed["client_metadata"][timestamp].clone(); + assert_eq!(completed, expected); + let accounts: Vec<_> = server + .handshakes() + .iter() + .map(|h| h.header("chatgpt-account-id").unwrap()) + .collect(); + assert_eq!(accounts, ["account_id", "account_id", "other-account"]); + test.codex.shutdown_and_wait().await?; + server.shutdown().await; + Ok(()) +} + #[derive(Clone, Copy, PartialEq, Eq)] enum ResultBodyCase { Ungranted,