diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 41e63c90..4602f329 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2005,34 +2005,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "codex-analytics" -version = "0.0.0" -dependencies = [ - "codex-app-server-protocol", - "codex-features", - "codex-git-utils", - "codex-http-client", - "codex-login", - "codex-model-provider", - "codex-model-provider-info", - "codex-plugin", - "codex-protocol", - "codex-runtime-agent-instance", - "codex-state", - "codex-utils-absolute-path", - "codex-utils-path-uri", - "http 1.4.0", - "os_info", - "pretty_assertions", - "serde", - "serde_json", - "sha1 0.10.6", - "tokio", - "tracing", - "wiremock", -] - [[package]] name = "codex-ansi-escape" version = "0.0.0" @@ -2093,7 +2065,6 @@ dependencies = [ "chrono", "clap", "codex-agent-message-board-host", - "codex-analytics", "codex-app-server-daemon", "codex-app-server-protocol", "codex-app-server-transport", @@ -2669,7 +2640,6 @@ dependencies = [ "codex-code-mode-runtime", "codex-http-client", "codex-otel", - "codex-otel-trace-websocket", "codex-plugin-host", "codex-protocol", "codex-utils-cargo-bin", @@ -2843,7 +2813,6 @@ dependencies = [ "codex-agent-graph-store", "codex-agent-message-board-host", "codex-agent-roles", - "codex-analytics", "codex-api", "codex-app-server-protocol", "codex-apply-patch", @@ -2985,7 +2954,6 @@ dependencies = [ name = "codex-core-api" version = "0.0.0" dependencies = [ - "codex-analytics", "codex-app-server-protocol", "codex-arg0", "codex-config", @@ -3023,7 +2991,6 @@ dependencies = [ "anyhow", "base64 0.22.1", "chrono", - "codex-analytics", "codex-api", "codex-app-server-protocol", "codex-config", @@ -3364,7 +3331,6 @@ name = "codex-external-agent-migration" version = "0.0.0" dependencies = [ "chrono", - "codex-analytics", "codex-app-server-protocol", "codex-config", "codex-core", @@ -3409,26 +3375,18 @@ name = "codex-feedback" version = "0.0.0" dependencies = [ "anyhow", - "bytes", - "codex-http-client", "codex-login", "codex-protocol", "codex-rollout", "codex-state", - "flate2", - "http 1.4.0", - "httpdate", "log", "mime_guess", "pretty_assertions", - "sentry", "serde_json", - "tar", "tempfile", "tokio", "tracing", "tracing-subscriber", - "wiremock", "zip", ] @@ -3515,7 +3473,6 @@ version = "0.0.0" dependencies = [ "anyhow", "chrono", - "codex-analytics", "codex-core", "codex-extension-api", "codex-otel", @@ -3553,7 +3510,6 @@ name = "codex-guardian-reviewer" version = "0.0.0" dependencies = [ "anyhow", - "codex-analytics", "codex-context-fragments", "codex-extension-api", "codex-features", @@ -3592,7 +3548,6 @@ dependencies = [ "anyhow", "base64 0.22.1", "codex-agent-identity", - "codex-analytics", "codex-api", "codex-config", "codex-context-fragments", @@ -3633,7 +3588,6 @@ version = "0.0.0" dependencies = [ "anyhow", "chrono", - "codex-analytics", "codex-attachment-store", "codex-context-fragments", "codex-core", @@ -3676,7 +3630,6 @@ dependencies = [ name = "codex-history-notes-extension" version = "0.0.0" dependencies = [ - "codex-analytics", "codex-client", "codex-config", "codex-core", @@ -4355,33 +4308,22 @@ dependencies = [ name = "codex-otel" version = "0.0.0" dependencies = [ - "bytes", "chrono", "codex-api", - "codex-http-client", "codex-protocol", - "codex-utils-absolute-path", "codex-utils-stream-parser", "codex-utils-string", "eventsource-stream", - "gethostname", "http 1.4.0", - "libc", "opentelemetry", - "opentelemetry-appender-tracing", - "opentelemetry-http", - "opentelemetry-otlp", "opentelemetry-semantic-conventions", "opentelemetry_sdk", "os_info", "pretty_assertions", - "rcgen", "reqwest 0.12.28", - "seccompiler", "serde", "serde_json", "strum_macros 0.28.0", - "tempfile", "thiserror 2.0.18", "tokio", "tracing", @@ -4389,17 +4331,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "codex-otel-trace-websocket" -version = "0.0.0" -dependencies = [ - "anyhow", - "axum", - "futures", - "tokio", - "tracing", -] - [[package]] name = "codex-plugin" version = "0.0.0" @@ -4789,7 +4720,6 @@ version = "0.0.0" dependencies = [ "assert_matches", "blake3", - "codex-analytics", "codex-attachment-store", "codex-config", "codex-core-plugin-common", @@ -5707,18 +5637,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "const-hex" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bb320cac8a0750d7f25280aa97b09c26edfe161164238ecbbb31092b079e735" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "proptest", - "serde_core", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -5863,7 +5781,6 @@ dependencies = [ "base64 0.22.1", "codex-agent-graph-store", "codex-agent-message-board-host", - "codex-analytics", "codex-arg0", "codex-attachment-store", "codex-config", @@ -6494,16 +6411,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" -[[package]] -name = "debugid" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" -dependencies = [ - "serde", - "uuid", -] - [[package]] name = "debugserver-types" version = "0.5.0" @@ -11227,68 +11134,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "opentelemetry-appender-tracing" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef6a1ac5ca3accf562b8c306fa8483c85f4390f768185ab775f242f7fe8fdcc2" -dependencies = [ - "opentelemetry", - "tracing", - "tracing-core", - "tracing-subscriber", -] - -[[package]] -name = "opentelemetry-http" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a6d09a73194e6b66df7c8f1b680f156d916a1a942abf2de06823dd02b7855d" -dependencies = [ - "async-trait", - "bytes", - "http 1.4.0", - "opentelemetry", - "reqwest 0.12.28", -] - -[[package]] -name = "opentelemetry-otlp" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2366db2dca4d2ad033cad11e6ee42844fd727007af5ad04a1730f4cb8163bf" -dependencies = [ - "http 1.4.0", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-proto", - "opentelemetry_sdk", - "prost", - "reqwest 0.12.28", - "serde_json", - "thiserror 2.0.18", - "tokio", - "tonic", - "tracing", -] - -[[package]] -name = "opentelemetry-proto" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7175df06de5eaee9909d4805a3d07e28bb752c34cab57fa9cff549da596b30f" -dependencies = [ - "base64 0.22.1", - "const-hex", - "opentelemetry", - "opentelemetry_sdk", - "prost", - "serde", - "serde_json", - "tonic", - "tonic-prost", -] - [[package]] name = "opentelemetry-semantic-conventions" version = "0.31.0" @@ -12018,21 +11863,6 @@ dependencies = [ "parking_lot", ] -[[package]] -name = "proptest" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee689443a2bd0a16ab0348b52ee43e3b2d1b1f931c8aa5c9f8de4c86fbe8c40" -dependencies = [ - "bitflags 2.13.1", - "num-traits", - "rand 0.9.3", - "rand_chacha 0.9.0", - "rand_xorshift", - "regex-syntax", - "unarray", -] - [[package]] name = "prost" version = "0.14.3" @@ -12781,15 +12611,6 @@ dependencies = [ "regex-syntax", ] -[[package]] -name = "rand_xorshift" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" -dependencies = [ - "rand_core 0.9.5", -] - [[package]] name = "ratatui" version = "0.30.2" @@ -13052,7 +12873,6 @@ dependencies = [ "cookie", "cookie_store", "encoding_rs", - "futures-channel", "futures-core", "futures-util", "h2", @@ -14028,45 +13848,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "sentry" -version = "0.46.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f925d575b468e88b079faf590a8dd0c9c99e2ec29e9bab663ceb8b45056312f" -dependencies = [ - "sentry-core", -] - -[[package]] -name = "sentry-core" -version = "0.46.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26ab054c34b87f96c3e4701bea1888317cde30cc7e4a6136d2c48454ab96661c" -dependencies = [ - "rand 0.9.3", - "sentry-types", - "serde", - "serde_json", - "url", -] - -[[package]] -name = "sentry-types" -version = "0.46.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eecbd63e9d15a26a40675ed180d376fcb434635d2e33de1c24003f61e3e2230d" -dependencies = [ - "debugid", - "hex", - "rand 0.9.3", - "serde", - "serde_json", - "thiserror 2.0.18", - "time", - "url", - "uuid", -] - [[package]] name = "sequence_trie" version = "0.3.6" @@ -16394,12 +16175,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - [[package]] name = "unic-langid" version = "0.9.6" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 18fd7e02..e4e2308b 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -1,7 +1,6 @@ [workspace] members = [ "aws-auth", - "analytics", "agent-graph-store", "agent-message-board-client", "agent-message-board-host", @@ -107,7 +106,6 @@ members = [ "sandboxing", "stdio-to-uds", "otel", - "otel-trace-websocket", "tcp-tunnel", "tui", "user-verification", @@ -177,7 +175,6 @@ license = "Apache-2.0" # Internal codex-realtime-webrtc = { path = "realtime-webrtc" } app_test_support = { path = "app-server/tests/common" } -codex-analytics = { path = "analytics" } codex-agent-graph-store = { path = "agent-graph-store" } codex-agent-identity = { path = "agent-identity" } codex-agent-roles = { path = "agent-roles" } @@ -267,7 +264,6 @@ codex-mxc-sandbox = { path = "mxc-sandbox" } codex-network-proxy = { path = "network-proxy" } codex-ollama = { path = "ollama" } codex-otel = { path = "otel" } -codex-otel-trace-websocket = { path = "otel-trace-websocket" } codex-plugin = { path = "plugin" } codex-model-provider = { path = "model-provider" } codex-process-hardening = { path = "process-hardening" } @@ -429,8 +425,6 @@ nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faa once_cell = "1.20.2" openssl-sys = "*" opentelemetry = "0.31.0" -opentelemetry-appender-tracing = "0.31.0" -opentelemetry-otlp = "0.31.0" opentelemetry-semantic-conventions = "0.31.0" opentelemetry_sdk = "0.31.0" os_info = "3.12.0" @@ -470,7 +464,6 @@ rustls-pki-types = "1.14.0" schemars = "0.8.22" seccompiler = "0.5.0" semver = "1.0" -sentry = "0.46.0" serde = { version = "1", features = ["rc"] } serde_ignored = "0.1.14" serde_json = "1" diff --git a/codex-rs/analytics/BUILD.bazel b/codex-rs/analytics/BUILD.bazel deleted file mode 100644 index aec07c87..00000000 --- a/codex-rs/analytics/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "analytics", - crate_name = "codex_analytics", -) diff --git a/codex-rs/analytics/Cargo.toml b/codex-rs/analytics/Cargo.toml deleted file mode 100644 index ad134107..00000000 --- a/codex-rs/analytics/Cargo.toml +++ /dev/null @@ -1,42 +0,0 @@ -[package] -edition.workspace = true -license.workspace = true -name = "codex-analytics" -version.workspace = true - -[lib] -doctest = false -name = "codex_analytics" -path = "src/lib.rs" - -[lints] -workspace = true - -[dependencies] -codex-features = { workspace = true } -codex-app-server-protocol = { workspace = true } -codex-git-utils = { workspace = true } -codex-http-client = { workspace = true } -codex-runtime-agent-instance = { workspace = true } -codex-login = { workspace = true } -codex-model-provider = { workspace = true } -codex-plugin = { workspace = true } -codex-protocol = { workspace = true } -codex-state = { workspace = true } -codex-utils-path-uri = { workspace = true } -http = { workspace = true } -os_info = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -sha1 = { workspace = true } -tokio = { workspace = true, features = [ - "macros", - "rt-multi-thread", -] } -tracing = { workspace = true, features = ["log"] } - -[dev-dependencies] -codex-model-provider-info = { workspace = true } -wiremock = { workspace = true } -codex-utils-absolute-path = { workspace = true } -pretty_assertions = { workspace = true } diff --git a/codex-rs/analytics/src/accepted_lines.rs b/codex-rs/analytics/src/accepted_lines.rs deleted file mode 100644 index 8bb91859..00000000 --- a/codex-rs/analytics/src/accepted_lines.rs +++ /dev/null @@ -1,187 +0,0 @@ -use crate::events::CodexAcceptedLineFingerprintsEventParams; -use crate::events::CodexAcceptedLineFingerprintsEventRequest; -use crate::events::TrackEventRequest; -use codex_git_utils::canonicalize_git_remote_url; -use codex_git_utils::get_git_remote_urls_assume_git_repo; -use sha1::Digest; -use std::path::Path; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct AcceptedLineCounts { - pub(crate) accepted_added_lines: u64, - pub(crate) accepted_deleted_lines: u64, -} - -pub(crate) struct AcceptedLineFingerprintEventInput { - pub(crate) event_type: &'static str, - pub(crate) turn_id: String, - pub(crate) thread_id: String, - pub(crate) product_surface: Option, - pub(crate) model_slug: Option, - pub(crate) completed_at: u64, - pub(crate) repo_hash: Option, - pub(crate) accepted_added_lines: u64, - pub(crate) accepted_deleted_lines: u64, -} - -pub(crate) fn accepted_line_counts_from_unified_diff(unified_diff: &str) -> AcceptedLineCounts { - let mut in_hunk = false; - let mut accepted_added_lines = 0; - let mut accepted_deleted_lines = 0; - - for line in unified_diff.lines() { - if line.starts_with("diff --git ") { - in_hunk = false; - continue; - } - - if line.starts_with("@@ ") { - in_hunk = true; - continue; - } - - if !in_hunk && (line.starts_with("+++ ") || line.starts_with("--- ")) { - continue; - } - - if line.starts_with('+') { - accepted_added_lines += 1; - continue; - } - - if line.starts_with('-') { - accepted_deleted_lines += 1; - } - } - - AcceptedLineCounts { - accepted_added_lines, - accepted_deleted_lines, - } -} - -pub fn fingerprint_hash(domain: &str, value: &str) -> String { - let mut hasher = sha1::Sha1::new(); - hasher.update(b"file-line-v1\0"); - hasher.update(domain.as_bytes()); - hasher.update(b"\0"); - hasher.update(value.as_bytes()); - format!("{:x}", hasher.finalize()) -} - -pub(crate) fn accepted_line_fingerprint_event_requests( - input: AcceptedLineFingerprintEventInput, -) -> Vec { - let AcceptedLineFingerprintEventInput { - event_type, - turn_id, - thread_id, - product_surface, - model_slug, - completed_at, - repo_hash, - accepted_added_lines, - accepted_deleted_lines, - } = input; - - vec![TrackEventRequest::AcceptedLineFingerprints(Box::new( - CodexAcceptedLineFingerprintsEventRequest { - event_type: "codex_accepted_line_fingerprints", - event_params: CodexAcceptedLineFingerprintsEventParams { - event_type, - turn_id, - thread_id, - product_surface, - model_slug, - completed_at, - repo_hash, - accepted_added_lines, - accepted_deleted_lines, - line_fingerprints: [], - }, - }, - ))] -} - -pub async fn accepted_line_repo_hash_for_cwd(cwd: &Path) -> Option { - let remotes = get_git_remote_urls_assume_git_repo(cwd).await?; - remotes - .get("origin") - .or_else(|| remotes.values().next()) - .map(|remote_url| { - let canonical_remote_url = canonicalize_git_remote_url(remote_url.as_str()) - .unwrap_or_else(|| remote_url.to_string()); - fingerprint_hash("repo", &canonical_remote_url) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_accepted_line_counts() { - let diff = "\ -diff --git a/src/lib.rs b/src/lib.rs -index 1111111..2222222 ---- a/src/lib.rs -+++ b/src/lib.rs -@@ -1,3 +1,5 @@ --old line -+fn useful() { -+} -+ return user.id; - context -"; - - assert_eq!( - accepted_line_counts_from_unified_diff(diff), - AcceptedLineCounts { - accepted_added_lines: 3, - accepted_deleted_lines: 1, - }, - ); - } - - #[test] - fn skips_added_file_metadata_headers() { - let diff = "\ -diff --git a/new.py b/new.py -new file mode 100644 -index 0000000..1111111 ---- /dev/null -+++ b/new.py -@@ -0,0 +1 @@ -+print('hello') -"; - - assert_eq!( - accepted_line_counts_from_unified_diff(diff), - AcceptedLineCounts { - accepted_added_lines: 1, - accepted_deleted_lines: 0, - }, - ); - } - - #[test] - fn parses_hunk_lines_that_look_like_file_headers() { - let diff = "\ -diff --git a/src/lib.rs b/src/lib.rs -index 1111111..2222222 ---- a/src/lib.rs -+++ b/src/lib.rs -@@ -1,2 +1,2 @@ ---- old value -+++ new value -"; - - assert_eq!( - accepted_line_counts_from_unified_diff(diff), - AcceptedLineCounts { - accepted_added_lines: 1, - accepted_deleted_lines: 1, - }, - ); - } -} diff --git a/codex-rs/analytics/src/analytics_capture.rs b/codex-rs/analytics/src/analytics_capture.rs deleted file mode 100644 index 7e1dd6eb..00000000 --- a/codex-rs/analytics/src/analytics_capture.rs +++ /dev/null @@ -1,34 +0,0 @@ -use crate::events::TrackEventsRequest; -use std::fs::File; -use std::fs::OpenOptions; -use std::io; -use std::io::Write; -use std::path::Path; - -pub(crate) const ANALYTICS_EVENTS_CAPTURE_FILE_ENV_VAR: &str = - "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE"; - -pub(crate) fn initialize(path: &Path) -> io::Result<()> { - open_capture_file(path).map(drop) -} - -pub(crate) fn append_payload(path: &Path, payload: &TrackEventsRequest) -> io::Result<()> { - let mut line = serde_json::to_vec(payload) - .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; - line.push(b'\n'); - - let mut file = open_capture_file(path)?; - file.write_all(&line)?; - file.flush() -} - -fn open_capture_file(path: &Path) -> io::Result { - let mut options = OpenOptions::new(); - options.create(true).append(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - options.open(path) -} diff --git a/codex-rs/analytics/src/client.rs b/codex-rs/analytics/src/client.rs deleted file mode 100644 index bdbf00c2..00000000 --- a/codex-rs/analytics/src/client.rs +++ /dev/null @@ -1,1277 +0,0 @@ -use crate::events::AppServerRpcTransport; -use crate::events::GuardianReviewAnalyticsResult; -use crate::events::GuardianReviewTrackContext; -use crate::events::TrackEventRequest; -use crate::events::TrackEventsRequest; -use crate::events::current_runtime_metadata; -use crate::facts::AnalyticsFact; -use crate::facts::AnalyticsJsonRpcError; -use crate::facts::AppInvocation; -use crate::facts::AppMentionedInput; -use crate::facts::AppUsedInput; -use crate::facts::ArtifactOperation; -use crate::facts::ArtifactOperationInput; -use crate::facts::CodexGoalEvent; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::ExternalAgentConfigImportCompletedInput; -use crate::facts::ExternalAgentConfigImportFailureInput; -use crate::facts::HookRunFact; -use crate::facts::HookRunInput; -use crate::facts::ImagePreparationFact; -use crate::facts::McpToolCallElicitation; -use crate::facts::PluginInstallFailedInput; -use crate::facts::PluginInstallRequested; -use crate::facts::PluginInstallRequestedInput; -use crate::facts::PluginInstallSource; -use crate::facts::PluginMeasurementsInput; -use crate::facts::PluginState; -use crate::facts::PluginStateChangedInput; -use crate::facts::SkillInvocation; -use crate::facts::SkillInvokedInput; -use crate::facts::SubAgentThreadStartedInput; -use crate::facts::TrackEventsContext; -use crate::facts::TurnCodexErrorFact; -use crate::facts::TurnProfileFact; -use crate::facts::TurnResolvedConfigFact; -use crate::facts::TurnTokenUsageFact; -use crate::guardian_v2::GuardianV2Event; -use crate::now_unix_millis; -use crate::product_attribution::MAX_THREAD_PRODUCTS; -use crate::product_attribution::ThreadProductUpdate; -use crate::product_attribution::ThreadProducts; -use crate::product_attribution::product_event_batches; -use crate::reducer::AnalyticsReducer; -use crate::reducer::MAX_PLUGIN_MEASUREMENTS_PER_BATCH; -use crate::reducer::tracked_tool_item_id; -use crate::reducer::valid_plugin_measurement_identifier; -use crate::reducer::valid_plugin_measurement_row; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ServerResponse; -use codex_app_server_protocol::Turn; -use codex_app_server_protocol::TurnCompletedNotification; -use codex_app_server_protocol::TurnError; -use codex_app_server_protocol::TurnItemsView; -use codex_app_server_protocol::TurnStartedNotification; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::item_event_to_server_notification; -use codex_features::RuntimeAuthMode; -use codex_http_client::OPENAI_ORGANIZATION_HEADER; -use codex_http_client::OPENAI_PROJECT_HEADER; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_model_provider::ChatgptBaseUrl; -use codex_plugin::PluginId; -use codex_plugin::PluginTelemetryMetadata; -use codex_protocol::ThreadId; -use codex_protocol::items::CollabAgentToolCallItem; -use codex_protocol::items::CollabAgentToolCallStatus; -use codex_protocol::items::TurnItem; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; -use codex_protocol::request_permissions::RequestPermissionsResponse; -use codex_runtime_agent_instance::RuntimeAuthSlot; -use http::HeaderMap; -use std::collections::HashSet; -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; -use std::time::Duration; -use tokio::sync::mpsc; -use tokio::sync::oneshot; - -const ANALYTICS_EVENTS_QUEUE_SIZE: usize = 256; -const ANALYTICS_EVENTS_TIMEOUT: Duration = Duration::from_secs(10); -// Covers two sequential POSTs plus queue/barrier scheduling; additional queued sends remain best-effort. -const ANALYTICS_EVENTS_FLUSH_TIMEOUT: Duration = Duration::from_secs(25); -const ANALYTICS_EVENT_DEDUPE_MAX_KEYS: usize = 4096; - -pub(crate) enum AnalyticsEventsQueueMessage { - Fact(Box), - ThreadProduct { - thread_id: String, - product_sku: Option, - generation: u64, - }, - Flush(oneshot::Sender<()>), -} - -#[derive(Clone)] -pub(crate) struct AnalyticsEventsQueue { - pub(crate) sender: mpsc::Sender, - pub(crate) product_generation: Arc, - pub(crate) app_used_emitted_keys: Arc>>, - pub(crate) plugin_used_emitted_keys: Arc>>, -} - -#[derive(Clone)] -pub struct AnalyticsEventsClient { - queue: Option, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -enum AnalyticsEventsDestination { - Http { - base_url: ChatgptBaseUrl, - api_key_headers: HeaderMap, - }, - #[cfg(debug_assertions)] - CaptureFile { path: PathBuf }, -} - -impl AnalyticsEventsDestination { - fn from_base_url(base_url: ChatgptBaseUrl, headers: HeaderMap) -> Self { - let capture_file = analytics_capture_file_from_env(); - let mut destination = Self::from_base_url_and_capture_file(base_url, capture_file); - match &mut destination { - Self::Http { - api_key_headers, .. - } => { - // Model-provider secrets and gateway headers do not belong on analytics requests. - for name in [OPENAI_ORGANIZATION_HEADER, OPENAI_PROJECT_HEADER] { - if let Some(value) = headers.get(name) { - api_key_headers.insert(name, value.clone()); - } - } - } - #[cfg(debug_assertions)] - Self::CaptureFile { .. } => {} - } - destination - } - - fn from_base_url_and_capture_file( - base_url: ChatgptBaseUrl, - capture_file: Option, - ) -> Self { - #[cfg(debug_assertions)] - if let Some(path) = capture_file { - if let Err(err) = crate::analytics_capture::initialize(&path) { - tracing::error!( - path = %path.display(), - "failed to initialize analytics event capture; network delivery remains disabled: {err}" - ); - } - tracing::warn!( - path = %path.display(), - "analytics event capture enabled; network delivery is disabled" - ); - return Self::CaptureFile { path }; - } - - #[cfg(not(debug_assertions))] - let _ = capture_file; - - Self::Http { - base_url, - api_key_headers: HeaderMap::new(), - } - } - - fn url_for_auth(&self, auth: &CodexAuth) -> Option { - match self { - Self::Http { base_url, .. } => { - let base_url = base_url.resolve(auth).trim_end_matches('/'); - Some(format!("{base_url}/codex/analytics-events/events")) - } - #[cfg(debug_assertions)] - Self::CaptureFile { .. } => None, - } - } -} - -fn analytics_capture_file_from_env() -> Option { - #[cfg(debug_assertions)] - { - std::env::var_os(crate::analytics_capture::ANALYTICS_EVENTS_CAPTURE_FILE_ENV_VAR) - .filter(|value| !value.is_empty()) - .map(PathBuf::from) - } - - #[cfg(not(debug_assertions))] - None -} - -impl AnalyticsEventsQueue { - fn new( - auth_manager: Arc, - destination: AnalyticsEventsDestination, - runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>, - ) -> Self { - let (sender, mut receiver) = mpsc::channel(ANALYTICS_EVENTS_QUEUE_SIZE); - let product_generation = Arc::new(AtomicU64::new(0)); - let worker_product_generation = Arc::clone(&product_generation); - tokio::spawn(async move { - let mut reducer = AnalyticsReducer::default(); - let mut thread_products = ThreadProducts::default(); - let mut registered_generation = 0; - while let Some(input) = receiver.recv().await { - let generation = worker_product_generation.load(Ordering::Acquire); - if generation != registered_generation { - // A dropped registration invalidates both current and queued attribution. - thread_products = ThreadProducts::default(); - registered_generation = generation; - } - let input = match input { - AnalyticsEventsQueueMessage::Fact(input) => *input, - AnalyticsEventsQueueMessage::ThreadProduct { - thread_id, - product_sku, - generation, - } => { - if generation != registered_generation { - continue; - } - // Pending tool events belong to the configuration that collected them. - let mut events = Vec::new(); - if thread_products.get(&thread_id) != product_sku.as_deref() { - reducer.flush_thread(&thread_id, &mut events); - } - if product_sku.is_some() - && !thread_products.products.contains_key(&thread_id) - && thread_products.products.len() >= MAX_THREAD_PRODUCTS - && let Some(evicted) = thread_products.registered_threads.front() - { - reducer.flush_thread(evicted, &mut events); - } - send_track_events( - &auth_manager, - &destination, - events, - &thread_products, - runtime_auth.as_ref(), - ) - .await; - thread_products.register(thread_id, product_sku); - continue; - } - AnalyticsEventsQueueMessage::Flush(done_tx) => { - let mut events = Vec::new(); - reducer.flush(&mut events); - send_track_events( - &auth_manager, - &destination, - events, - &thread_products, - runtime_auth.as_ref(), - ) - .await; - let _ = done_tx.send(()); - continue; - } - }; - let mut events = Vec::new(); - reducer.ingest(input, &mut events).await; - send_track_events( - &auth_manager, - &destination, - events, - &thread_products, - runtime_auth.as_ref(), - ) - .await; - } - }); - Self { - sender, - product_generation, - app_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - plugin_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - } - } - - fn try_send(&self, input: AnalyticsFact) { - if self - .sender - .try_send(AnalyticsEventsQueueMessage::Fact(Box::new(input))) - .is_err() - { - //TODO: add a metric for this - tracing::warn!("dropping analytics events: queue is full"); - } - } - - pub(crate) fn should_enqueue_app_used( - &self, - tracking: &TrackEventsContext, - app: &AppInvocation, - ) -> bool { - let Some(connector_id) = app.connector_id.as_ref() else { - return true; - }; - let mut emitted = self - .app_used_emitted_keys - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if emitted.len() >= ANALYTICS_EVENT_DEDUPE_MAX_KEYS { - emitted.clear(); - } - emitted.insert((tracking.turn_id.clone(), connector_id.clone())) - } - - pub(crate) fn should_enqueue_plugin_used( - &self, - tracking: &TrackEventsContext, - plugin: &PluginTelemetryMetadata, - ) -> bool { - let mut emitted = self - .plugin_used_emitted_keys - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if emitted.len() >= ANALYTICS_EVENT_DEDUPE_MAX_KEYS { - emitted.clear(); - } - let Some(plugin_id) = plugin - .plugin_id - .as_ref() - .map(PluginId::as_key) - .or_else(|| plugin.remote_plugin_id.clone()) - else { - return true; - }; - emitted.insert((tracking.turn_id.clone(), plugin_id)) - } -} - -impl AnalyticsEventsClient { - /// Registers this thread's product attribution without changing authentication. - /// A full queue clears shared attribution until threads register again, without blocking startup. - pub fn update_thread_product_sku(&self, thread_id: ThreadId, update: ThreadProductUpdate) { - let product_sku = match update { - ThreadProductUpdate::Set(product) => Some(product), - ThreadProductUpdate::Clear => None, - }; - let Some(queue) = &self.queue else { - return; - }; - if queue - .sender - .try_send(AnalyticsEventsQueueMessage::ThreadProduct { - thread_id: thread_id.to_string(), - product_sku, - generation: queue.product_generation.load(Ordering::Acquire), - }) - .is_err() - { - queue.product_generation.fetch_add(1, Ordering::AcqRel); - tracing::warn!("clearing analytics product attribution: queue is unavailable"); - } - } - - pub fn new( - auth_manager: Arc, - base_url: impl Into, - analytics_enabled: Option, - ) -> Self { - Self::new_with_runtime( - auth_manager, - base_url, - analytics_enabled, - /*runtime_auth*/ None, - /*api_key_headers*/ HeaderMap::new(), - ) - } - - /// Share runtime identity for OpenAI delivery; file capture never authenticates. - pub fn new_with_runtime( - auth_manager: Arc, - base_url: impl Into, - analytics_enabled: Option, - runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>, - api_key_headers: HeaderMap, - ) -> Self { - let base_url = base_url.into(); - let runtime_auth = runtime_auth.filter(|_| match &base_url { - ChatgptBaseUrl::Default => true, - ChatgptBaseUrl::Configured(url) => { - codex_http_client::classify_openai_api_url(url) - != codex_http_client::OpenAiDestination::Other - } - }); - // aKode: analytics are never uploaded. The upstream client posted - // events to `{chatgpt_base_url}/codex/analytics-events/events`; the - // queue is never created, so every `track_*` call is a no-op. - let _ = ( - analytics_enabled, - auth_manager, - runtime_auth, - AnalyticsEventsDestination::from_base_url(base_url, api_key_headers), - ); - Self { queue: None } - } - - /// Give a resumed actor its own queue while preserving the caller's analytics setting. - pub fn for_auth_context( - &self, - auth_manager: Arc, - base_url: String, - runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>, - api_key_headers: HeaderMap, - ) -> Self { - Self::new_with_runtime( - auth_manager, - base_url, - Some(self.queue.is_some()), - runtime_auth, - api_key_headers, - ) - } - - pub fn disabled() -> Self { - Self { queue: None } - } - - pub async fn flush(&self) { - let Some(queue) = self.queue.as_ref() else { - return; - }; - let (done_tx, done_rx) = oneshot::channel(); - let flushed = tokio::time::timeout(ANALYTICS_EVENTS_FLUSH_TIMEOUT, async { - if queue - .sender - .send(AnalyticsEventsQueueMessage::Flush(done_tx)) - .await - .is_err() - { - return false; - } - done_rx.await.is_ok() - }) - .await; - - if !matches!(flushed, Ok(true)) { - tracing::warn!("timed out or failed while flushing analytics events"); - } - } - - pub fn is_enabled(&self) -> bool { - self.queue.is_some() - } - - pub fn track_plugin_measurements(&self, mut input: PluginMeasurementsInput) { - if input.rows.is_empty() - || input.rows.len() > MAX_PLUGIN_MEASUREMENTS_PER_BATCH - || !valid_plugin_measurement_identifier(&input.operation) - { - return; - } - input.rows.retain(valid_plugin_measurement_row); - if input.rows.is_empty() { - return; - } - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginMeasurements(input), - )); - } - - pub fn track_skill_invocations( - &self, - tracking: TrackEventsContext, - invocations: Vec, - ) { - if invocations.is_empty() { - return; - } - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::SkillInvoked( - SkillInvokedInput { - tracking, - invocations, - }, - ))); - } - - pub fn track_artifact_operation( - &self, - tracking: TrackEventsContext, - operation: ArtifactOperation, - ) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::ArtifactOperation(ArtifactOperationInput { - tracking, - operation, - }), - )); - } - - pub fn track_initialize( - &self, - connection_id: u64, - params: InitializeParams, - product_client_id: String, - rpc_transport: AppServerRpcTransport, - ) { - self.record_fact(AnalyticsFact::Initialize { - connection_id, - params, - product_client_id, - runtime: current_runtime_metadata(), - rpc_transport, - }); - } - - pub fn track_subagent_thread_started(&self, input: SubAgentThreadStartedInput) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::SubAgentThreadStarted(input), - )); - } - - /// Logs Guardian turn and tool events that bypass the app-server listener. - pub fn track_guardian_session_event(&self, thread_id: ThreadId, event: &Event) { - if let Some(notification) = session_event_to_analytics_notification(thread_id, event) { - self.track_notification(¬ification); - } - } - - pub fn track_collab_tool_call( - &self, - turn_id: String, - mut item: CollabAgentToolCallItem, - started_at_ms: i64, - completed_at_ms: i64, - ) { - let thread_id = item.sender_thread_id.to_string(); - let completed_item = codex_app_server_protocol::ThreadItemPayload::from( - TurnItem::CollabAgentToolCall(item.clone()), - ); - item.status = CollabAgentToolCallStatus::InProgress; - - self.track_notification(&ServerNotification::ItemStarted( - ItemStartedNotification::new( - thread_id.clone(), - turn_id.clone(), - codex_app_server_protocol::ThreadItemPayload::from(TurnItem::CollabAgentToolCall( - item, - )), - started_at_ms, - ), - )); - self.track_notification(&ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - thread_id, - turn_id, - completed_item, - Some(started_at_ms), - completed_at_ms, - ), - )); - } - - pub fn track_code_mode_tool_call(&self, input: crate::facts::CodeModeToolCallFact) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::CodeModeToolCall(input), - )); - } - - pub fn track_control_tool_call(&self, input: crate::facts::ControlToolCallFact) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall( - input, - ))); - } - - pub fn track_guardian_review( - &self, - tracking: &GuardianReviewTrackContext, - result: GuardianReviewAnalyticsResult, - completed_at_ms: u64, - elapsed: Duration, - ) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::GuardianReview( - Box::new(tracking.event_params(result, completed_at_ms, elapsed)), - ))); - } - - pub fn track_app_mentioned(&self, tracking: TrackEventsContext, mentions: Vec) { - if mentions.is_empty() { - return; - } - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::AppMentioned( - AppMentionedInput { tracking, mentions }, - ))); - } - - pub fn track_request( - &self, - connection_id: u64, - request_id: RequestId, - request: &ClientRequest, - ) { - if let ClientRequest::TurnInterrupt { params, .. } = request { - if params.turn_id.is_empty() { - return; - } - self.record_fact(AnalyticsFact::ExplicitClientInterruptRequest { - connection_id, - request_id, - turn_id: params.turn_id.clone(), - requested_at_ms: now_unix_millis(), - }); - return; - } - if !matches!( - request, - ClientRequest::TurnStart { .. } | ClientRequest::TurnSteer { .. } - ) { - return; - } - self.record_fact(AnalyticsFact::ClientRequest { - connection_id, - request_id, - request: Box::new(request.clone()), - }); - } - - pub fn track_app_used( - &self, - tracking: TrackEventsContext, - app: AppInvocation, - elicitation_type: Option, - ) { - let Some(queue) = self.queue.as_ref() else { - return; - }; - if !queue.should_enqueue_app_used(&tracking, &app) { - return; - } - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed( - AppUsedInput { - tracking, - app, - elicitation_type, - }, - ))); - } - - pub fn track_mcp_tool_call_elicitation(&self, input: McpToolCallElicitation) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::McpToolCallElicitation(input), - )); - } - - pub fn track_hook_run(&self, tracking: TrackEventsContext, hook: HookRunFact) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::HookRun( - HookRunInput { tracking, hook }, - ))); - } - - pub fn track_plugin_used(&self, tracking: TrackEventsContext, plugin: PluginTelemetryMetadata) { - let Some(queue) = self.queue.as_ref() else { - return; - }; - if !queue.should_enqueue_plugin_used(&tracking, &plugin) { - return; - } - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::PluginUsed( - crate::facts::PluginUsedInput { tracking, plugin }, - ))); - } - - pub fn track_plugin_install_requested( - &self, - tracking: TrackEventsContext, - request: PluginInstallRequested, - ) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginInstallRequested(PluginInstallRequestedInput { - tracking, - request, - }), - )); - } - - pub fn track_compaction(&self, event: crate::facts::CodexCompactionEvent) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::Compaction( - Box::new(event), - ))); - } - - pub fn track_realtime_session_updated(&self, thread_id: String, realtime_session_id: String) { - self.record_fact(AnalyticsFact::RealtimeSessionUpdated { - thread_id, - realtime_session_id, - }); - } - - pub fn track_guardian_v2_event(&self, event: GuardianV2Event) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::GuardianV2( - Box::new(event), - ))); - } - - pub fn track_goal_event(&self, event: CodexGoalEvent) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::Goal(Box::new( - event, - )))); - } - - pub fn track_thread_hint_status(&self, event: crate::thread_hint::ThreadHintStatusEvent) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::ThreadHintStatus(Box::new(event)), - )); - } - - pub fn track_image_preparation(&self, fact: ImagePreparationFact) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::ImagePreparation(Box::new(fact)), - )); - } - - pub fn track_turn_resolved_config(&self, fact: TurnResolvedConfigFact) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::TurnResolvedConfig(Box::new(fact)), - )); - } - - pub fn track_turn_token_usage(&self, fact: TurnTokenUsageFact) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::TurnTokenUsage( - Box::new(fact), - ))); - } - - pub fn track_turn_profile(&self, fact: TurnProfileFact) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile( - Box::new(fact), - ))); - } - - pub fn track_turn_codex_error(&self, fact: TurnCodexErrorFact) { - self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::TurnCodexError( - Box::new(fact), - ))); - } - - pub fn track_plugin_installed(&self, plugin: PluginTelemetryMetadata) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, - state: PluginState::Installed, - }), - )); - } - - pub fn track_plugin_install_failed( - &self, - plugin: PluginTelemetryMetadata, - source: PluginInstallSource, - error_type: String, - sub_error_type: Option, - ) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginInstallFailed(PluginInstallFailedInput { - plugin, - source, - error_type, - sub_error_type, - }), - )); - } - - pub fn track_external_agent_config_import_completed( - &self, - input: ExternalAgentConfigImportCompletedInput, - ) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input), - )); - } - - pub fn track_external_agent_config_import_failure( - &self, - input: ExternalAgentConfigImportFailureInput, - ) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::ExternalAgentConfigImportFailure(input), - )); - } - - pub fn track_plugin_uninstalled(&self, plugin: PluginTelemetryMetadata) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, - state: PluginState::Uninstalled, - }), - )); - } - - pub fn track_plugin_enabled(&self, plugin: PluginTelemetryMetadata) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, - state: PluginState::Enabled, - }), - )); - } - - pub fn track_plugin_disabled(&self, plugin: PluginTelemetryMetadata) { - self.record_fact(AnalyticsFact::Custom( - CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, - state: PluginState::Disabled, - }), - )); - } - - pub(crate) fn record_fact(&self, input: AnalyticsFact) { - if let Some(queue) = self.queue.as_ref() { - queue.try_send(input); - } - } - - pub fn track_response( - &self, - connection_id: u64, - request_id: RequestId, - response: &ClientResponsePayload, - ) { - self.track_response_inner( - connection_id, - request_id, - response, - /*thread_originator*/ None, - ); - } - - pub fn track_response_with_thread_originator( - &self, - connection_id: u64, - request_id: RequestId, - response: &ClientResponsePayload, - thread_originator: String, - ) { - self.track_response_inner(connection_id, request_id, response, Some(thread_originator)); - } - - fn track_response_inner( - &self, - connection_id: u64, - request_id: RequestId, - response: &ClientResponsePayload, - thread_originator: Option, - ) { - if !matches!( - response, - ClientResponsePayload::ThreadStart(_) - | ClientResponsePayload::ThreadResume(_) - | ClientResponsePayload::ThreadFork(_) - | ClientResponsePayload::TurnStart(_) - | ClientResponsePayload::TurnSteer(_) - | ClientResponsePayload::TurnInterrupt(_) - ) { - return; - } - if serde_json::to_writer(std::io::sink(), response).is_err() { - return; - } - self.record_fact(AnalyticsFact::ClientResponse { - connection_id, - request_id, - response: Box::new(response.clone()), - thread_originator, - }); - } - - pub fn track_error_response( - &self, - connection_id: u64, - request_id: RequestId, - error: JSONRPCErrorError, - error_type: Option, - ) { - self.record_fact(AnalyticsFact::ErrorResponse { - connection_id, - request_id, - error, - error_type, - }); - } - - pub fn track_server_request(&self, connection_id: u64, request: ServerRequest) { - self.record_fact(AnalyticsFact::ServerRequest { - connection_id, - request: Box::new(request), - }); - } - - pub fn track_server_response(&self, completed_at_ms: u64, response: ServerResponse) { - self.record_fact(AnalyticsFact::ServerResponse { - completed_at_ms, - response: Box::new(response), - }); - } - - pub fn track_effective_permissions_approval_response( - &self, - completed_at_ms: u64, - request_id: RequestId, - response: RequestPermissionsResponse, - ) { - self.record_fact(AnalyticsFact::EffectivePermissionsApprovalResponse { - completed_at_ms, - request_id, - response: Box::new(response), - }); - } - - pub fn track_server_request_aborted(&self, completed_at_ms: u64, request_id: RequestId) { - self.record_fact(AnalyticsFact::ServerRequestAborted { - completed_at_ms, - request_id, - }); - } - - /// Records analytics-relevant notifications without cloning ignored variants. - pub fn track_notification(&self, notification: &ServerNotification) { - match notification { - ServerNotification::ThreadRealtimeStarted(started) => { - self.record_fact(AnalyticsFact::RealtimeSessionStarted { - thread_id: started.thread_id.clone(), - realtime_session_id: started.realtime_session_id.clone(), - started_at: crate::now_unix_seconds(), - }); - return; - } - ServerNotification::ThreadRealtimeClosed(closed) => { - self.record_fact(AnalyticsFact::RealtimeSessionClosed { - thread_id: closed.thread_id.clone(), - closed_at: crate::now_unix_seconds(), - }); - return; - } - _ => {} - } - if let ServerNotification::ThreadRealtimeItemAdded(handoff) = notification { - if handoff.item.get("type").and_then(serde_json::Value::as_str) - == Some("handoff_request") - { - self.record_fact(AnalyticsFact::RealtimeHandoffRequested { - thread_id: handoff.thread_id.clone(), - }); - } - return; - } - if !matches!( - notification, - ServerNotification::ThreadArchived(_) - | ServerNotification::ThreadClosed(_) - | ServerNotification::ThreadUnarchived(_) - | ServerNotification::TurnStarted(_) - | ServerNotification::TurnCompleted(_) - | ServerNotification::TurnDiffUpdated(_) - | ServerNotification::ItemStarted(_) - | ServerNotification::ItemCompleted(_) - | ServerNotification::ItemGuardianApprovalReviewStarted(_) - | ServerNotification::ItemGuardianApprovalReviewCompleted(_) - ) { - return; - } - self.record_fact(AnalyticsFact::Notification(Box::new(notification.clone()))); - } -} - -fn session_event_to_analytics_notification( - thread_id: ThreadId, - event: &Event, -) -> Option { - let notification = match &event.msg { - EventMsg::ItemStarted(started) => item_event_to_server_notification( - event.msg.clone(), - &started.thread_id.to_string(), - &started.turn_id, - ), - EventMsg::ItemCompleted(completed) => item_event_to_server_notification( - event.msg.clone(), - &completed.thread_id.to_string(), - &completed.turn_id, - ), - EventMsg::TurnStarted(started) => { - ServerNotification::TurnStarted(TurnStartedNotification { - thread_id: thread_id.to_string(), - turn: Turn { - started_at: started.started_at, - root_turn_id: started.root_turn_id.clone(), - ..analytics_turn(&started.turn_id, TurnStatus::InProgress) - }, - }) - } - EventMsg::TurnComplete(completed) => { - let error = completed.error.as_ref().map(|error| TurnError { - message: String::new(), - codex_error_info: error.codex_error_info.clone().map(Into::into), - additional_details: None, - misalignment: None, - }); - let status = if error.is_some() { - TurnStatus::Failed - } else { - TurnStatus::Completed - }; - ServerNotification::TurnCompleted(TurnCompletedNotification { - thread_id: thread_id.to_string(), - turn: Turn { - error, - started_at: completed.started_at, - completed_at: completed.completed_at, - duration_ms: completed.duration_ms, - ..analytics_turn(&completed.turn_id, status) - }, - }) - } - EventMsg::TurnAborted(aborted) => { - ServerNotification::TurnCompleted(TurnCompletedNotification { - thread_id: thread_id.to_string(), - turn: Turn { - started_at: aborted.started_at, - completed_at: aborted.completed_at, - duration_ms: aborted.duration_ms, - ..analytics_turn( - aborted.turn_id.as_deref().unwrap_or(&event.id), - TurnStatus::Interrupted, - ) - }, - }) - } - // Legacy tool events accompany canonical items. Messages, reasoning, and review - // content must not enter the analytics queue. - _ => return None, - }; - match ¬ification { - ServerNotification::ItemStarted(ItemStartedNotification { item, .. }) - | ServerNotification::ItemCompleted(ItemCompletedNotification { item, .. }) => { - tracked_tool_item_id(&item.payload)?; - } - _ => {} - } - Some(notification) -} - -fn analytics_turn(turn_id: &str, status: TurnStatus) -> Turn { - Turn { - id: turn_id.to_string(), - root_turn_id: None, - items: Vec::new(), - items_view: TurnItemsView::NotLoaded, - status, - error: None, - started_at: None, - completed_at: None, - duration_ms: None, - } -} - -async fn send_track_events( - auth_manager: &AuthManager, - destination: &AnalyticsEventsDestination, - mut events: Vec, - thread_products: &ThreadProducts, - runtime_auth: Option<&(RuntimeAuthSlot, RuntimeAuthMode)>, -) { - if events.is_empty() { - return; - } - - let Some((auth, http_client_factory)) = auth_manager.auth_with_http_client_factory().await - else { - return; - }; - if auth.is_api_key_auth() { - events.retain(TrackEventRequest::can_send_with_api_key_auth); - } else if !auth.uses_codex_backend() { - return; - } - if events.is_empty() { - return; - } - - // Product streams are capped by product_event_batches. Parallel streams add no - // timeout waves to the existing sequential isolated-event request splitting. - let mut requests = tokio::task::JoinSet::new(); - for (product_sku, events) in product_event_batches(events, thread_products) { - let (auth, destination, factory) = ( - auth.clone(), - destination.clone(), - http_client_factory.clone(), - ); - let product_sku = product_sku.map(str::to_string); - let runtime_auth = runtime_auth.cloned(); - requests.spawn(async move { - for events in track_event_request_batches(events) { - send_track_events_request( - &auth, - &destination, - events, - &factory, - product_sku.as_deref(), - runtime_auth.as_ref(), - ) - .await; - } - }); - } - while let Some(result) = requests.join_next().await { - if let Err(error) = result { - tracing::warn!(%error, "analytics product stream failed"); - } - } -} - -fn track_event_request_batches(events: Vec) -> Vec> { - let mut batches = Vec::new(); - let mut current_batch = Vec::new(); - - for event in events { - if event.should_send_in_isolated_request() { - if !current_batch.is_empty() { - batches.push(current_batch); - current_batch = Vec::new(); - } - batches.push(vec![event]); - } else { - current_batch.push(event); - } - } - - if !current_batch.is_empty() { - batches.push(current_batch); - } - - batches -} - -async fn send_track_events_request( - auth: &CodexAuth, - destination: &AnalyticsEventsDestination, - events: Vec, - http_client_factory: &codex_http_client::HttpClientFactory, - product_sku: Option<&str>, - runtime_auth: Option<&(RuntimeAuthSlot, RuntimeAuthMode)>, -) { - if events.is_empty() { - return; - } - - let payload = TrackEventsRequest { events }; - - #[cfg(debug_assertions)] - if capture_track_events_request(destination, &payload) { - return; - } - - let Some(url) = destination.url_for_auth(auth) else { - return; - }; - if runtime_auth.is_some() - && let Err(error) = codex_model_provider::validate_runtime_destination(Some(&url)) - { - tracing::warn!("failed to authenticate events request: {error}"); - return; - } - let runtime = match runtime_auth { - Some((slot, mode)) => { - let Some(manager) = slot.get() else { - tracing::warn!("runtime authentication has not been initialized for events"); - return; - }; - Some((Arc::clone(manager), *mode)) - } - None => None, - }; - let headers = match destination { - AnalyticsEventsDestination::Http { - api_key_headers, .. - } if auth.is_api_key_auth() => api_key_headers.clone(), - _ => HeaderMap::new(), - }; - let resolved = async { - let resolved = - codex_model_provider::auth_provider_for_request(auth, runtime.as_ref(), &headers) - .await?; - let factory = resolved.bind_http_client_factory(http_client_factory.clone())?; - resolved - .auth - .apply_auth_headers(headers) - .await - .map(|headers| (headers, factory)) - } - .await; - let (headers, factory) = match resolved { - Ok(resolved) => resolved, - Err(error) => { - tracing::warn!("failed to authenticate events request: {error}"); - return; - } - }; - let client = codex_login::default_client::create_client_for_route_async( - factory, - url.clone(), - codex_http_client::ClientRouteClass::Api, - codex_login::default_client::ClientRedirectPolicy::Default, - ) - .await; - let client = match client { - Ok(client) => client, - Err(error) => { - tracing::warn!(%error, "failed to build events client"); - return; - } - }; - let mut request = client - .post(&url) - .timeout(ANALYTICS_EVENTS_TIMEOUT) - .headers(headers) - .header("Content-Type", "application/json") - .json(&payload); - if let Some(product_sku) = product_sku { - request = request.header("X-OpenAI-Product-Sku", product_sku); - } - let response = request.send().await; - - match response { - Ok(response) if response.status().is_success() => {} - Ok(response) => { - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - tracing::warn!("events failed with status {status}: {body}"); - } - Err(err) => { - tracing::warn!("failed to send events request: {err}"); - } - } -} - -#[cfg(debug_assertions)] -fn capture_track_events_request( - destination: &AnalyticsEventsDestination, - payload: &TrackEventsRequest, -) -> bool { - let AnalyticsEventsDestination::CaptureFile { path } = destination else { - return false; - }; - - use std::sync::PoisonError; - static CAPTURE_LOCK: Mutex<()> = Mutex::new(()); - let _capture_guard = CAPTURE_LOCK.lock().unwrap_or_else(PoisonError::into_inner); - if let Err(err) = crate::analytics_capture::append_payload(path, payload) { - tracing::error!( - path = %path.display(), - "failed to capture analytics events; network delivery remains disabled: {err}" - ); - } - true -} - -#[cfg(test)] -#[path = "client_tests.rs"] -mod tests; - -#[cfg(test)] -#[path = "client_runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/analytics/src/client_product_tests.rs b/codex-rs/analytics/src/client_product_tests.rs deleted file mode 100644 index 97b3ac6a..00000000 --- a/codex-rs/analytics/src/client_product_tests.rs +++ /dev/null @@ -1,359 +0,0 @@ -//! Verify product attribution remains per thread across shared queues and HTTP batches. -//! Reconfiguration preserves buffered attribution; queue overflow falls back to unknown. - -use super::AnalyticsEventsClient; -use super::AnalyticsEventsDestination; -use super::AnalyticsEventsQueue; -use super::sample_regular_track_event; -use super::sample_thread_start_response; -use super::sample_turn_start_response; -use super::send_track_events; -use crate::ThreadProductUpdate; -use crate::events::AppServerRpcTransport; -use crate::facts::PluginMeasurementRow; -use crate::facts::PluginMeasurementsInput; -use crate::product_attribution::ThreadProducts; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CollabAgentTool; -use codex_app_server_protocol::CollabAgentToolCallStatus; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::TurnStartedNotification; -use codex_login::AuthManager; -use codex_protocol::ThreadId; -use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; - -enum Responses { - Immediate, - PauseAfter(usize), - Together, -} - -type CapturedRequest = (Option, serde_json::Value); - -#[test] -fn product_registry_clears_unset_threads_and_bounds_retention() { - let mut products = ThreadProducts::default(); - products.register("unset".to_string(), Some("aeon".to_string())); - products.register("unset".to_string(), /*product*/ None); - for index in 0..=4096 { - products.register(format!("thread-{index}"), Some("tpp".to_string())); - } - let batches = crate::product_attribution::product_event_batches( - vec![ - sample_regular_track_event("unset"), - sample_regular_track_event("thread-0"), - sample_regular_track_event("thread-4096"), - ], - &products, - ); - assert_eq!( - batches - .into_iter() - .map(|(product, events)| (product, events.len())) - .collect::>(), - vec![(None, 2), (Some("tpp"), 1)] - ); - for index in 0..17 { - products.register(format!("thread-{index}"), Some(format!("product-{index}"))); - } - let events = (0..17) - .map(|index| sample_regular_track_event(&format!("thread-{index}"))) - .collect::>(); - let expected = serde_json::json!([[null, &events]]); - assert_eq!( - serde_json::to_value(crate::product_attribution::product_event_batches( - events, &products - )) - .unwrap(), - expected - ); -} - -async fn capture_requests( - count: usize, - responses: Responses, -) -> ( - AnalyticsEventsDestination, - tokio::task::JoinHandle>, - tokio::sync::oneshot::Receiver<()>, - tokio::sync::oneshot::Sender<()>, -) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let destination = AnalyticsEventsDestination::Http { - base_url: format!("http://{}", listener.local_addr().unwrap()).into(), - api_key_headers: Default::default(), - }; - let (paused_tx, paused_rx) = tokio::sync::oneshot::channel(); - let (resume_tx, resume_rx) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - let mut pause = Some((paused_tx, resume_rx)); - let mut requests = Vec::new(); - let mut pending = Vec::new(); - for _ in 0..count { - let (mut stream, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let (headers, body) = loop { - let mut buffer = [0; 4096]; - let count = stream.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") { - let headers = String::from_utf8_lossy(&request[..end]).to_lowercase(); - let length: usize = headers - .lines() - .find_map(|line| line.strip_prefix("content-length: ")) - .unwrap() - .parse() - .unwrap(); - if request.len() >= end + 4 + length { - break ( - headers, - serde_json::from_slice(&request[end + 4..end + 4 + length]).unwrap(), - ); - } - } - }; - let product = headers - .lines() - .find_map(|line| line.strip_prefix("x-openai-product-sku: ")) - .map(str::to_string); - requests.push((product, body)); - if matches!(responses, Responses::PauseAfter(count) if count == requests.len()) { - let (paused, resume) = pause.take().unwrap(); - paused.send(()).unwrap(); - resume.await.unwrap(); - } - pending.push(stream); - if matches!(responses, Responses::Together) && requests.len() < count { - continue; - } - for mut stream in pending.drain(..) { - stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") - .await - .unwrap(); - } - } - requests - }); - (destination, server, paused_rx, resume_tx) -} - -#[tokio::test] -async fn product_streams_send_concurrently_and_preserve_event_order() { - // Withhold every response until all 16 requests arrive: serial delivery would time out. - let (destination, server, _, _) = capture_requests(/*count*/ 16, Responses::Together).await; - let manager = AuthManager::from_auth_for_testing( - codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ); - let mut products = ThreadProducts::default(); - for index in 0..16 { - products.register(format!("thread-{index}"), Some(format!("product-{index}"))); - } - let event = |index| { - let mut event = sample_regular_track_event(&format!("thread-{}", index % 16)); - if let crate::events::TrackEventRequest::SkillInvocation(skill) = &mut event { - skill.event_params.turn_id = Some(format!("turn-{index}")); - } - event - }; - let events = (0..32).map(event).collect(); - tokio::time::timeout( - std::time::Duration::from_secs(15), - send_track_events( - &manager, - &destination, - events, - &products, - /*runtime_auth*/ None, - ), - ) - .await - .unwrap(); - let mut requests = server.await.unwrap(); - requests.sort_by(|a, b| a.0.cmp(&b.0)); - let mut expected = (0..16) - .map(|index| { - ( - Some(format!("product-{index}")), - serde_json::json!({"events": [event(index), event(index + 16)]}), - ) - }) - .collect::>(); - expected.sort_by(|a, b| a.0.cmp(&b.0)); - assert_eq!(requests, expected); -} - -#[tokio::test] -async fn buffered_tool_events_preserve_attribution_or_drop_it_on_queue_overflow() { - for (new_product, overflow) in [ - (Some("tpp"), false), - (None, false), - (Some("tpp"), true), - (None, true), - ] { - let (destination, server, paused, resume) = capture_requests( - if overflow { 5 } else { 2 }, - if overflow { - Responses::PauseAfter(2) - } else { - Responses::Immediate - }, - ) - .await; - let manager = AuthManager::from_auth_for_testing( - codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ); - let client = AnalyticsEventsClient { - queue: Some(AnalyticsEventsQueue::new( - manager, - destination, - /*runtime_auth*/ None, - )), - }; - let thread_id = ThreadId::new(); - client.update_thread_product_sku(thread_id, ThreadProductUpdate::Set("aeon".to_string())); - client.track_initialize( - /*connection_id*/ 1, - InitializeParams { - client_info: ClientInfo { - name: "test".to_string(), - title: None, - version: "1".to_string(), - }, - capabilities: None, - }, - "test_client".to_string(), - AppServerRpcTransport::InProcess, - ); - let mut response = sample_thread_start_response(); - let ClientResponsePayload::ThreadStart(started) = &mut response else { - unreachable!() - }; - started.thread.id = thread_id.to_string(); - client.track_response(/*connection_id*/ 1, RequestId::Integer(1), &response); - let ClientResponsePayload::TurnStart(started) = sample_turn_start_response() else { - unreachable!() - }; - client.track_notification(&ServerNotification::TurnStarted(TurnStartedNotification { - thread_id: thread_id.to_string(), - turn: started.turn, - })); - // Collaborator completions wait in the reducer for subsequent sampling evidence. - let completed = ItemCompletedNotification::new( - thread_id.to_string(), - "turn-1".to_string(), - ThreadItemPayload::CollabAgentToolCall { - id: "item".to_string(), - tool: CollabAgentTool::SendMessage, - status: CollabAgentToolCallStatus::Failed, - sender_thread_id: thread_id.to_string(), - receiver_thread_ids: Vec::new(), - prompt: None, - model: None, - reasoning_effort: None, - agents_states: Default::default(), - }, - /*started_at_ms*/ None, - /*completed_at_ms*/ 2, - ); - client.track_notification(&ServerNotification::ItemStarted( - ItemStartedNotification::new( - thread_id.to_string(), - "turn-1".to_string(), - completed.item.payload.clone(), - /*started_at_ms*/ 1, - ), - )); - client.track_notification(&ServerNotification::ItemCompleted(completed)); - let measurement = PluginMeasurementsInput { - thread_id: thread_id.to_string(), - turn_id: "turn-1".to_string(), - item_id: "measurement".to_string(), - originator: "test_client".to_string(), - model_slug: None, - reasoning_effort: None, - plugin_id: "sites@test".to_string(), - execution_id: "execution".to_string(), - operation: "build".to_string(), - rows: vec![PluginMeasurementRow { - measurement_name: "duration_ms".to_string(), - number_value: 12.0, - dimensions: BTreeMap::new(), - }], - }; - if overflow { - client.track_plugin_measurements(measurement.clone()); - paused.await.unwrap(); - // Hold HTTP delivery while stale registrations fill the shared queue. - let capacity = client.queue.as_ref().unwrap().sender.capacity(); - for _ in 0..capacity { - client.update_thread_product_sku( - thread_id, - ThreadProductUpdate::Set("aeon".to_string()), - ); - } - } - client.update_thread_product_sku( - thread_id, - new_product.map_or(ThreadProductUpdate::Clear, |value| { - ThreadProductUpdate::Set(value.to_string()) - }), - ); - if overflow { - resume.send(()).unwrap(); - } - client.flush().await; - if overflow { - client.track_plugin_measurements(measurement.clone()); - client.flush().await; - client - .update_thread_product_sku(thread_id, ThreadProductUpdate::Set("tpp".to_string())); - client.track_plugin_measurements(measurement); - client.flush().await; - } - let requests = tokio::time::timeout(std::time::Duration::from_secs(5), server) - .await - .unwrap() - .unwrap(); - let expected = if overflow { - vec![ - (Some("aeon"), "codex_thread_initialized"), - (Some("aeon"), "codex_plugin_measurement_event"), - (None, "codex_collab_agent_tool_call_event"), - (None, "codex_plugin_measurement_event"), - (Some("tpp"), "codex_plugin_measurement_event"), - ] - } else { - vec![ - (Some("aeon"), "codex_thread_initialized"), - (Some("aeon"), "codex_collab_agent_tool_call_event"), - ] - } - .into_iter() - .map(|(product, event)| (product.map(str::to_string), event.to_string())) - .collect::>(); - assert_eq!( - requests - .into_iter() - .map(|(product, body)| ( - product, - body["events"][0]["event_type"] - .as_str() - .unwrap() - .to_string(), - )) - .collect::>(), - expected - ); - } -} diff --git a/codex-rs/analytics/src/client_runtime_auth_tests.rs b/codex-rs/analytics/src/client_runtime_auth_tests.rs deleted file mode 100644 index 86857adc..00000000 --- a/codex-rs/analytics/src/client_runtime_auth_tests.rs +++ /dev/null @@ -1,298 +0,0 @@ -//! Runtime signing and destination isolation at the analytics delivery boundary. - -use super::*; -use crate::facts::PluginMeasurementRow; -use crate::facts::PluginMeasurementsInput; -use codex_features::RuntimeAuthMode; -use codex_runtime_agent_instance::AgentHostAuthorization; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::RuntimeAuthSlot; -use codex_runtime_agent_instance::RuntimeRegistrationMetadata; -use codex_runtime_agent_instance::RuntimeRole; -use pretty_assertions::assert_eq; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::path; - -async fn emit(client: &AnalyticsEventsClient, execution_id: &str) { - client.track_plugin_measurements(PluginMeasurementsInput { - thread_id: "thread-a".into(), - turn_id: "turn-a".into(), - item_id: "item-a".into(), - originator: "codex_cli_rs".into(), - model_slug: None, - reasoning_effort: None, - plugin_id: "plugin-a".into(), - execution_id: execution_id.into(), - operation: "security_scan".into(), - rows: vec![PluginMeasurementRow { - measurement_name: "findings".into(), - number_value: 1.0, - dimensions: Default::default(), - }], - }); - client.flush().await; -} - -#[tokio::test] -async fn runtime_delivery_signs_each_batch_and_strips_cross_origin_auth() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - let redirected = MockServer::start().await; - Mock::given(path("/")) - .respond_with(ResponseTemplate::new(200)) - .expect(2) - .mount(&redirected) - .await; - Mock::given(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "runtime_agent_instance_id": "runtime-analytics", "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null}, - }))) - .expect(1).mount(&server).await; - Mock::given(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri())) - .expect(2) - .mount(&server) - .await; - let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a")); - let runtime = ( - Arc::new(RuntimeAuthManager::new( - Arc::clone(&credentials), - AgentHostAuthorization::InstallationId { - installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - )), - mode, - ); - // Inject the selected context at the delivery boundary for the loopback fixture. - let client = AnalyticsEventsClient { - queue: Some(AnalyticsEventsQueue::new( - credentials, - AnalyticsEventsDestination::Http { - base_url: server.uri().into(), - api_key_headers: Default::default(), - }, - Some((Arc::new(std::sync::OnceLock::from(runtime.0)), runtime.1)), - )), - }; - emit(&client, "first").await; - emit(&client, "second").await; - let forwarded = redirected.received_requests().await.unwrap(); - assert_eq!(forwarded.len(), 2); - for request in &forwarded { - assert!(!request.headers.contains_key("authorization")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - redirected.verify().await; - let requests = server.received_requests().await.unwrap(); - let proofs: Vec<_> = requests - .iter() - .filter(|r| r.url.path() == "/codex/analytics-events/events") - .map(|request| { - let authorization = request.headers["authorization"].to_str().unwrap(); - match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, "Bearer key-a"); - request.headers["x-openai-agent-assertion"] - .to_str() - .unwrap() - .to_string() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .unwrap() - .to_string() - } - } - }) - .collect(); - assert_eq!(proofs.len(), 2); - assert_ne!(proofs[0], proofs[1]); - server.verify().await; - } -} - -// aKode: the analytics client never creates a delivery queue, so nothing is sent. -#[tokio::test] -async fn analytics_client_never_sends_events() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - Mock::given(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .expect(0) - .mount(&server) - .await; - let client = AnalyticsEventsClient::new_with_runtime( - AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a")), - server.uri(), - Some(true), - Some((RuntimeAuthSlot::default(), mode)), - /*api_key_headers*/ Default::default(), - ); - emit(&client, "custom").await; - assert!(server.received_requests().await.unwrap().is_empty()); - server.verify().await; - } -} - -#[tokio::test] -async fn analytics_between_model_calls_keeps_the_selected_api_resources() { - use codex_http_client::ClientRouteClass; - use codex_login::default_client::ClientRedirectPolicy; - use codex_model_provider_info::ModelProviderInfo; - use std::collections::HashMap; - - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - Mock::given(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "runtime_agent_instance_id": "runtime-selected", "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-selected", "project_id": null}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/v1/responses")) - .respond_with( - ResponseTemplate::new(200).set_body_json(serde_json::json!({"output": []})), - ) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a")); - let owner = Arc::new(RuntimeAuthManager::new( - Arc::clone(&credentials), - AgentHostAuthorization::InstallationId { - installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - )); - let mut info = - ModelProviderInfo::create_openai_provider(Some(format!("{}/v1", server.uri()))); - info.env_http_headers = None; - info.http_headers = Some(HashMap::from([ - ("OpenAI-Organization".into(), "org-selected".into()), - ("OpenAI-Project".into(), "proj-selected".into()), - ("X-Model-Secret".into(), "model-only".into()), - ])); - let destination = AnalyticsEventsDestination::from_base_url( - server.uri().into(), - info.build_header_map().unwrap(), - ); - let analytics = AnalyticsEventsClient { - queue: Some(AnalyticsEventsQueue::new( - Arc::clone(&credentials), - destination, - Some(( - Arc::new(std::sync::OnceLock::from(Arc::clone(&owner))), - mode, - )), - )), - }; - let provider = codex_model_provider::test_support::runtime_model_provider( - info, - Arc::clone(&credentials), - (owner, mode), - ); - for attempt in 0..2 { - let request = codex_model_provider::resolve_request( - provider.as_ref(), - /*scope*/ None, - /*routing*/ None, - credentials.http_client_factory(), - ) - .await - .unwrap(); - let url = request.api_provider.url_for_path("responses"); - let headers = request - .api_auth - .apply_auth_headers(request.api_provider.headers) - .await - .unwrap(); - let client = codex_login::default_client::create_client_for_route_async( - request.http_client_factory, - url.clone(), - ClientRouteClass::Api, - ClientRedirectPolicy::Default, - ) - .await - .unwrap(); - assert!( - client - .post(&url) - .headers(headers) - .json(&serde_json::json!({"input": "hello"})) - .send() - .await - .unwrap() - .status() - .is_success() - ); - if attempt == 0 { - emit(&analytics, "between-model-calls").await; - } - } - let requests = server.received_requests().await.unwrap(); - let registrations: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/agent/register") - .collect(); - assert_eq!( - registrations.len(), - 1, - "analytics must reuse the model registration" - ); - let registration: serde_json::Value = registrations[0].body_json().unwrap(); - assert_eq!( - registration["actor_auth"]["organization_id"], - "org-selected" - ); - assert_eq!(registration["actor_auth"]["project_id"], "proj-selected"); - for request in requests - .iter() - .filter(|request| request.url.path() != "/agent/register") - { - assert_eq!(request.headers["openai-organization"], "org-selected"); - assert_eq!(request.headers["openai-project"], "proj-selected"); - match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(request.headers["authorization"], "Bearer key-a"); - assert!(request.headers.contains_key("x-openai-agent-assertion")); - } - RuntimeAuthMode::AssertionOnly => { - assert!( - request.headers["authorization"] - .to_str() - .unwrap() - .starts_with("AgentAssertion ") - ); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - } - if request.url.path() == "/codex/analytics-events/events" { - assert!(!request.headers.contains_key("x-model-secret")); - } - } - server.verify().await; - } -} diff --git a/codex-rs/analytics/src/client_tests.rs b/codex-rs/analytics/src/client_tests.rs deleted file mode 100644 index 534886e0..00000000 --- a/codex-rs/analytics/src/client_tests.rs +++ /dev/null @@ -1,1285 +0,0 @@ -use super::AnalyticsEventsClient; -use super::AnalyticsEventsDestination; -use super::AnalyticsEventsQueue; -use super::AnalyticsEventsQueueMessage; -#[cfg(debug_assertions)] -use super::capture_track_events_request; -use super::send_track_events; -#[cfg(debug_assertions)] -use super::send_track_events_request; -use super::track_event_request_batches; -#[cfg(debug_assertions)] -use crate::events::AppServerRpcTransport; -use crate::events::CodexAcceptedLineFingerprintsEventParams; -use crate::events::CodexAcceptedLineFingerprintsEventRequest; -#[cfg(debug_assertions)] -use crate::events::CodexAppServerClientMetadata; -#[cfg(debug_assertions)] -use crate::events::CodexMcpToolCallEventParams; -#[cfg(debug_assertions)] -use crate::events::CodexMcpToolCallEventRequest; -#[cfg(debug_assertions)] -use crate::events::CodexPluginMeasurementEventParams; -#[cfg(debug_assertions)] -use crate::events::CodexPluginMeasurementEventRequest; -#[cfg(debug_assertions)] -use crate::events::CodexPluginMetadata; -#[cfg(debug_assertions)] -use crate::events::CodexPluginUsedEventRequest; -#[cfg(debug_assertions)] -use crate::events::CodexPluginUsedMetadata; -#[cfg(debug_assertions)] -use crate::events::CodexRuntimeMetadata; -#[cfg(debug_assertions)] -use crate::events::CodexToolItemEventBase; -#[cfg(debug_assertions)] -use crate::events::FinalApprovalOutcome; -use crate::events::SkillInvocationEventParams; -use crate::events::SkillInvocationEventRequest; -#[cfg(debug_assertions)] -use crate::events::ThreadArchiveAction; -#[cfg(debug_assertions)] -use crate::events::ThreadArchiveEvent; -#[cfg(debug_assertions)] -use crate::events::ThreadArchiveEventParams; -#[cfg(debug_assertions)] -use crate::events::ToolItemTerminalStatus; -use crate::events::TrackEventRequest; -#[cfg(debug_assertions)] -use crate::events::codex_artifact_operation_event_request; -use crate::facts::AnalyticsFact; -use crate::facts::AppInvocation; -#[cfg(debug_assertions)] -use crate::facts::ArtifactOperation; -#[cfg(debug_assertions)] -use crate::facts::ArtifactOperationLifecycle; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::InvocationType; -use crate::facts::PluginMeasurementRow; -use crate::facts::PluginMeasurementsInput; -use crate::facts::TrackEventsContext; -#[cfg(debug_assertions)] -use crate::product_attribution::ThreadProducts; -use crate::reducer::MAX_PLUGIN_MEASUREMENTS_PER_BATCH; -use codex_app_server_protocol::ApprovalsReviewer as AppServerApprovalsReviewer; -use codex_app_server_protocol::AskForApproval as AppServerAskForApproval; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CommandExecutionOutputDeltaNotification; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SandboxPolicy as AppServerSandboxPolicy; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionSource as AppServerSessionSource; -use codex_app_server_protocol::Thread; -use codex_app_server_protocol::ThreadArchiveParams; -use codex_app_server_protocol::ThreadArchiveResponse; -use codex_app_server_protocol::ThreadArchivedNotification; -use codex_app_server_protocol::ThreadForkResponse; -use codex_app_server_protocol::ThreadRealtimeClosedNotification; -use codex_app_server_protocol::ThreadRealtimeItemAddedNotification; -use codex_app_server_protocol::ThreadRealtimeStartedNotification; -use codex_app_server_protocol::ThreadResumeResponse; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::ThreadStatus as AppServerThreadStatus; -use codex_app_server_protocol::Turn; -use codex_app_server_protocol::TurnDiffUpdatedNotification; -use codex_app_server_protocol::TurnInterruptParams; -use codex_app_server_protocol::TurnInterruptResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_app_server_protocol::TurnSteerParams; -use codex_app_server_protocol::TurnSteerResponse; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -#[cfg(debug_assertions)] -use codex_login::AuthManager; -use codex_model_provider::ChatgptBaseUrl; -use codex_protocol::protocol::RealtimeConversationVersion; -use codex_utils_absolute_path::test_support::PathBufExt; -use codex_utils_absolute_path::test_support::test_path_buf; -use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use std::collections::HashSet; -#[cfg(debug_assertions)] -use std::fs; -#[cfg(debug_assertions)] -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::Mutex; -#[cfg(debug_assertions)] -use std::time::SystemTime; -use tokio::sync::mpsc; -use tokio::sync::mpsc::error::TryRecvError; - -#[path = "client_product_tests.rs"] -mod product_tests; - -#[cfg(debug_assertions)] -impl AnalyticsEventsClient { - pub(crate) fn new_for_capture_file(auth_manager: Arc, path: PathBuf) -> Self { - Self { - queue: Some(AnalyticsEventsQueue::new( - auth_manager, - AnalyticsEventsDestination::CaptureFile { path }, - /*runtime_auth*/ None, - )), - } - } -} - -fn sample_accepted_line_fingerprint_event(thread_id: &str) -> TrackEventRequest { - TrackEventRequest::AcceptedLineFingerprints(Box::new( - CodexAcceptedLineFingerprintsEventRequest { - event_type: "codex_accepted_line_fingerprints", - event_params: CodexAcceptedLineFingerprintsEventParams { - event_type: "codex.accepted_line_fingerprints", - turn_id: "turn-1".to_string(), - thread_id: thread_id.to_string(), - product_surface: Some("codex".to_string()), - model_slug: Some("gpt-5.1-codex".to_string()), - completed_at: 1, - repo_hash: None, - accepted_added_lines: 1, - accepted_deleted_lines: 0, - line_fingerprints: [], - }, - }, - )) -} - -fn sample_skill_track_event(thread_id: &str, plugin_id: Option<&str>) -> TrackEventRequest { - TrackEventRequest::SkillInvocation(SkillInvocationEventRequest { - event_type: "skill_invocation", - skill_id: format!("skill-{thread_id}"), - skill_name: "doc".to_string(), - event_params: SkillInvocationEventParams { - turn_trigger: None, - product_client_id: None, - skill_scope: None, - plugin_id: plugin_id.map(str::to_string), - remote_plugin_id: None, - thread_id: Some(thread_id.to_string()), - turn_id: Some("turn-1".to_string()), - voice_session_id: None, - invoke_type: Some(InvocationType::Explicit), - model_slug: Some("gpt-5.1-codex".to_string()), - }, - }) -} - -#[cfg(debug_assertions)] -fn sample_artifact_operation_event(thread_id: &str) -> TrackEventRequest { - TrackEventRequest::ArtifactOperation(codex_artifact_operation_event_request( - TrackEventsContext { - turn_metadata: None, - model_slug: "gpt-5.1-codex".to_string(), - thread_id: thread_id.to_string(), - turn_id: "turn-1".to_string(), - product_client_id: "codex_desktop".to_string(), - }, - ArtifactOperation { - item_id: format!("item-{thread_id}"), - lifecycle: ArtifactOperationLifecycle::Started, - occurred_at_ms: 1, - plugin_id: "presentations@openai-primary-runtime".to_string(), - script_path: "skills/presentations/container_tools/mark_artifact_operation_started.mjs" - .to_string(), - skill: "presentations".to_string(), - artifact_type: "presentation".to_string(), - operation_kind: "create".to_string(), - expected_output_count: 1, - output_format: "pptx".to_string(), - execution_backend: "unified_exec".to_string(), - }, - )) -} - -fn sample_regular_track_event(thread_id: &str) -> TrackEventRequest { - sample_skill_track_event(thread_id, /*plugin_id*/ None) -} - -#[cfg(debug_assertions)] -fn sample_mcp_tool_call_event(thread_id: &str, plugin_id: Option<&str>) -> TrackEventRequest { - TrackEventRequest::McpToolCall(CodexMcpToolCallEventRequest { - event_type: "codex_mcp_tool_call_event", - event_params: CodexMcpToolCallEventParams { - base: CodexToolItemEventBase { - turn_trigger: None, - thread_id: thread_id.to_string(), - session_id: format!("session-{thread_id}"), - turn_id: "turn-1".to_string(), - root_turn_id: None, - item_id: format!("item-{thread_id}"), - cell_id: None, - parent_call_id: None, - originating_response_id: None, - subsequent_response_id: None, - app_server_client: CodexAppServerClientMetadata { - product_client_id: "codex_desktop".to_string(), - client_name: None, - client_version: None, - rpc_transport: AppServerRpcTransport::InProcess, - experimental_api_enabled: None, - }, - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.0.0".to_string(), - runtime_os: "test".to_string(), - runtime_os_version: "test".to_string(), - runtime_arch: "test".to_string(), - }, - thread_source: None, - subagent_source: None, - parent_thread_id: None, - tool_name: "search".to_string(), - tool_event_type: None, - started_at_ms: 1, - completed_at_ms: 2, - duration_ms: Some(1), - execution_duration_ms: Some(1), - review_count: 0, - guardian_review_count: 0, - user_review_count: 0, - final_approval_outcome: FinalApprovalOutcome::NotNeeded, - terminal_status: ToolItemTerminalStatus::Completed, - failure_kind: None, - requested_additional_permissions: false, - requested_network_access: false, - }, - mcp_server_name: "sample".to_string(), - mcp_tool_name: "search".to_string(), - mcp_error_present: false, - plugin_id: plugin_id.map(str::to_string), - connector_id: None, - voice_session_id: None, - elicitation_type: None, - }, - }) -} - -#[cfg(debug_assertions)] -fn sample_plugin_used_track_event(thread_id: &str, plugin_id: Option<&str>) -> TrackEventRequest { - TrackEventRequest::PluginUsed(CodexPluginUsedEventRequest { - event_type: "codex_plugin_used", - event_params: CodexPluginUsedMetadata { - turn_trigger: None, - plugin: CodexPluginMetadata { - plugin_id: plugin_id.map(str::to_string), - remote_plugin_id: None, - plugin_name: Some("sample".to_string()), - marketplace_name: Some("test".to_string()), - has_skills: Some(true), - mcp_server_count: Some(1), - connector_ids: Some(vec!["calendar".to_string()]), - product_client_id: Some("codex_desktop".to_string()), - }, - mcp_server_names: Some(vec!["mcp-1".to_string()]), - thread_id: Some(thread_id.to_string()), - turn_id: Some("turn-1".to_string()), - model_slug: Some("gpt-5.1-codex".to_string()), - }, - }) -} - -#[cfg(debug_assertions)] -fn unique_capture_path(name: &str) -> PathBuf { - let nonce = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .expect("system clock should be after Unix epoch") - .as_nanos(); - std::env::temp_dir().join(format!( - "codex-analytics-{name}-{}-{nonce}.jsonl", - std::process::id() - )) -} - -fn client_with_receiver() -> ( - AnalyticsEventsClient, - mpsc::Receiver, -) { - let (sender, receiver) = mpsc::channel(8); - let queue = AnalyticsEventsQueue { - sender, - product_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)), - app_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - plugin_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - }; - (AnalyticsEventsClient { queue: Some(queue) }, receiver) -} - -#[test] -#[cfg(debug_assertions)] -fn analytics_destination_uses_explicit_capture_file() { - let capture_path = unique_capture_path("destination"); - let destination = AnalyticsEventsDestination::from_base_url_and_capture_file( - "https://chatgpt.com/backend-api/".into(), - Some(capture_path.clone()), - ); - - assert_eq!( - destination, - AnalyticsEventsDestination::CaptureFile { - path: capture_path.clone() - } - ); - assert_eq!( - fs::read_to_string(&capture_path).expect("read capture file"), - "" - ); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - - let mode = fs::metadata(&capture_path) - .expect("read capture file metadata") - .permissions() - .mode(); - assert_eq!(mode & 0o777, 0o600); - } - fs::remove_file(capture_path).expect("remove capture file"); -} - -#[test] -fn analytics_destination_uses_http_without_capture_file() { - let commercial_url = "https://chatgpt.com/backend-api/codex/analytics-events/events"; - let gov_url = "https://gov.chatgpt.com/backend-api/codex/analytics-events/events"; - for (base_url, expected_urls) in [ - ( - ChatgptBaseUrl::Default, - [commercial_url, gov_url, commercial_url], - ), - ( - ChatgptBaseUrl::from("https://chatgpt.com/backend-api/"), - [commercial_url; 3], - ), - ( - ChatgptBaseUrl::from("https://proxy.example/backend-api/"), - ["https://proxy.example/backend-api/codex/analytics-events/events"; 3], - ), - ] { - let destination = AnalyticsEventsDestination::from_base_url_and_capture_file( - base_url.clone(), - /*capture_file*/ None, - ); - assert_eq!( - destination, - AnalyticsEventsDestination::Http { - base_url, - api_key_headers: Default::default() - } - ); - - for (api_key, expected_url) in ["sk-test", "sk-proj-fedramp-test", "sk-test"] - .into_iter() - .zip(expected_urls) - { - let auth = codex_login::CodexAuth::from_api_key(api_key); - assert_eq!( - destination.url_for_auth(&auth).as_deref(), - Some(expected_url) - ); - } - } -} - -#[test] -#[cfg(not(debug_assertions))] -fn analytics_destination_ignores_capture_file_in_release() { - let destination = AnalyticsEventsDestination::from_base_url_and_capture_file( - "https://chatgpt.com/backend-api/".into(), - Some(std::path::PathBuf::from("ignored.jsonl")), - ); - - assert_eq!( - destination, - AnalyticsEventsDestination::Http { - base_url: "https://chatgpt.com/backend-api/".into(), - api_key_headers: Default::default(), - } - ); -} - -#[tokio::test] -#[cfg(debug_assertions)] -async fn capture_file_writes_exact_serialized_request() { - let capture_path = unique_capture_path("single"); - let destination = AnalyticsEventsDestination::CaptureFile { - path: capture_path.clone(), - }; - let event = sample_regular_track_event("thread-1"); - let expected_event = serde_json::to_value(&event).expect("serialize expected event"); - let auth = codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault); - // Capture-only delivery must not initialize or depend on runtime authentication. - let runtime = (Default::default(), Default::default()); - send_track_events_request( - &auth, - &destination, - vec![event], - &factory, - /*product_sku*/ None, - Some(&runtime), - ) - .await; - - let contents = fs::read_to_string(&capture_path).expect("read capture file"); - let lines = contents.lines().collect::>(); - assert_eq!(lines.len(), 1); - let payload: serde_json::Value = - serde_json::from_str(lines[0]).expect("parse captured payload"); - assert_eq!(payload, serde_json::json!({"events": [expected_event]})); - - fs::remove_file(capture_path).expect("remove capture file"); -} - -#[tokio::test] -#[cfg(debug_assertions)] -async fn capture_file_writes_final_batches_as_separate_lines() { - let capture_path = unique_capture_path("batches"); - let destination = AnalyticsEventsDestination::CaptureFile { - path: capture_path.clone(), - }; - let auth = codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let events = vec![ - sample_regular_track_event("thread-1"), - sample_accepted_line_fingerprint_event("thread-2"), - sample_regular_track_event("thread-3"), - ]; - - for batch in track_event_request_batches(events) { - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault); - send_track_events_request( - &auth, - &destination, - batch, - &factory, - /*product_sku*/ None, - /*runtime_auth*/ None, - ) - .await; - } - - let contents = fs::read_to_string(&capture_path).expect("read capture file"); - let payloads = contents - .lines() - .map(|line| serde_json::from_str::(line).expect("parse capture line")) - .collect::>(); - assert_eq!(payloads.len(), 3); - assert_eq!(payloads[0]["events"][0]["skill_id"], "skill-thread-1"); - assert_eq!( - payloads[1]["events"][0]["event_type"], - "codex_accepted_line_fingerprints" - ); - assert_eq!(payloads[2]["events"][0]["skill_id"], "skill-thread-3"); - - fs::remove_file(capture_path).expect("remove capture file"); -} - -#[tokio::test] -#[cfg(debug_assertions)] -async fn api_key_auth_sends_only_plugin_events_to_codex_backend() { - let capture_path = unique_capture_path("api-key-plugin-events"); - let destination = AnalyticsEventsDestination::CaptureFile { - path: capture_path.clone(), - }; - let auth_manager = codex_login::AuthManager::from_auth_for_testing( - codex_login::CodexAuth::from_api_key("sk-test"), - ); - let plugin_measurement = |thread_id: &str, plugin_id: &str| { - TrackEventRequest::PluginMeasurement(CodexPluginMeasurementEventRequest { - event_type: "codex_plugin_measurement_event", - event_params: CodexPluginMeasurementEventParams { - model_slug: None, - reasoning_effort: None, - thread_id: thread_id.to_string(), - turn_id: "turn-1".to_string(), - item_id: "item-1".to_string(), - originator: "codex_cli_rs".to_string(), - plugin_id: plugin_id.to_string(), - execution_id: "execution-1".to_string(), - operation: "security_scan".to_string(), - measurement_name: "findings".to_string(), - number_value: 1.0, - dimensions: None, - }, - }) - }; - - send_track_events( - &auth_manager, - &destination, - vec![ - sample_regular_track_event("non-plugin-skill"), - sample_mcp_tool_call_event("non-plugin-mcp", /*plugin_id*/ None), - sample_plugin_used_track_event("non-plugin-used", /*plugin_id*/ None), - plugin_measurement("non-plugin-measurement", /*plugin_id*/ ""), - sample_accepted_line_fingerprint_event("other-event"), - TrackEventRequest::ThreadArchive(ThreadArchiveEvent { - event_type: "codex_thread_archive_event", - event_params: ThreadArchiveEventParams { - thread_id: "non-plugin-thread-archive".to_string(), - action: ThreadArchiveAction::Archived, - occurred_at_ms: 1, - app_server_client: None, - runtime: None, - thread_source: None, - parent_thread_id: None, - }, - }), - sample_plugin_used_track_event("plugin-used", Some("sample@test")), - sample_skill_track_event("plugin-skill", Some("sample@test")), - sample_mcp_tool_call_event("plugin-mcp", Some("sample@test")), - sample_artifact_operation_event("plugin-artifact"), - plugin_measurement("plugin-measurement", "sample@test"), - ], - &ThreadProducts::default(), - /*runtime_auth*/ None, - ) - .await; - - let contents = fs::read_to_string(&capture_path).expect("read capture file"); - let lines = contents.lines().collect::>(); - assert_eq!(lines.len(), 1); - let payload: serde_json::Value = - serde_json::from_str(lines[0]).expect("parse captured payload"); - let events = payload["events"].as_array().expect("events array"); - for event in events { - let event_params = event["event_params"].as_object().expect("event params"); - for server_owned_field in [ - "auth_mode", - "api_organization_id", - "api_project_id", - "api_key_tracking_id", - ] { - assert!(!event_params.contains_key(server_owned_field)); - } - } - let delivered_events = events - .iter() - .map(|event| { - serde_json::json!({ - "event_type": event["event_type"], - "plugin_id": event["event_params"]["plugin_id"], - "thread_id": event["event_params"]["thread_id"], - }) - }) - .collect::>(); - assert_eq!( - delivered_events, - vec![ - serde_json::json!({ - "event_type": "codex_plugin_used", - "plugin_id": "sample@test", - "thread_id": "plugin-used", - }), - serde_json::json!({ - "event_type": "skill_invocation", - "plugin_id": "sample@test", - "thread_id": "plugin-skill", - }), - serde_json::json!({ - "event_type": "codex_mcp_tool_call_event", - "plugin_id": "sample@test", - "thread_id": "plugin-mcp", - }), - serde_json::json!({ - "event_type": "codex_artifact_operation", - "plugin_id": "presentations@openai-primary-runtime", - "thread_id": "plugin-artifact", - }), - serde_json::json!({ - "event_type": "codex_plugin_measurement_event", - "plugin_id": "sample@test", - "thread_id": "plugin-measurement", - }), - ] - ); - - fs::remove_file(capture_path).expect("remove capture file"); -} - -#[test] -#[cfg(debug_assertions)] -fn capture_write_failure_still_consumes_delivery() { - let capture_path = unique_capture_path("missing-parent").join("events.jsonl"); - let destination = AnalyticsEventsDestination::CaptureFile { path: capture_path }; - let payload = crate::events::TrackEventsRequest { - events: vec![sample_regular_track_event("thread-1")], - }; - - assert!(capture_track_events_request(&destination, &payload)); -} - -fn sample_turn_start_request() -> ClientRequest { - ClientRequest::TurnStart { - request_id: RequestId::Integer(1), - params: TurnStartParams { - thread_id: "thread-1".to_string(), - client_user_message_id: None, - input: Vec::new(), - ..Default::default() - }, - } -} - -fn sample_turn_steer_request() -> ClientRequest { - ClientRequest::TurnSteer { - request_id: RequestId::Integer(2), - params: TurnSteerParams { - thread_id: "thread-1".to_string(), - expected_turn_id: "turn-1".to_string(), - client_user_message_id: None, - input: Vec::new(), - responsesapi_client_metadata: None, - responsesapi_client_metadata_patch: None, - additional_context: None, - }, - } -} - -fn sample_turn_interrupt_request(turn_id: &str) -> ClientRequest { - ClientRequest::TurnInterrupt { - request_id: RequestId::Integer(3), - params: TurnInterruptParams { - thread_id: "thread-1".to_string(), - turn_id: turn_id.to_string(), - }, - } -} - -fn sample_turn_interrupt_response() -> ClientResponsePayload { - ClientResponsePayload::TurnInterrupt(TurnInterruptResponse {}) -} - -fn sample_thread_archive_request() -> ClientRequest { - ClientRequest::ThreadArchive { - request_id: RequestId::Integer(3), - params: ThreadArchiveParams { - thread_id: "thread-1".to_string(), - }, - } -} - -fn sample_thread(thread_id: &str) -> Thread { - Thread { - originator: None, - environments: None, - id: thread_id.to_string(), - extra: None, - session_id: format!("session-{thread_id}"), - forked_from_id: None, - parent_thread_id: None, - preview: "first prompt".to_string(), - ephemeral: false, - section: None, - section_entered_at: None, - project_id: None, - daybreak_enabled: None, - history_mode: Default::default(), - model_provider: "openai".to_string(), - model: None, - reasoning_effort: None, - created_at: 1, - updated_at: 2, - recency_at: Some(2), - status: AppServerThreadStatus::Idle, - path: None, - cwd: test_path_buf("/tmp").abs(), - cli_version: "0.0.0".to_string(), - source: AppServerSessionSource::Exec, - can_accept_direct_input: None, - thread_source: None, - agent_nickname: None, - agent_role: None, - git_info: None, - name: None, - turns: Vec::new(), - } -} - -fn sample_thread_start_response() -> ClientResponsePayload { - ClientResponsePayload::ThreadStart(ThreadStartResponse { - disabled_plugin_ids: Vec::new(), - thread: sample_thread("thread-1"), - model: "gpt-5".to_string(), - model_provider: "openai".to_string(), - service_tier: None, - cwd: test_path_buf("/tmp").abs(), - runtime_workspace_roots: Vec::new(), - instruction_sources: Vec::new(), - approval_policy: AppServerAskForApproval::OnRequest, - approvals_reviewer: AppServerApprovalsReviewer::User, - sandbox: AppServerSandboxPolicy::DangerFullAccess, - active_permission_profile: None, - reasoning_effort: None, - multi_agent_mode: Default::default(), - }) -} - -fn sample_thread_resume_response() -> ClientResponsePayload { - ClientResponsePayload::ThreadResume(ThreadResumeResponse { - disabled_plugin_ids: Vec::new(), - thread: sample_thread("thread-2"), - model: "gpt-5".to_string(), - model_provider: "openai".to_string(), - service_tier: None, - cwd: test_path_buf("/tmp").abs(), - runtime_workspace_roots: Vec::new(), - instruction_sources: Vec::new(), - approval_policy: AppServerAskForApproval::OnRequest, - approvals_reviewer: AppServerApprovalsReviewer::User, - sandbox: AppServerSandboxPolicy::DangerFullAccess, - active_permission_profile: None, - reasoning_effort: None, - collaboration_mode: None, - multi_agent_mode: Default::default(), - initial_turns_page: None, - turns_backwards_cursor: None, - items_backwards_cursor: None, - }) -} - -fn sample_thread_fork_response() -> ClientResponsePayload { - ClientResponsePayload::ThreadFork(ThreadForkResponse { - disabled_plugin_ids: Vec::new(), - thread: sample_thread("thread-3"), - model: "gpt-5".to_string(), - model_provider: "openai".to_string(), - service_tier: None, - cwd: test_path_buf("/tmp").abs(), - runtime_workspace_roots: Vec::new(), - instruction_sources: Vec::new(), - approval_policy: AppServerAskForApproval::OnRequest, - approvals_reviewer: AppServerApprovalsReviewer::User, - sandbox: AppServerSandboxPolicy::DangerFullAccess, - active_permission_profile: None, - reasoning_effort: None, - multi_agent_mode: Default::default(), - }) -} - -fn sample_turn_start_response() -> ClientResponsePayload { - ClientResponsePayload::TurnStart(TurnStartResponse { - turn: Turn { - id: "turn-1".to_string(), - root_turn_id: None, - items_view: codex_app_server_protocol::TurnItemsView::Full, - items: Vec::new(), - status: AppServerTurnStatus::InProgress, - error: None, - started_at: None, - completed_at: None, - duration_ms: None, - }, - }) -} - -fn sample_turn_steer_response() -> ClientResponsePayload { - ClientResponsePayload::TurnSteer(TurnSteerResponse { - turn_id: "turn-2".to_string(), - }) -} - -#[test] -fn track_plugin_measurements_rejects_unbounded_inputs_before_queueing() { - let (client, mut receiver) = client_with_receiver(); - let measurements = |row_count| PluginMeasurementsInput { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "item-1".to_string(), - originator: "codex_cli_rs".to_string(), - model_slug: None, - reasoning_effort: None, - plugin_id: "sample@openai-curated".to_string(), - execution_id: "execution-1".to_string(), - operation: "security_scan".to_string(), - rows: vec![ - PluginMeasurementRow { - measurement_name: "finding_count".to_string(), - number_value: 1.0, - dimensions: BTreeMap::new(), - }; - row_count - ], - }; - - client.track_plugin_measurements(measurements(MAX_PLUGIN_MEASUREMENTS_PER_BATCH + 1)); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); - - let mut oversized_operation = measurements(1); - oversized_operation.operation = "o".repeat(65); - client.track_plugin_measurements(oversized_operation); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); - - let mut mixed_rows = measurements(4); - mixed_rows.rows[0].measurement_name = "m".repeat(65); - mixed_rows.rows[1] - .dimensions - .insert("d".repeat(65), "valid".to_string()); - mixed_rows.rows[2] - .dimensions - .insert("valid".to_string(), "v".repeat(65)); - client.track_plugin_measurements(mixed_rows); - assert!(matches!( - receiver.try_recv(), - Ok(AnalyticsEventsQueueMessage::Fact(fact)) - if matches!( - fact.as_ref(), - AnalyticsFact::Custom(CustomAnalyticsFact::PluginMeasurements(input)) - if input.rows.len() == 1 - && input.rows[0].measurement_name == "finding_count" - ) - )); - - client.track_plugin_measurements(measurements(MAX_PLUGIN_MEASUREMENTS_PER_BATCH)); - assert!(matches!( - receiver.try_recv(), - Ok(AnalyticsEventsQueueMessage::Fact(fact)) - if matches!( - fact.as_ref(), - AnalyticsFact::Custom(CustomAnalyticsFact::PluginMeasurements(input)) - if input.rows.len() == MAX_PLUGIN_MEASUREMENTS_PER_BATCH - ) - )); -} - -#[test] -fn track_request_only_enqueues_analytics_relevant_requests() { - let (client, mut receiver) = client_with_receiver(); - - for (request_id, request) in [ - (RequestId::Integer(1), sample_turn_start_request()), - (RequestId::Integer(2), sample_turn_steer_request()), - ] { - client.track_request(/*connection_id*/ 7, request_id, &request); - assert!(matches!( - receiver.try_recv(), - Ok(AnalyticsEventsQueueMessage::Fact(input)) - if matches!(*input, AnalyticsFact::ClientRequest { .. }) - )); - } - - client.track_request( - /*connection_id*/ 7, - RequestId::Integer(3), - &sample_turn_interrupt_request("turn-1"), - ); - assert!(matches!( - receiver.try_recv(), - Ok(AnalyticsEventsQueueMessage::Fact(input)) - if matches!( - *input, - AnalyticsFact::ExplicitClientInterruptRequest { - ref turn_id, - requested_at_ms, - .. - } if turn_id == "turn-1" && requested_at_ms > 0 - ) - )); - - let ignored_request = sample_thread_archive_request(); - client.track_request( - /*connection_id*/ 7, - RequestId::Integer(3), - &ignored_request, - ); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); - - client.track_request( - /*connection_id*/ 7, - RequestId::Integer(4), - &sample_turn_interrupt_request(""), - ); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[test] -fn track_response_only_enqueues_analytics_relevant_responses() { - let (client, mut receiver) = client_with_receiver(); - - for (request_id, response) in [ - (RequestId::Integer(1), sample_thread_start_response()), - (RequestId::Integer(2), sample_thread_resume_response()), - (RequestId::Integer(3), sample_thread_fork_response()), - (RequestId::Integer(4), sample_turn_start_response()), - (RequestId::Integer(5), sample_turn_steer_response()), - (RequestId::Integer(6), sample_turn_interrupt_response()), - ] { - client.track_response(/*connection_id*/ 7, request_id, &response); - assert!(matches!( - receiver.try_recv(), - Ok(AnalyticsEventsQueueMessage::Fact(input)) - if matches!(*input, AnalyticsFact::ClientResponse { .. }) - )); - } - - client.track_response( - /*connection_id*/ 7, - RequestId::Integer(7), - &ClientResponsePayload::ThreadArchive(ThreadArchiveResponse {}), - ); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[cfg(unix)] -#[test] -fn track_response_ignores_unserializable_thread_responses() { - use std::ffi::OsString; - use std::os::unix::ffi::OsStringExt; - - let (client, mut receiver) = client_with_receiver(); - let mut response = sample_thread_start_response(); - let ClientResponsePayload::ThreadStart(thread_start) = &mut response else { - panic!("expected thread/start response"); - }; - thread_start.cwd = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path( - std::path::PathBuf::from(OsString::from_vec(vec![b'/', b'b', b'a', b'd', 0xff])), - ) - .expect("non-UTF-8 Unix paths are valid absolute paths"); - - client.track_response(/*connection_id*/ 7, RequestId::Integer(1), &response); - - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[tokio::test] -async fn flush_waits_for_preceding_fact_delivery() { - let (client, mut receiver) = client_with_receiver(); - client.track_request( - /*connection_id*/ 7, - RequestId::Integer(1), - &sample_turn_start_request(), - ); - - let flush = tokio::spawn(async move { client.flush().await }); - assert!(matches!( - receiver.recv().await, - Some(AnalyticsEventsQueueMessage::Fact(input)) - if matches!(*input, AnalyticsFact::ClientRequest { .. }) - )); - let done_tx = match receiver.recv().await { - Some(AnalyticsEventsQueueMessage::Flush(done_tx)) => done_tx, - _ => panic!("expected analytics flush barrier"), - }; - tokio::time::sleep(std::time::Duration::from_millis(25)).await; - assert!(!flush.is_finished()); - done_tx.send(()).expect("flush receiver should remain open"); - flush.await.expect("flush task should complete"); -} - -#[tokio::test] -async fn flush_is_noop_when_analytics_is_disabled() { - let client = AnalyticsEventsClient::new( - codex_login::AuthManager::from_auth_for_testing( - codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - "https://chatgpt.com/backend-api".to_string(), - /*analytics_enabled*/ Some(false), - ); - client.track_notification(&ServerNotification::ThreadArchived( - ThreadArchivedNotification { - thread_id: "thread-1".to_string(), - }, - )); - assert!(client.queue.is_none()); - client.flush().await; -} - -#[test] -fn app_used_preserves_first_classification_and_emits_again_next_turn() { - let (client, mut receiver) = client_with_receiver(); - let tracking = TrackEventsContext { - turn_metadata: None, - model_slug: "gpt-5".to_string(), - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - product_client_id: "codex_desktop".to_string(), - }; - for (turn_id, elicitation_type) in [ - ("turn-1", Some(ElicitationType::AuthOrLink)), - ("turn-1", None), - ("turn-2", None), - ] { - client.track_app_used( - TrackEventsContext { - turn_id: turn_id.to_string(), - ..tracking.clone() - }, - AppInvocation { - connector_id: Some("calendar".to_string()), - app_name: Some("Calendar".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type, - ); - } - for (turn_id, elicitation_type) in [ - ("turn-1", Some(ElicitationType::AuthOrLink)), - ("turn-2", None), - ] { - let Ok(AnalyticsEventsQueueMessage::Fact(input)) = receiver.try_recv() else { - panic!("expected app-used analytics fact"); - }; - let AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(input)) = *input else { - panic!("expected app-used analytics fact"); - }; - assert_eq!( - ( - input.tracking.turn_id.as_str(), - input.app.connector_id.as_deref(), - input.elicitation_type, - ), - (turn_id, Some("calendar"), elicitation_type) - ); - } - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[test] -fn track_notification_only_enqueues_analytics_relevant_notifications() { - let (client, mut receiver) = client_with_receiver(); - let tracked_payload = TurnDiffUpdatedNotification { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - diff: "diff".to_string(), - }; - let tracked_notification = ServerNotification::TurnDiffUpdated(tracked_payload.clone()); - - client.track_notification(&tracked_notification); - - let Ok(AnalyticsEventsQueueMessage::Fact(input)) = receiver.try_recv() else { - panic!("expected analytics notification"); - }; - let AnalyticsFact::Notification(notification) = *input else { - panic!("expected analytics notification fact"); - }; - let ServerNotification::TurnDiffUpdated(notification) = *notification else { - panic!("expected turn diff notification"); - }; - assert_eq!(notification, tracked_payload); - - let ignored_notification = - ServerNotification::CommandExecutionOutputDelta(CommandExecutionOutputDeltaNotification { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "item-1".to_string(), - delta: "output".to_string(), - }); - - client.track_notification(&ignored_notification); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[test] -fn track_notification_records_realtime_session_boundaries() { - let (client, mut receiver) = client_with_receiver(); - - client.track_notification(&ServerNotification::ThreadRealtimeStarted( - ThreadRealtimeStartedNotification { - thread_id: "thread-1".to_string(), - realtime_session_id: Some("voice-session-1".to_string()), - version: RealtimeConversationVersion::V2, - }, - )); - - let Ok(AnalyticsEventsQueueMessage::Fact(input)) = receiver.try_recv() else { - panic!("expected realtime session started fact"); - }; - let AnalyticsFact::RealtimeSessionStarted { - thread_id, - realtime_session_id, - started_at, - } = *input - else { - panic!("expected realtime session started fact"); - }; - assert_eq!(thread_id, "thread-1"); - assert_eq!(realtime_session_id.as_deref(), Some("voice-session-1")); - assert!(started_at > 0); - - client.track_notification(&ServerNotification::ThreadRealtimeClosed( - ThreadRealtimeClosedNotification { - thread_id: "thread-1".to_string(), - reason: Some("completed".to_string()), - }, - )); - - let Ok(AnalyticsEventsQueueMessage::Fact(input)) = receiver.try_recv() else { - panic!("expected realtime session closed fact"); - }; - let AnalyticsFact::RealtimeSessionClosed { - thread_id, - closed_at, - } = *input - else { - panic!("expected realtime session closed fact"); - }; - assert_eq!(thread_id, "thread-1"); - assert!(closed_at >= started_at); -} - -#[test] -fn realtime_handoff_tracks_only_marker_without_transcript() { - let (client, mut receiver) = client_with_receiver(); - client.track_notification(&ServerNotification::ThreadRealtimeItemAdded( - ThreadRealtimeItemAddedNotification { - thread_id: "thread-1".to_string(), - item: serde_json::json!({ - "type": "handoff_request", - "input_transcript": "private speech", - }), - }, - )); - let Ok(AnalyticsEventsQueueMessage::Fact(input)) = receiver.try_recv() else { - panic!("expected realtime handoff marker"); - }; - assert!(matches!( - *input, - AnalyticsFact::RealtimeHandoffRequested { thread_id } if thread_id == "thread-1" - )); - client.track_notification(&ServerNotification::ThreadRealtimeItemAdded( - ThreadRealtimeItemAddedNotification { - thread_id: "thread-1".to_string(), - item: serde_json::json!({"type": "input_transcript"}), - }, - )); - assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty))); -} - -#[test] -fn track_event_request_batches_only_isolates_accepted_line_fingerprint_events() { - let batches = track_event_request_batches(vec![ - sample_regular_track_event("thread-1"), - sample_regular_track_event("thread-2"), - sample_accepted_line_fingerprint_event("thread-3"), - sample_accepted_line_fingerprint_event("thread-4"), - sample_regular_track_event("thread-5"), - sample_regular_track_event("thread-6"), - ]); - - assert_eq!(batches.len(), 4); - assert_eq!(batches[0].len(), 2); - assert_eq!(batches[1].len(), 1); - assert_eq!(batches[2].len(), 1); - assert_eq!(batches[3].len(), 2); - assert!(batches[1][0].should_send_in_isolated_request()); - assert!(batches[2][0].should_send_in_isolated_request()); -} - -#[cfg(debug_assertions)] -#[tokio::test] -async fn account_switch_between_batches_does_not_send_old_credentials() { - use codex_http_client::DestinationPolicy; - use codex_http_client::NetworkPolicyController; - use codex_login::AuthCredentialsStoreMode as Store; - use tokio::io::AsyncReadExt; - use tokio::io::AsyncWriteExt; - - let home = unique_capture_path("batch-account-switch"); - fs::create_dir_all(&home).unwrap(); - let mut stored: codex_login::AuthDotJson = serde_json::from_value(serde_json::json!({ - "auth_mode": "chatgptAuthTokens", - "tokens": { - "id_token": "e30.e30.sig", - "access_token": "test-access-token-a", - "refresh_token": "", - "account_id": "account-a", - }, - })) - .unwrap(); - stored.last_refresh = Some(SystemTime::now().into()); - codex_login::save_auth(&home, &stored, Store::File, Default::default()).unwrap(); - let controller = NetworkPolicyController::default(); - let policy = controller.policy(); - let manager = Arc::new( - codex_login::AuthManager::new( - home.clone(), - /*enable_codex_api_key_env*/ false, - Store::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - Default::default(), - codex_login::AuthRouteConfig::from_http_client_factory( - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) - .with_network_policy(policy.clone()), - ), - ) - .await, - ); - assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted)); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let destination = AnalyticsEventsDestination::Http { - base_url: format!("http://{}", listener.local_addr().unwrap()).into(), - api_key_headers: Default::default(), - }; - let requests = Arc::new(Mutex::new(Vec::new())); - let captured = Arc::clone(&requests); - let server_manager = Arc::clone(&manager); - let server_home = home.clone(); - let server = tokio::spawn(async move { - loop { - let (mut stream, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - loop { - let mut buffer = [0; 4096]; - let count = stream.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") { - let headers = String::from_utf8_lossy(&request[..end]).to_lowercase(); - let length: usize = headers - .lines() - .find_map(|line| line.strip_prefix("content-length: ")) - .unwrap() - .parse() - .unwrap(); - if request.len() >= end + 4 + length { - break; - } - } - } - let first = { - let mut requests = captured.lock().unwrap(); - requests.push(String::from_utf8(request).unwrap()); - requests.len() == 1 - }; - if first { - let tokens = stored.tokens.as_mut().unwrap(); - tokens.account_id = Some("account-b".to_string()); - tokens.access_token = "test-access-token-b".to_string(); - codex_login::save_auth(&server_home, &stored, Store::File, Default::default()) - .unwrap(); - server_manager.reload().await; - assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted)); - } - let _ = stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") - .await; - } - }); - let events = vec![ - sample_accepted_line_fingerprint_event("one"), - sample_accepted_line_fingerprint_event("two"), - ]; - send_track_events( - &manager, - &destination, - events, - &ThreadProducts::default(), - /*runtime_auth*/ None, - ) - .await; - server.abort(); - let _ = server.await; - let requests = requests.lock().unwrap(); - assert_eq!(requests.len(), 1); - assert!( - requests[0] - .to_lowercase() - .contains("chatgpt-account-id: account-a") - ); - assert!(requests[0].contains("test-access-token-a")); - fs::remove_dir_all(home).unwrap(); -} diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs deleted file mode 100644 index bb0a74d5..00000000 --- a/codex-rs/analytics/src/events.rs +++ /dev/null @@ -1,1629 +0,0 @@ -use std::sync::LazyLock; -use std::time::Duration; - -use crate::facts::AppInvocation; -use crate::facts::ArtifactOperation; -use crate::facts::ArtifactOperationLifecycle; -use crate::facts::CodexCompactionEvent; -use crate::facts::CodexErrKind; -use crate::facts::CodexGoalEvent; -use crate::facts::CompactionImplementation; -use crate::facts::CompactionPhase; -use crate::facts::CompactionReason; -use crate::facts::CompactionStatus; -use crate::facts::CompactionStrategy; -use crate::facts::CompactionTrigger; -use crate::facts::ElicitationType; -use crate::facts::GoalEventKind; -use crate::facts::HookRunFact; -use crate::facts::ImagePreparationMetadata; -use crate::facts::InvocationType; -use crate::facts::PluginInstallRequested; -use crate::facts::PluginState; -use crate::facts::SubAgentThreadStartedInput; -use crate::facts::ThreadInitializationMode; -use crate::facts::TrackEventsContext; -use crate::facts::TurnAnalyticsMetadata; -use crate::facts::TurnStatus; -use crate::facts::TurnSteerRejectionReason; -use crate::facts::TurnSteerResult; -use crate::facts::TurnSubmissionType; -use crate::guardian_v2::GuardianV2EventRequest; -use crate::now_unix_millis; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::CommandExecutionSource; -use codex_login::default_client::originator; -use codex_plugin::PluginId; -use codex_plugin::PluginTelemetryMetadata; -use codex_protocol::approvals::NetworkApprovalProtocol; -use codex_protocol::models::AdditionalPermissionProfile; -use codex_protocol::models::SandboxPermissions; -use codex_protocol::protocol::GuardianAssessmentOutcome; -use codex_protocol::protocol::GuardianCommandSource; -use codex_protocol::protocol::GuardianRiskLevel; -use codex_protocol::protocol::GuardianUserAuthorization; -use codex_protocol::protocol::HookEventName; -use codex_protocol::protocol::HookExecutionMode; -use codex_protocol::protocol::HookHandlerType; -use codex_protocol::protocol::HookRunStatus; -use codex_protocol::protocol::HookSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadSource; -use codex_protocol::protocol::TokenUsage; -use serde::Serialize; -use std::collections::BTreeMap; - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum AppServerRpcTransport { - Stdio, - Websocket, - InProcess, -} - -#[derive(Serialize)] -pub(crate) struct TrackEventsRequest { - pub(crate) events: Vec, -} - -#[derive(Serialize)] -#[serde(untagged)] -pub(crate) enum TrackEventRequest { - SkillInvocation(SkillInvocationEventRequest), - ThreadInitialized(ThreadInitializedEvent), - ThreadArchive(ThreadArchiveEvent), - GuardianReview(Box), - GuardianV2(Box), - AppMentioned(CodexAppMentionedEventRequest), - AppUsed(CodexAppUsedEventRequest), - HookRun(CodexHookRunEventRequest), - Compaction(Box), - Goal(Box), - ThreadHintStatus(Box), - TurnEvent(Box), - TurnSteer(CodexTurnSteerEventRequest), - ArtifactOperation(CodexArtifactOperationEventRequest), - CommandExecution(CodexCommandExecutionEventRequest), - PluginMeasurement(CodexPluginMeasurementEventRequest), - FileChange(CodexFileChangeEventRequest), - CuaToolCallStarted(CodexCuaToolCallStartedEventRequest), - McpToolCall(CodexMcpToolCallEventRequest), - DynamicToolCall(CodexDynamicToolCallEventRequest), - ControlToolCall(CodexControlToolCallEventRequest), - CollabAgentToolCall(CodexCollabAgentToolCallEventRequest), - WebSearch(CodexWebSearchEventRequest), - ImageGeneration(CodexImageGenerationEventRequest), - AcceptedLineFingerprints(Box), - #[allow(dead_code)] - ReviewEvent(CodexReviewEventRequest), - PluginUsed(CodexPluginUsedEventRequest), - PluginInstallRequested(CodexPluginInstallRequestedEventRequest), - PluginInstalled(CodexPluginEventRequest), - PluginUninstalled(CodexPluginEventRequest), - PluginEnabled(CodexPluginEventRequest), - PluginDisabled(CodexPluginEventRequest), - PluginInstallFailed(CodexPluginInstallFailedEventRequest), - ExternalAgentConfigImportCompleted(CodexOnboardingExternalAgentImportCompleteEventRequest), - ExternalAgentConfigImportFailure(CodexOnboardingExternalAgentImportFailureEventRequest), -} - -#[derive(Serialize)] -pub(crate) struct CodexArtifactOperationEventParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) thread_id: String, - pub(crate) turn_id: String, - pub(crate) item_id: String, - pub(crate) lifecycle: ArtifactOperationLifecycle, - pub(crate) occurred_at_ms: u64, - pub(crate) product_client_id: String, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) model_slug: String, - pub(crate) plugin_id: String, - pub(crate) script_path: String, - pub(crate) skill: String, - pub(crate) artifact_type: String, - pub(crate) operation_kind: String, - pub(crate) expected_output_count: u32, - pub(crate) output_format: String, - pub(crate) execution_backend: String, -} - -#[derive(Serialize)] -pub(crate) struct CodexArtifactOperationEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexArtifactOperationEventParams, -} - -pub(crate) fn codex_artifact_operation_event_request( - tracking: TrackEventsContext, - operation: ArtifactOperation, -) -> CodexArtifactOperationEventRequest { - let turn = tracking.turn_metadata.as_deref(); - CodexArtifactOperationEventRequest { - event_type: "codex_artifact_operation", - event_params: CodexArtifactOperationEventParams { - turn_trigger: turn.and_then(TurnAnalyticsMetadata::turn_trigger), - thread_id: tracking.thread_id, - turn_id: tracking.turn_id, - item_id: operation.item_id, - lifecycle: operation.lifecycle, - occurred_at_ms: operation.occurred_at_ms, - product_client_id: tracking.product_client_id, - runtime: current_runtime_metadata(), - model_slug: tracking.model_slug, - plugin_id: operation.plugin_id, - script_path: operation.script_path, - skill: operation.skill, - artifact_type: operation.artifact_type, - operation_kind: operation.operation_kind, - expected_output_count: operation.expected_output_count, - output_format: operation.output_format, - execution_backend: operation.execution_backend, - }, - } -} - -impl TrackEventRequest { - pub(crate) fn should_send_in_isolated_request(&self) -> bool { - matches!(self, Self::AcceptedLineFingerprints(_)) - } - - pub(crate) fn can_send_with_api_key_auth(&self) -> bool { - match self { - Self::PluginUsed(event) => event.event_params.plugin.plugin_id.is_some(), - Self::SkillInvocation(event) => event.event_params.plugin_id.is_some(), - Self::CuaToolCallStarted(event) => event.event_params.plugin_id.is_some(), - Self::McpToolCall(event) => event.event_params.plugin_id.is_some(), - Self::ArtifactOperation(event) => !event.event_params.plugin_id.is_empty(), - Self::PluginMeasurement(event) => !event.event_params.plugin_id.is_empty(), - _ => false, - } - } -} - -#[derive(Serialize)] -pub(crate) struct CodexAcceptedLineFingerprintsEventParams { - pub(crate) event_type: &'static str, - pub(crate) turn_id: String, - pub(crate) thread_id: String, - pub(crate) product_surface: Option, - pub(crate) model_slug: Option, - pub(crate) completed_at: u64, - pub(crate) repo_hash: Option, - pub(crate) accepted_added_lines: u64, - pub(crate) accepted_deleted_lines: u64, - // Analytics ingestion and warehouse schemas require this field on the wire. - // Keep it statically empty; line fingerprints are no longer generated. - pub(crate) line_fingerprints: [(); 0], -} - -#[derive(Serialize)] -pub(crate) struct CodexAcceptedLineFingerprintsEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexAcceptedLineFingerprintsEventParams, -} - -#[derive(Serialize)] -pub(crate) struct SkillInvocationEventRequest { - pub(crate) event_type: &'static str, - pub(crate) skill_id: String, - pub(crate) skill_name: String, - pub(crate) event_params: SkillInvocationEventParams, -} - -#[derive(Serialize)] -pub(crate) struct SkillInvocationEventParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) product_client_id: Option, - pub(crate) skill_scope: Option, - pub(crate) plugin_id: Option, - pub(crate) remote_plugin_id: Option, - pub(crate) thread_id: Option, - pub(crate) turn_id: Option, - pub(crate) voice_session_id: Option, - pub(crate) invoke_type: Option, - pub(crate) model_slug: Option, -} - -#[derive(Clone, Serialize)] -pub(crate) struct CodexAppServerClientMetadata { - pub(crate) product_client_id: String, - pub(crate) client_name: Option, - pub(crate) client_version: Option, - pub(crate) rpc_transport: AppServerRpcTransport, - pub(crate) experimental_api_enabled: Option, -} - -#[derive(Clone, Serialize)] -pub(crate) struct CodexRuntimeMetadata { - pub(crate) codex_rs_version: String, - pub(crate) runtime_os: String, - pub(crate) runtime_os_version: String, - pub(crate) runtime_arch: String, -} - -#[derive(Serialize)] -pub(crate) struct ThreadInitializedEventParams { - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) model: String, - pub(crate) ephemeral: bool, - /// Whether the thread's checkout is a validated linked Git worktree, if known. - pub(crate) is_worktree: Option, - pub(crate) thread_source: Option, - pub(crate) initialization_mode: ThreadInitializationMode, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) forked_from_thread_id: Option, - pub(crate) created_at: u64, -} - -#[derive(Serialize)] -pub(crate) struct ThreadInitializedEvent { - pub(crate) event_type: &'static str, - pub(crate) event_params: ThreadInitializedEventParams, -} - -#[derive(Clone, Copy, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ThreadArchiveAction { - Archived, - Unarchived, -} - -#[derive(Serialize)] -pub(crate) struct ThreadArchiveEventParams { - pub(crate) thread_id: String, - pub(crate) action: ThreadArchiveAction, - pub(crate) occurred_at_ms: u64, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) app_server_client: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) runtime: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) thread_source: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) parent_thread_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct ThreadArchiveEvent { - pub(crate) event_type: &'static str, - pub(crate) event_params: ThreadArchiveEventParams, -} - -#[derive(Serialize)] -pub(crate) struct GuardianReviewEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: GuardianReviewEventPayload, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GuardianReviewDecision { - Approved, - Denied, - Aborted, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GuardianReviewTerminalStatus { - Approved, - Denied, - Aborted, - TimedOut, - FailedClosed, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GuardianReviewFailureReason { - StaleAuthorization, - Timeout, - Cancelled, - PromptBuildError, - SessionError, - ParseError, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GuardianReviewSessionKind { - TrunkNew, - TrunkReused, - EphemeralForked, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GuardianApprovalRequestSource { - /// Approval requested directly by the main Codex turn. - MainTurn, - /// Approval requested by a delegated subagent and routed through the parent - /// session for guardian review. - DelegatedSubagent, -} - -/// Path-free permission metadata for a Guardian reviewed action. -#[derive(Clone, Debug, Serialize)] -pub struct GuardianAdditionalPermissions { - network: Option, -} - -#[derive(Clone, Debug, Serialize)] -struct GuardianNetworkPermissions { - enabled: Option, -} - -impl From<&AdditionalPermissionProfile> for GuardianAdditionalPermissions { - fn from(permissions: &AdditionalPermissionProfile) -> Self { - Self { - network: permissions - .network - .as_ref() - .map(|network| GuardianNetworkPermissions { - enabled: network.enabled, - }), - } - } -} - -#[derive(Clone, Debug, Serialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum GuardianReviewedAction { - NativeToolCall {}, - Shell { - sandbox_permissions: SandboxPermissions, - additional_permissions: Option, - }, - UnifiedExec { - sandbox_permissions: SandboxPermissions, - additional_permissions: Option, - tty: bool, - }, - WriteStdin { - tty: bool, - }, - Execve { - source: GuardianCommandSource, - additional_permissions: Option, - }, - ApplyPatch {}, - NetworkAccess { - protocol: NetworkApprovalProtocol, - port: u16, - }, - McpToolCall { - server: String, - tool_name: String, - connector_id: Option, - connector_name: Option, - tool_title: Option, - }, - RequestPermissions {}, -} - -#[derive(Clone, Serialize)] -pub struct GuardianReviewEventParams { - pub guardian_context_mode: Option<&'static str>, - pub thread_id: String, - pub turn_id: String, - pub review_id: String, - pub target_item_id: Option, - pub approval_request_source: GuardianApprovalRequestSource, - pub reviewed_action: GuardianReviewedAction, - pub reviewed_action_truncated: bool, - pub decision: GuardianReviewDecision, - pub terminal_status: GuardianReviewTerminalStatus, - pub failure_reason: Option, - pub attempt_count: i64, - pub risk_level: Option, - pub user_authorization: Option, - pub outcome: Option, - pub guardian_thread_id: Option, - pub guardian_session_kind: Option, - pub guardian_model: Option, - pub guardian_reasoning_effort: Option, - pub guardian_default_review_model_id: Option, - pub guardian_catalog_contains_auto_review: Option, - pub guardian_review_model_overridden: Option, - pub guardian_review_model_override: Option, - pub guardian_model_provider_id: Option, - pub had_prior_review_context: Option, - /// Configured overall review budget in milliseconds; zero means unlimited. - pub review_timeout_ms: u64, - pub tool_call_count: Option, - pub time_to_first_token_ms: Option, - pub completion_latency_ms: Option, - pub started_at: u64, - pub completed_at: Option, - pub input_tokens: Option, - pub cached_input_tokens: Option, - pub cache_write_input_tokens: Option, - pub output_tokens: Option, - pub reasoning_output_tokens: Option, - pub total_tokens: Option, -} - -pub struct GuardianReviewTrackContext { - thread_id: String, - turn_id: String, - review_id: String, - target_item_id: Option, - approval_request_source: GuardianApprovalRequestSource, - reviewed_action: GuardianReviewedAction, - review_timeout_ms: u64, - pub started_at_ms: u64, -} - -impl GuardianReviewTrackContext { - pub fn new( - thread_id: String, - turn_id: String, - review_id: String, - target_item_id: Option, - approval_request_source: GuardianApprovalRequestSource, - reviewed_action: GuardianReviewedAction, - review_timeout_ms: u64, - ) -> Self { - Self { - thread_id, - turn_id, - review_id, - target_item_id, - approval_request_source, - reviewed_action, - review_timeout_ms, - started_at_ms: now_unix_millis(), - } - } - - pub(crate) fn event_params( - &self, - result: GuardianReviewAnalyticsResult, - completed_at_ms: u64, - elapsed: Duration, - ) -> GuardianReviewEventParams { - let completion_latency_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX); - GuardianReviewEventParams { - guardian_context_mode: result.guardian_context_mode, - thread_id: self.thread_id.clone(), - turn_id: self.turn_id.clone(), - review_id: self.review_id.clone(), - target_item_id: self.target_item_id.clone(), - approval_request_source: self.approval_request_source, - reviewed_action: self.reviewed_action.clone(), - reviewed_action_truncated: result.reviewed_action_truncated, - decision: result.decision, - terminal_status: result.terminal_status, - failure_reason: result.failure_reason, - attempt_count: result.attempt_count, - risk_level: result.risk_level, - user_authorization: result.user_authorization, - outcome: result.outcome, - guardian_thread_id: result.guardian_thread_id, - guardian_session_kind: result.guardian_session_kind, - guardian_model: result.guardian_model, - guardian_reasoning_effort: result.guardian_reasoning_effort, - guardian_default_review_model_id: result.guardian_default_review_model_id, - guardian_catalog_contains_auto_review: result.guardian_catalog_contains_auto_review, - guardian_review_model_overridden: result.guardian_review_model_overridden, - guardian_review_model_override: result.guardian_review_model_override, - guardian_model_provider_id: result.guardian_model_provider_id, - had_prior_review_context: result.had_prior_review_context, - review_timeout_ms: self.review_timeout_ms, - // TODO(rhan-oai): plumb nested Guardian review session tool-call counts. - tool_call_count: None, - time_to_first_token_ms: result.time_to_first_token_ms, - completion_latency_ms: Some(completion_latency_ms), - started_at: self.started_at_ms / 1_000, - completed_at: Some(completed_at_ms / 1_000), - input_tokens: result.token_usage.as_ref().map(|usage| usage.input_tokens), - cached_input_tokens: result - .token_usage - .as_ref() - .map(|usage| usage.cached_input_tokens), - cache_write_input_tokens: result - .token_usage - .as_ref() - .map(|usage| usage.cache_write_input_tokens), - output_tokens: result.token_usage.as_ref().map(|usage| usage.output_tokens), - reasoning_output_tokens: result - .token_usage - .as_ref() - .map(|usage| usage.reasoning_output_tokens), - total_tokens: result.token_usage.as_ref().map(|usage| usage.total_tokens), - } - } -} - -#[derive(Debug)] -pub struct GuardianReviewAnalyticsResult { - pub guardian_context_mode: Option<&'static str>, - pub decision: GuardianReviewDecision, - pub terminal_status: GuardianReviewTerminalStatus, - pub failure_reason: Option, - pub attempt_count: i64, - /// An allow was validated against changed parent/root authorization or review context. - /// Retained across attempts; this does not identify the cause of a later cancellation. - pub context_changed: bool, - pub risk_level: Option, - pub user_authorization: Option, - pub outcome: Option, - pub guardian_thread_id: Option, - pub guardian_session_kind: Option, - pub guardian_model: Option, - pub guardian_reasoning_effort: Option, - pub guardian_default_review_model_id: Option, - pub guardian_catalog_contains_auto_review: Option, - pub guardian_review_model_overridden: Option, - pub guardian_review_model_override: Option, - pub guardian_model_provider_id: Option, - pub had_prior_review_context: Option, - pub reviewed_action_truncated: bool, - pub token_usage: Option, - pub time_to_first_token_ms: Option, -} - -impl GuardianReviewAnalyticsResult { - pub fn without_session() -> Self { - Self { - guardian_context_mode: None, - decision: GuardianReviewDecision::Denied, - terminal_status: GuardianReviewTerminalStatus::FailedClosed, - failure_reason: None, - attempt_count: 1, - context_changed: false, - risk_level: None, - user_authorization: None, - outcome: None, - guardian_thread_id: None, - guardian_session_kind: None, - guardian_model: None, - guardian_reasoning_effort: None, - guardian_default_review_model_id: None, - guardian_catalog_contains_auto_review: None, - guardian_review_model_overridden: None, - guardian_review_model_override: None, - guardian_model_provider_id: None, - had_prior_review_context: None, - reviewed_action_truncated: false, - token_usage: None, - time_to_first_token_ms: None, - } - } - - pub fn from_session(params: GuardianReviewSessionAnalyticsParams) -> Self { - Self { - guardian_thread_id: Some(params.guardian_thread_id), - guardian_session_kind: Some(params.guardian_session_kind), - guardian_model: Some(params.guardian_model), - guardian_reasoning_effort: params.guardian_reasoning_effort, - guardian_default_review_model_id: Some(params.guardian_default_review_model_id), - guardian_catalog_contains_auto_review: Some( - params.guardian_catalog_contains_auto_review, - ), - guardian_review_model_overridden: Some(params.guardian_review_model_overridden), - guardian_review_model_override: params.guardian_review_model_override, - guardian_model_provider_id: Some(params.guardian_model_provider_id), - had_prior_review_context: Some(params.had_prior_review_context), - ..Self::without_session() - } - } -} - -pub struct GuardianReviewSessionAnalyticsParams { - pub guardian_thread_id: String, - pub guardian_session_kind: GuardianReviewSessionKind, - pub guardian_model: String, - pub guardian_reasoning_effort: Option, - pub guardian_default_review_model_id: String, - pub guardian_catalog_contains_auto_review: bool, - pub guardian_review_model_overridden: bool, - pub guardian_review_model_override: Option, - pub guardian_model_provider_id: String, - pub had_prior_review_context: bool, -} - -#[derive(Serialize)] -pub(crate) struct GuardianReviewEventPayload { - pub(crate) session_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - #[serde(flatten)] - pub(crate) guardian_review: GuardianReviewEventParams, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum FinalApprovalOutcome { - Unknown, - NotNeeded, - ConfigAllowed, - PolicyForbidden, - GuardianApproved, - GuardianDenied, - GuardianAborted, - UserApproved, - UserApprovedForSession, - UserDenied, - UserAborted, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ToolItemTerminalStatus { - Completed, - Failed, - Rejected, - Interrupted, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ToolItemFailureKind { - ToolError, - ApprovalDenied, - ApprovalAborted, - SandboxDenied, - PolicyForbidden, -} - -/// The immediate initiator of the tool request associated with an analytics event. -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ToolEventType { - /// The event item ID matches a tool call emitted in a sampled model response. - ModelToolCall, - /// The event item ID matches a child call dispatched by an executing tool. - InnerToolCall, -} - -#[derive(Serialize)] -pub(crate) struct CodexToolItemEventBase { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) turn_id: String, - pub(crate) root_turn_id: Option, - /// App-server ThreadItem.id. For tool-originated items this generally - /// corresponds to the originating core call_id. - pub(crate) item_id: String, - pub(crate) cell_id: Option, - pub(crate) parent_call_id: Option, - pub(crate) originating_response_id: Option, - pub(crate) subsequent_response_id: Option, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) tool_name: String, - /// Absent when origin evidence is unavailable or conflicting at emission time. - pub(crate) tool_event_type: Option, - pub(crate) started_at_ms: u64, - pub(crate) completed_at_ms: u64, - // Observed item lifecycle duration. This may undercount end-to-end execution - // for tools where app-server only sees part of the upstream flow. - pub(crate) duration_ms: Option, - pub(crate) execution_duration_ms: Option, - pub(crate) review_count: u64, - pub(crate) guardian_review_count: u64, - pub(crate) user_review_count: u64, - pub(crate) final_approval_outcome: FinalApprovalOutcome, - pub(crate) terminal_status: ToolItemTerminalStatus, - pub(crate) failure_kind: Option, - pub(crate) requested_additional_permissions: bool, - pub(crate) requested_network_access: bool, -} - -#[derive(Serialize)] -pub(crate) struct CodexCuaToolCallStartedEventParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) turn_id: String, - pub(crate) root_turn_id: Option, - pub(crate) item_id: String, - pub(crate) cell_id: Option, - pub(crate) parent_call_id: Option, - pub(crate) originating_response_id: Option, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) tool_event_type: Option, - pub(crate) started_at_ms: u64, - pub(crate) mcp_server_name: String, - pub(crate) mcp_tool_name: String, - pub(crate) plugin_id: Option, - pub(crate) connector_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexCuaToolCallStartedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexCuaToolCallStartedEventParams, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ReviewSubjectKind { - CommandExecution, - WriteStdin, - FileChange, - McpToolCall, - Permissions, - NetworkAccess, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum Reviewer { - Guardian, - User, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ReviewTrigger { - Initial, - SandboxDenial, - NetworkPolicyDenial, - ExecveIntercept, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ReviewStatus { - Approved, - Denied, - Aborted, - TimedOut, -} - -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ReviewResolution { - None, - SessionApproval, - ExecPolicyAmendment, - NetworkPolicyAmendment, -} - -#[derive(Serialize)] -pub(crate) struct CodexReviewEventParams { - pub(crate) thread_id: String, - pub(crate) turn_id: String, - pub(crate) item_id: Option, - pub(crate) review_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) subject_kind: ReviewSubjectKind, - pub(crate) subject_name: String, - pub(crate) reviewer: Reviewer, - pub(crate) trigger: ReviewTrigger, - pub(crate) status: ReviewStatus, - pub(crate) resolution: ReviewResolution, - pub(crate) started_at_ms: u64, - pub(crate) completed_at_ms: u64, - pub(crate) duration_ms: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexReviewEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexReviewEventParams, -} -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum WebSearchActionKind { - Search, - OpenPage, - FindInPage, - Other, -} - -#[derive(Serialize)] -pub(crate) struct CodexCommandExecutionEventParams { - pub(crate) sandbox_backend: Option, - pub(crate) model_slug: Option, - pub(crate) reasoning_effort: Option, - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) plugin_id: Option, - pub(crate) script_path: Option, - pub(crate) command_execution_source: CommandExecutionSource, - pub(crate) exit_code: Option, - pub(crate) command_total_action_count: u64, - pub(crate) command_read_action_count: u64, - pub(crate) command_list_files_action_count: u64, - pub(crate) command_search_action_count: u64, - pub(crate) command_unknown_action_count: u64, -} - -#[derive(Serialize)] -pub(crate) struct CodexCommandExecutionEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexCommandExecutionEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginMeasurementEventParams { - pub(crate) thread_id: String, - pub(crate) turn_id: String, - pub(crate) item_id: String, - pub(crate) originator: String, - pub(crate) model_slug: Option, - pub(crate) reasoning_effort: Option, - pub(crate) plugin_id: String, - pub(crate) execution_id: String, - pub(crate) operation: String, - pub(crate) measurement_name: String, - pub(crate) number_value: f64, - pub(crate) dimensions: Option>, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginMeasurementEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexPluginMeasurementEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexFileChangeEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) file_change_count: u64, - pub(crate) file_add_count: u64, - pub(crate) file_update_count: u64, - pub(crate) file_delete_count: u64, - pub(crate) file_move_count: u64, -} - -#[derive(Serialize)] -pub(crate) struct CodexFileChangeEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexFileChangeEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexMcpToolCallEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) mcp_server_name: String, - pub(crate) mcp_tool_name: String, - pub(crate) mcp_error_present: bool, - pub(crate) plugin_id: Option, - pub(crate) connector_id: Option, - pub(crate) voice_session_id: Option, - pub(crate) elicitation_type: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexMcpToolCallEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexMcpToolCallEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexDynamicToolCallEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) dynamic_tool_name: String, - pub(crate) success: Option, - pub(crate) output_content_item_count: Option, - pub(crate) output_text_item_count: Option, - pub(crate) output_image_item_count: Option, - pub(crate) output_audio_item_count: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexDynamicToolCallEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexDynamicToolCallEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexControlToolCallEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) success: bool, -} - -#[derive(Serialize)] -pub(crate) struct CodexControlToolCallEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexControlToolCallEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexCollabAgentToolCallEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) sender_thread_id: String, - pub(crate) receiver_thread_count: u64, - pub(crate) receiver_thread_ids: Option>, - pub(crate) requested_model: Option, - pub(crate) requested_reasoning_effort: Option, - pub(crate) agent_state_count: Option, - pub(crate) completed_agent_count: Option, - pub(crate) failed_agent_count: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexCollabAgentToolCallEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexCollabAgentToolCallEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexWebSearchEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) web_search_action: Option, - pub(crate) query_present: bool, - pub(crate) query_count: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexWebSearchEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexWebSearchEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexImageGenerationEventParams { - #[serde(flatten)] - pub(crate) base: CodexToolItemEventBase, - pub(crate) revised_prompt_present: bool, - pub(crate) saved_path_present: bool, - pub(crate) transparent_background: Option, - pub(crate) imagegen_request_id: Option, - pub(crate) generation_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexImageGenerationEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexImageGenerationEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexAppMetadata { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) connector_id: Option, - pub(crate) thread_id: Option, - pub(crate) turn_id: Option, - pub(crate) app_name: Option, - pub(crate) product_client_id: Option, - pub(crate) invoke_type: Option, - pub(crate) model_slug: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexAppMentionedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexAppMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexAppUsedMetadata { - #[serde(flatten)] - pub(crate) app: CodexAppMetadata, - pub(crate) voice_session_id: Option, - pub(crate) elicitation_type: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexAppUsedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexAppUsedMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexHookRunMetadata { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - pub(crate) thread_id: Option, - pub(crate) turn_id: Option, - pub(crate) product_client_id: Option, - pub(crate) model_slug: Option, - pub(crate) hook_name: Option, - pub(crate) hook_source: Option<&'static str>, - pub(crate) handler_type: Option, - pub(crate) execution_mode: Option, - pub(crate) status: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexHookRunEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexHookRunMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexCompactionEventParams { - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) turn_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) trigger: CompactionTrigger, - pub(crate) reason: CompactionReason, - pub(crate) implementation: CompactionImplementation, - pub(crate) phase: CompactionPhase, - pub(crate) strategy: CompactionStrategy, - pub(crate) status: CompactionStatus, - pub(crate) voice_session_id: Option, - pub(crate) codex_error_kind: Option, - pub(crate) codex_error_http_status_code: Option, - pub(crate) usage_limit_window_minutes: Option, - pub(crate) active_context_tokens_before: i64, - pub(crate) active_context_tokens_after: i64, - pub(crate) retained_image_count: Option, - pub(crate) compaction_summary_tokens: Option, - pub(crate) cached_input_tokens: Option, - pub(crate) cache_write_input_tokens: Option, - pub(crate) started_at: u64, - pub(crate) completed_at: u64, - pub(crate) duration_ms: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexCompactionEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexCompactionEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexGoalEventParams { - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) turn_id: Option, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) goal_id: String, - pub(crate) event_kind: GoalEventKind, - pub(crate) goal_status: codex_state::ThreadGoalStatus, - pub(crate) has_token_budget: bool, - pub(crate) cumulative_tokens_accounted: Option, - pub(crate) cumulative_time_accounted_seconds: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexGoalEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexGoalEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexTurnEventParams { - #[serde(flatten)] - pub(crate) critical_path: crate::turn_critical_path::CriticalPathEventParams, - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) turn_id: String, - /// First received active plugin inventory. Null is unknown; [] is observed empty. - pub(crate) active_plugin_ids_at_turn_start: Option>, - pub(crate) voice_session_id: Option, - pub(crate) root_turn_id: Option, - pub(crate) turn_trigger: Option, - pub(crate) codex_turn_source: Option, - // TODO(rhan-oai): Populate once queued/default submission type is plumbed from - // the turn/start callsites instead of always being reported as None. - pub(crate) submission_type: Option, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) ephemeral: bool, - pub(crate) thread_source: Option, - pub(crate) initialization_mode: ThreadInitializationMode, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) model: Option, - pub(crate) model_provider: String, - pub(crate) sandbox_policy: Option<&'static str>, - pub(crate) reasoning_effort: Option, - pub(crate) reasoning_summary: Option, - pub(crate) service_tier: String, - pub(crate) approval_policy: String, - pub(crate) approvals_reviewer: String, - pub(crate) guardian_v2_enabled: bool, - pub(crate) multi_agent_version: codex_protocol::protocol::MultiAgentVersion, - pub(crate) sandbox_network_access: bool, - pub(crate) collaboration_mode: Option<&'static str>, - pub(crate) personality: Option, - pub(crate) workspace_kind: Option, - pub(crate) num_input_images: usize, - pub(crate) image_preparations: Vec, - pub(crate) is_first_turn: bool, - pub(crate) status: Option, - /// Client wall-clock time for the first non-startup turn/interrupt request - /// that later received a successful response. - pub(crate) explicit_client_interrupt_requested_at_ms: Option, - pub(crate) turn_error: Option, - pub(crate) codex_error_kind: Option, - pub(crate) codex_error_http_status_code: Option, - /// The server-selected window responsible for a usage limit, when known. - pub(crate) usage_limit_window_minutes: Option, - pub(crate) steer_count: Option, - pub(crate) total_tool_call_count: Option, - pub(crate) shell_command_count: Option, - pub(crate) file_change_count: Option, - pub(crate) mcp_tool_call_count: Option, - pub(crate) dynamic_tool_call_count: Option, - pub(crate) subagent_tool_call_count: Option, - pub(crate) web_search_count: Option, - pub(crate) image_generation_count: Option, - pub(crate) input_tokens: Option, - pub(crate) cached_input_tokens: Option, - pub(crate) cache_write_input_tokens: Option, - pub(crate) output_tokens: Option, - pub(crate) reasoning_output_tokens: Option, - pub(crate) total_tokens: Option, - pub(crate) before_first_sampling_ms: u64, - pub(crate) sampling_ms: u64, - pub(crate) compaction_ms: u64, - pub(crate) between_sampling_overhead_ms: u64, - pub(crate) tool_blocking_ms: u64, - pub(crate) after_last_sampling_ms: u64, - pub(crate) sampling_request_count: u32, - pub(crate) sampling_retry_count: u32, - pub(crate) tools_change_count: u32, - pub(crate) duration_ms: Option, - pub(crate) started_at: Option, - pub(crate) completed_at: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexTurnEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexTurnEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexTurnSteerEventParams { - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) expected_turn_id: Option, - pub(crate) accepted_turn_id: Option, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) num_input_images: usize, - pub(crate) result: TurnSteerResult, - pub(crate) rejection_reason: Option, - pub(crate) created_at: u64, -} - -#[derive(Serialize)] -pub(crate) struct CodexTurnSteerEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexTurnSteerEventParams, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginMetadata { - pub(crate) plugin_id: Option, - pub(crate) remote_plugin_id: Option, - pub(crate) plugin_name: Option, - pub(crate) marketplace_name: Option, - pub(crate) has_skills: Option, - pub(crate) mcp_server_count: Option, - pub(crate) connector_ids: Option>, - pub(crate) product_client_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginUsedMetadata { - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) turn_trigger: Option, - #[serde(flatten)] - pub(crate) plugin: CodexPluginMetadata, - pub(crate) mcp_server_names: Option>, - pub(crate) thread_id: Option, - pub(crate) turn_id: Option, - pub(crate) model_slug: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginInstallRequestedPluginMetadata { - pub(crate) plugin_id: String, - pub(crate) remote_plugin_id: Option, - pub(crate) plugin_name: String, - pub(crate) connector_ids: Vec, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginInstallRequestedMetadata { - pub(crate) suggestion_id: String, - pub(crate) plugins: Vec, - pub(crate) source: crate::facts::PluginInstallRequestSource, - pub(crate) thread_id: String, - pub(crate) turn_id: String, - pub(crate) model_slug: String, - pub(crate) product_client_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginInstallRequestedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexPluginInstallRequestedMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexPluginMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginInstallFailedMetadata { - #[serde(flatten)] - pub(crate) plugin: CodexPluginMetadata, - pub(crate) source: crate::facts::PluginInstallSource, - pub(crate) error_type: String, - pub(crate) sub_error_type: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginInstallFailedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexPluginInstallFailedMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexOnboardingExternalAgentImportCompleteMetadata { - pub(crate) import_id: String, - pub(crate) source: String, - pub(crate) provider_id: String, - #[serde(rename = "type")] - pub(crate) item_type: String, - pub(crate) success_count: usize, - pub(crate) failed_count: usize, - pub(crate) product_client_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexOnboardingExternalAgentImportCompleteEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexOnboardingExternalAgentImportCompleteMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexOnboardingExternalAgentImportFailureMetadata { - pub(crate) import_id: String, - pub(crate) source: String, - pub(crate) provider_id: String, - #[serde(rename = "type")] - pub(crate) item_type: String, - pub(crate) failure_stage: String, - pub(crate) error_type: String, - pub(crate) sub_error_type: Option, - pub(crate) product_client_id: Option, -} - -#[derive(Serialize)] -pub(crate) struct CodexOnboardingExternalAgentImportFailureEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexOnboardingExternalAgentImportFailureMetadata, -} - -#[derive(Serialize)] -pub(crate) struct CodexPluginUsedEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: CodexPluginUsedMetadata, -} - -pub(crate) fn plugin_state_event_type(state: PluginState) -> &'static str { - match state { - PluginState::Installed => "codex_plugin_installed", - PluginState::Uninstalled => "codex_plugin_uninstalled", - PluginState::Enabled => "codex_plugin_enabled", - PluginState::Disabled => "codex_plugin_disabled", - } -} - -pub(crate) fn codex_app_metadata( - tracking: &TrackEventsContext, - app: AppInvocation, -) -> CodexAppMetadata { - let turn = tracking.turn_metadata.as_deref(); - CodexAppMetadata { - turn_trigger: turn.and_then(TurnAnalyticsMetadata::turn_trigger), - connector_id: app.connector_id, - thread_id: Some(tracking.thread_id.clone()), - turn_id: Some(tracking.turn_id.clone()), - app_name: app.app_name, - product_client_id: Some(tracking.product_client_id.clone()), - invoke_type: app.invocation_type, - model_slug: Some(tracking.model_slug.clone()), - } -} - -pub(crate) fn codex_plugin_metadata(plugin: PluginTelemetryMetadata) -> CodexPluginMetadata { - codex_plugin_metadata_with_product_client_id(plugin, originator().value) -} - -fn codex_plugin_metadata_with_product_client_id( - plugin: PluginTelemetryMetadata, - product_client_id: String, -) -> CodexPluginMetadata { - let PluginTelemetryMetadata { - plugin_id, - remote_plugin_id, - capability_summary, - } = plugin; - CodexPluginMetadata { - plugin_id: plugin_id.as_ref().map(PluginId::as_key), - remote_plugin_id, - plugin_name: plugin_id - .as_ref() - .map(|plugin_id| plugin_id.plugin_name.clone()), - marketplace_name: plugin_id.map(|plugin_id| plugin_id.marketplace_name), - has_skills: capability_summary - .as_ref() - .map(|summary| summary.has_skills), - mcp_server_count: capability_summary - .as_ref() - .map(|summary| summary.mcp_server_names.len()), - connector_ids: capability_summary.map(|summary| { - summary - .app_connector_ids - .into_iter() - .map(|connector_id| connector_id.0) - .collect() - }), - product_client_id: Some(product_client_id), - } -} - -pub(crate) fn codex_plugin_install_requested_metadata( - tracking: &TrackEventsContext, - request: PluginInstallRequested, -) -> CodexPluginInstallRequestedMetadata { - CodexPluginInstallRequestedMetadata { - suggestion_id: request.suggestion_id, - plugins: request - .plugins - .into_iter() - .map(|plugin| CodexPluginInstallRequestedPluginMetadata { - plugin_id: plugin.plugin_id, - remote_plugin_id: plugin.remote_plugin_id, - plugin_name: plugin.plugin_name, - connector_ids: plugin.connector_ids, - }) - .collect(), - source: request.source, - thread_id: tracking.thread_id.clone(), - turn_id: tracking.turn_id.clone(), - model_slug: tracking.model_slug.clone(), - product_client_id: Some(originator().value), - } -} - -pub(crate) fn codex_compaction_event_params( - input: CodexCompactionEvent, - session_id: String, - app_server_client: CodexAppServerClientMetadata, - runtime: CodexRuntimeMetadata, - thread_source: Option, - subagent_source: Option, - parent_thread_id: Option, -) -> CodexCompactionEventParams { - CodexCompactionEventParams { - thread_id: input.thread_id, - session_id, - turn_id: input.turn_id, - app_server_client, - runtime, - thread_source, - subagent_source, - parent_thread_id, - trigger: input.trigger, - reason: input.reason, - implementation: input.implementation, - phase: input.phase, - strategy: input.strategy, - status: input.status, - voice_session_id: None, - codex_error_kind: input.codex_error_kind, - codex_error_http_status_code: input.codex_error_http_status_code, - usage_limit_window_minutes: input.usage_limit_window_minutes, - active_context_tokens_before: input.active_context_tokens_before, - active_context_tokens_after: input.active_context_tokens_after, - retained_image_count: input.retained_image_count, - compaction_summary_tokens: input.compaction_summary_tokens, - cached_input_tokens: input.cached_input_tokens, - cache_write_input_tokens: input.cache_write_input_tokens, - started_at: input.started_at, - completed_at: input.completed_at, - duration_ms: input.duration_ms, - } -} - -pub(crate) fn codex_goal_event_params( - input: CodexGoalEvent, - session_id: String, - app_server_client: CodexAppServerClientMetadata, - runtime: CodexRuntimeMetadata, - thread_source: Option, - subagent_source: Option, - parent_thread_id: Option, -) -> CodexGoalEventParams { - CodexGoalEventParams { - thread_id: input.thread_id, - session_id, - turn_id: input.turn_id, - app_server_client, - runtime, - thread_source, - subagent_source, - parent_thread_id, - goal_id: input.goal_id, - event_kind: input.event_kind, - goal_status: input.goal_status, - has_token_budget: input.has_token_budget, - cumulative_tokens_accounted: input.cumulative_tokens_accounted, - cumulative_time_accounted_seconds: input.cumulative_time_accounted_seconds, - } -} - -pub(crate) fn codex_plugin_used_metadata( - tracking: &TrackEventsContext, - plugin: PluginTelemetryMetadata, -) -> CodexPluginUsedMetadata { - let mcp_server_names = plugin - .capability_summary - .as_ref() - .map(|summary| summary.mcp_server_names.clone()); - let turn = tracking.turn_metadata.as_deref(); - CodexPluginUsedMetadata { - turn_trigger: turn.and_then(TurnAnalyticsMetadata::turn_trigger), - plugin: codex_plugin_metadata_with_product_client_id( - plugin, - tracking.product_client_id.clone(), - ), - mcp_server_names, - thread_id: Some(tracking.thread_id.clone()), - turn_id: Some(tracking.turn_id.clone()), - model_slug: Some(tracking.model_slug.clone()), - } -} - -pub(crate) fn codex_hook_run_metadata( - tracking: &TrackEventsContext, - hook: HookRunFact, -) -> CodexHookRunMetadata { - let turn = tracking.turn_metadata.as_deref(); - CodexHookRunMetadata { - turn_trigger: turn.and_then(TurnAnalyticsMetadata::turn_trigger), - thread_id: Some(tracking.thread_id.clone()), - turn_id: Some(tracking.turn_id.clone()), - product_client_id: Some(tracking.product_client_id.clone()), - model_slug: Some(tracking.model_slug.clone()), - hook_name: Some(analytics_hook_event_name(hook.event_name).to_owned()), - hook_source: Some(analytics_hook_source(hook.hook_source)), - handler_type: Some(hook.handler_type), - execution_mode: Some(hook.execution_mode), - status: Some(analytics_hook_status(hook.status)), - } -} - -fn analytics_hook_event_name(event_name: HookEventName) -> &'static str { - match event_name { - HookEventName::PreToolUse => "PreToolUse", - HookEventName::PermissionRequest => "PermissionRequest", - HookEventName::PostToolUse => "PostToolUse", - HookEventName::PreCompact => "PreCompact", - HookEventName::PostCompact => "PostCompact", - HookEventName::PreModelRequest => "PreModelRequest", - HookEventName::PostModelRequest => "PostModelRequest", - HookEventName::SessionStart => "SessionStart", - HookEventName::SessionEnd => "SessionEnd", - HookEventName::UserPromptSubmit => "UserPromptSubmit", - HookEventName::SubagentStart => "SubagentStart", - HookEventName::SubagentStop => "SubagentStop", - HookEventName::Stop => "Stop", - HookEventName::Interrupt => "Interrupt", - } -} - -fn analytics_hook_source(source: HookSource) -> &'static str { - match source { - HookSource::System => "system", - HookSource::User => "user", - HookSource::Project => "project", - HookSource::Mdm => "mdm", - HookSource::SessionFlags => "session_flags", - HookSource::Plugin => "plugin", - HookSource::CloudRequirements => "cloud_requirements", - HookSource::CloudManagedConfig => "cloud_managed_config", - HookSource::LegacyManagedConfigFile => "legacy_managed_config_file", - HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm", - HookSource::Unknown => "unknown", - } -} - -pub(crate) fn current_runtime_metadata() -> CodexRuntimeMetadata { - // Runtime metadata is stable; avoid launching OS discovery subprocesses per event. - static OS_INFO: LazyLock = LazyLock::new(os_info::get); - let os_info = &*OS_INFO; - CodexRuntimeMetadata { - codex_rs_version: env!("CARGO_PKG_VERSION").to_string(), - runtime_os: std::env::consts::OS.to_string(), - runtime_os_version: os_info.version().to_string(), - runtime_arch: std::env::consts::ARCH.to_string(), - } -} - -pub(crate) fn subagent_thread_started_event_request( - input: SubAgentThreadStartedInput, -) -> ThreadInitializedEvent { - let event_params = ThreadInitializedEventParams { - thread_id: input.thread_id, - session_id: input.session_id, - app_server_client: CodexAppServerClientMetadata { - product_client_id: input.product_client_id, - client_name: input.client_name, - client_version: input.client_version, - rpc_transport: AppServerRpcTransport::InProcess, - experimental_api_enabled: None, - }, - runtime: current_runtime_metadata(), - model: input.model, - ephemeral: input.ephemeral, - is_worktree: None, - thread_source: input.thread_source, - initialization_mode: input.initialization_mode, - subagent_source: Some(subagent_source_name(&input.subagent_source)), - parent_thread_id: input.parent_thread_id, - forked_from_thread_id: input.forked_from_thread_id, - created_at: input.created_at, - }; - ThreadInitializedEvent { - event_type: "codex_thread_initialized", - event_params, - } -} - -pub(crate) fn subagent_source_name(subagent_source: &SubAgentSource) -> String { - subagent_source.kind().to_string() -} - -fn analytics_hook_status(status: HookRunStatus) -> HookRunStatus { - match status { - // Running is unexpected here and normalized defensively. - HookRunStatus::Running => HookRunStatus::Failed, - other => other, - } -} diff --git a/codex-rs/analytics/src/facts.rs b/codex-rs/analytics/src/facts.rs deleted file mode 100644 index 68d055c8..00000000 --- a/codex-rs/analytics/src/facts.rs +++ /dev/null @@ -1,776 +0,0 @@ -use crate::events::AppServerRpcTransport; -use crate::events::CodexRuntimeMetadata; -use crate::events::GuardianReviewEventParams; -use crate::guardian_v2::GuardianV2Event; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ServerResponse; -use codex_plugin::PluginTelemetryMetadata; -use codex_protocol::config_types::ApprovalsReviewer; -use codex_protocol::config_types::ModeKind; -use codex_protocol::config_types::Personality; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::ServiceTier; -use codex_protocol::error::CodexErr; -pub use codex_protocol::error::CodexErrKind; -use codex_protocol::error::CodexErrorDetails; -use codex_protocol::models::PermissionProfile; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::HookEventName; -use codex_protocol::protocol::HookExecutionMode; -use codex_protocol::protocol::HookHandlerType; -use codex_protocol::protocol::HookRunStatus; -use codex_protocol::protocol::HookSource; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SkillScope; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadSource; -use codex_protocol::protocol::TokenUsage; -use codex_protocol::request_permissions::RequestPermissionsResponse; -use codex_utils_path_uri::PathUri; -use serde::Serialize; -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::sync::Arc; - -#[derive(Clone)] -pub struct TrackEventsContext { - pub model_slug: String, - pub thread_id: String, - pub turn_id: String, - pub product_client_id: String, - pub turn_metadata: Option>, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum ArtifactOperationLifecycle { - Started, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ArtifactOperation { - pub item_id: String, - pub lifecycle: ArtifactOperationLifecycle, - pub occurred_at_ms: u64, - pub plugin_id: String, - pub script_path: String, - pub skill: String, - pub artifact_type: String, - pub operation_kind: String, - pub expected_output_count: u32, - pub output_format: String, - pub execution_backend: String, -} - -#[derive(Clone)] -pub enum CodeModeToolCallFact { - CellStarted { - thread_id: String, - turn_id: String, - call_id: String, - cell_id: String, - }, - ChildStarted { - thread_id: String, - turn_id: String, - call_id: String, - cell_id: String, - }, - CellClosed { - thread_id: String, - turn_id: String, - cell_id: String, - }, - SamplingResponseCompleted { - thread_id: String, - turn_id: String, - response_id: String, - tool_call_ids: Vec, - }, - Completed { - thread_id: String, - turn_id: String, - turn_metadata: Arc, - call_id: String, - cell_id: Option, - tool_name: String, - started_at_ms: u64, - completed_at_ms: u64, - status: CodeModeToolCallStatus, - }, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CodeModeToolCallStatus { - Completed, - Failed, - Interrupted, -} - -#[derive(Clone)] -pub struct ControlToolCallFact { - pub thread_id: String, - pub turn_id: String, - pub turn_metadata: Arc, - pub call_id: String, - pub cell_id: Option, - pub tool_name: String, - pub started_at_ms: u64, - pub completed_at_ms: u64, - pub status: ControlToolCallStatus, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ControlToolCallStatus { - Completed, - Failed, - Rejected, - Interrupted, -} - -pub fn build_track_events_context( - model_slug: String, - thread_id: String, - turn_id: String, - product_client_id: String, - turn_metadata: Option>, -) -> TrackEventsContext { - TrackEventsContext { - model_slug, - thread_id, - turn_id, - product_client_id, - turn_metadata, - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum ImageDetailSetting { - High, - Original, -} - -/// Measurements for one successfully decoded image at the point where Codex prepares it for -/// durable conversation history. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct ImagePreparationMetadata { - /// Set for images embedded in message content. - pub message_role: Option, - /// Set to the originating call ID for tool-output images. This joins to the `item_id` on - /// existing tool events for tool type and provenance. - pub item_id: Option, - pub effective_detail: ImageDetailSetting, - pub source_width: u32, - pub source_height: u32, - pub prepared_width: u32, - pub prepared_height: u32, -} - -#[derive(Clone)] -pub struct ImagePreparationFact { - pub turn_id: String, - pub metadata: ImagePreparationMetadata, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum TurnSubmissionType { - Default, - Queued, -} - -#[derive(Clone)] -pub struct TurnResolvedConfigFact { - pub turn_id: String, - pub thread_id: String, - pub turn_metadata: Arc, - /// Observed active plugin inventory. None is unknown; Some([]) is observed empty. - pub active_plugin_ids_at_turn_start: Option>, - pub num_input_images: usize, - pub submission_type: Option, - pub ephemeral: bool, - pub session_source: SessionSource, - pub model: String, - pub model_provider: String, - pub permission_profile: PermissionProfile, - pub permission_profile_cwd: PathBuf, - pub reasoning_effort: Option, - pub reasoning_summary: Option, - pub service_tier: Option, - pub approval_policy: AskForApproval, - pub approvals_reviewer: ApprovalsReviewer, - pub guardian_v2_enabled: bool, - pub multi_agent_version: codex_protocol::protocol::MultiAgentVersion, - pub sandbox_network_access: bool, - pub collaboration_mode: ModeKind, - pub personality: Option, - pub workspace_kind: Option, - pub is_first_turn: bool, -} - -/// A live, read-only view of a turn's analytics metadata. -/// -/// Implementations must return `None` for unknown or ambiguous roots. The reducer -/// reads this when constructing each event because steering can invalidate a root -/// after the turn's configuration has been resolved. -pub trait TurnAnalyticsMetadata: Send + Sync { - fn root_turn_id(&self) -> Option; - /// The caller-provided trigger recorded when this turn started. - fn turn_trigger(&self) -> Option; - /// The effective Responses source at event emission, including accepted steers. - fn codex_turn_source(&self) -> Option; -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum ThreadInitializationMode { - New, - Forked, - Resumed, -} - -#[derive(Clone)] -pub struct TurnTokenUsageFact { - pub turn_id: String, - pub thread_id: String, - pub token_usage: TokenUsage, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct TurnProfile { - pub critical_path: crate::TurnCriticalPath, - pub before_first_sampling_ms: u64, - pub sampling_ms: u64, - pub compaction_ms: u64, - pub between_sampling_overhead_ms: u64, - pub tool_blocking_ms: u64, - pub after_last_sampling_ms: u64, - pub sampling_request_count: u32, - pub sampling_retry_count: u32, - pub tools_change_count: u32, -} - -#[derive(Clone)] -pub struct TurnProfileFact { - pub turn_id: String, - pub profile: TurnProfile, -} - -#[derive(Clone)] -pub struct TurnCodexErrorFact { - pub(crate) turn_id: String, - pub(crate) thread_id: String, - pub(crate) error: TurnCodexError, -} - -impl TurnCodexErrorFact { - pub fn from_codex_err(thread_id: String, turn_id: String, error: &CodexErr) -> Self { - Self { - turn_id, - thread_id, - error: TurnCodexError::from_codex_err(error), - } - } -} - -#[derive(Clone)] -pub(crate) struct TurnCodexError { - pub(crate) kind: CodexErrKind, - pub(crate) http_status_code: Option, - pub(crate) usage_limit_window_minutes: Option, -} - -impl TurnCodexError { - fn from_codex_err(error: &CodexErr) -> Self { - Self { - kind: error.into(), - http_status_code: error.http_status_code_value(), - usage_limit_window_minutes: match error.details() { - CodexErrorDetails::UsageLimitReached(error) => error.limit_window_minutes, - _ => None, - }, - } - } -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum TurnStatus { - Completed, - Failed, - Interrupted, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum TurnSteerResult { - Accepted, - Rejected, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum TurnSteerRejectionReason { - NoActiveTurn, - ExpectedTurnMismatch, - NonSteerableReview, - NonSteerableCompact, - EmptyInput, - InputTooLarge, -} - -#[derive(Clone)] -pub struct CodexTurnSteerEvent { - pub expected_turn_id: Option, - pub accepted_turn_id: Option, - pub num_input_images: usize, - pub result: TurnSteerResult, - pub rejection_reason: Option, - pub created_at: u64, -} - -#[derive(Clone, Copy, Debug)] -pub enum AnalyticsJsonRpcError { - TurnSteer(TurnSteerRequestError), - Input(InputError), -} - -#[derive(Clone, Copy, Debug)] -pub enum TurnSteerRequestError { - NoActiveTurn, - ExpectedTurnMismatch, - NonSteerableReview, - NonSteerableCompact, -} - -#[derive(Clone, Copy, Debug)] -pub enum InputError { - Empty, - TooLarge, -} - -impl From for TurnSteerRejectionReason { - fn from(error: TurnSteerRequestError) -> Self { - match error { - TurnSteerRequestError::NoActiveTurn => Self::NoActiveTurn, - TurnSteerRequestError::ExpectedTurnMismatch => Self::ExpectedTurnMismatch, - TurnSteerRequestError::NonSteerableReview => Self::NonSteerableReview, - TurnSteerRequestError::NonSteerableCompact => Self::NonSteerableCompact, - } - } -} - -impl From for TurnSteerRejectionReason { - fn from(error: InputError) -> Self { - match error { - InputError::Empty => Self::EmptyInput, - InputError::TooLarge => Self::InputTooLarge, - } - } -} - -#[derive(Clone, Debug)] -pub struct SkillInvocation { - pub skill_name: String, - pub location: SkillInvocationLocation, - pub plugin_id: Option, - pub remote_plugin_id: Option, - pub invocation_type: InvocationType, -} - -#[derive(Clone, Debug)] -pub enum SkillInvocationLocation { - Host { - path: PathUri, - scope: SkillScope, - }, - Resource { - id: String, - skill_id: Option, - scope: Option, - }, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum InvocationType { - Explicit, - Implicit, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum ElicitationType { - /// Authentication or account linking blocked the original attempt, as reported - /// by trusted connector auth-failure metadata. Both are treated the same when - /// identifying elicitation-only usage. This does not imply that an - /// authentication prompt was shown or completed. - AuthOrLink, - Approval, -} - -pub struct AppInvocation { - pub connector_id: Option, - pub app_name: Option, - pub invocation_type: Option, -} - -/// A known classification, queued before the corresponding item completion. -/// Ordinary calls do not send this fact; their emitted classification stays null. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct McpToolCallElicitation { - pub thread_id: String, - pub turn_id: String, - pub item_id: String, - pub elicitation_type: ElicitationType, -} - -#[derive(Clone)] -pub struct SubAgentThreadStartedInput { - pub session_id: String, - pub thread_id: String, - pub parent_thread_id: Option, - pub forked_from_thread_id: Option, - pub product_client_id: String, - pub client_name: Option, - pub client_version: Option, - pub model: String, - pub ephemeral: bool, - pub thread_source: Option, - pub subagent_source: SubAgentSource, - pub initialization_mode: ThreadInitializationMode, - pub created_at: u64, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionTrigger { - Manual, - Auto, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionReason { - UserRequested, - ContextLimit, - ModelDownshift, - CompHashChanged, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionImplementation { - Responses, - ResponsesCompactionV2, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionPhase { - StandaloneTurn, - PreTurn, - MidTurn, - PostTurn, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionStrategy { - Memento, - PrefixCompaction, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum CompactionStatus { - Completed, - Failed, - Interrupted, -} - -#[derive(Clone)] -pub struct CodexCompactionEvent { - pub thread_id: String, - pub turn_id: String, - pub trigger: CompactionTrigger, - pub reason: CompactionReason, - pub implementation: CompactionImplementation, - pub phase: CompactionPhase, - pub strategy: CompactionStrategy, - pub status: CompactionStatus, - pub codex_error_kind: Option, - pub codex_error_http_status_code: Option, - pub usage_limit_window_minutes: Option, - pub active_context_tokens_before: i64, - pub active_context_tokens_after: i64, - pub retained_image_count: Option, - pub compaction_summary_tokens: Option, - pub cached_input_tokens: Option, - pub cache_write_input_tokens: Option, - pub started_at: u64, - pub completed_at: u64, - pub duration_ms: Option, -} - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum GoalEventKind { - Created, - UsageAccounted, - StatusChanged, - Cleared, -} - -#[derive(Clone)] -pub struct CodexGoalEvent { - pub thread_id: String, - pub turn_id: Option, - pub goal_id: String, - pub event_kind: GoalEventKind, - pub goal_status: codex_state::ThreadGoalStatus, - pub has_token_budget: bool, - pub cumulative_tokens_accounted: Option, - pub cumulative_time_accounted_seconds: Option, -} - -#[allow(dead_code)] -pub(crate) enum AnalyticsFact { - Initialize { - connection_id: u64, - params: InitializeParams, - product_client_id: String, - runtime: CodexRuntimeMetadata, - rpc_transport: AppServerRpcTransport, - }, - ClientRequest { - connection_id: u64, - request_id: RequestId, - request: Box, - }, - ExplicitClientInterruptRequest { - connection_id: u64, - request_id: RequestId, - turn_id: String, - requested_at_ms: u64, - }, - ClientResponse { - connection_id: u64, - request_id: RequestId, - response: Box, - thread_originator: Option, - }, - ErrorResponse { - connection_id: u64, - request_id: RequestId, - error: JSONRPCErrorError, - error_type: Option, - }, - ServerRequest { - connection_id: u64, - request: Box, - }, - ServerResponse { - completed_at_ms: u64, - response: Box, - }, - EffectivePermissionsApprovalResponse { - completed_at_ms: u64, - request_id: RequestId, - response: Box, - }, - ServerRequestAborted { - completed_at_ms: u64, - request_id: RequestId, - }, - RealtimeHandoffRequested { - thread_id: String, - }, - RealtimeSessionStarted { - thread_id: String, - realtime_session_id: Option, - started_at: u64, - }, - RealtimeSessionUpdated { - thread_id: String, - realtime_session_id: String, - }, - RealtimeSessionClosed { - thread_id: String, - closed_at: u64, - }, - Notification(Box), - // Facts that do not naturally exist on the app-server protocol surface, or - // would require non-trivial protocol reshaping on this branch. - Custom(CustomAnalyticsFact), -} - -pub(crate) enum CustomAnalyticsFact { - ArtifactOperation(ArtifactOperationInput), - CodeModeToolCall(CodeModeToolCallFact), - ControlToolCall(ControlToolCallFact), - SubAgentThreadStarted(SubAgentThreadStartedInput), - Compaction(Box), - Goal(Box), - ThreadHintStatus(Box), - GuardianReview(Box), - GuardianV2(Box), - TurnResolvedConfig(Box), - TurnTokenUsage(Box), - TurnProfile(Box), - TurnCodexError(Box), - ImagePreparation(Box), - SkillInvoked(SkillInvokedInput), - AppMentioned(AppMentionedInput), - AppUsed(AppUsedInput), - McpToolCallElicitation(McpToolCallElicitation), - HookRun(HookRunInput), - PluginUsed(PluginUsedInput), - PluginInstallRequested(PluginInstallRequestedInput), - PluginStateChanged(PluginStateChangedInput), - PluginInstallFailed(PluginInstallFailedInput), - PluginMeasurements(PluginMeasurementsInput), - ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedInput), - ExternalAgentConfigImportFailure(ExternalAgentConfigImportFailureInput), -} - -pub(crate) struct ArtifactOperationInput { - pub tracking: TrackEventsContext, - pub operation: ArtifactOperation, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct PluginMeasurementRow { - pub measurement_name: String, - pub number_value: f64, - pub dimensions: BTreeMap, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct PluginMeasurementsInput { - pub thread_id: String, - pub turn_id: String, - pub item_id: String, - pub originator: String, - pub model_slug: Option, - pub reasoning_effort: Option, - pub plugin_id: String, - pub execution_id: String, - pub operation: String, - pub rows: Vec, -} - -pub(crate) struct SkillInvokedInput { - pub tracking: TrackEventsContext, - pub invocations: Vec, -} - -pub(crate) struct AppMentionedInput { - pub tracking: TrackEventsContext, - pub mentions: Vec, -} - -pub(crate) struct AppUsedInput { - pub tracking: TrackEventsContext, - pub app: AppInvocation, - pub elicitation_type: Option, -} - -pub(crate) struct HookRunInput { - pub tracking: TrackEventsContext, - pub hook: HookRunFact, -} - -pub struct HookRunFact { - pub event_name: HookEventName, - pub hook_source: HookSource, - pub handler_type: HookHandlerType, - pub execution_mode: HookExecutionMode, - pub status: HookRunStatus, -} - -pub(crate) struct PluginUsedInput { - pub tracking: TrackEventsContext, - pub plugin: PluginTelemetryMetadata, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum PluginInstallRequestSource { - EndpointRecommendation, - LegacyDiscovery, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginInstallRequested { - pub suggestion_id: String, - pub plugins: Vec, - pub source: PluginInstallRequestSource, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginInstallRequestedPlugin { - pub plugin_id: String, - pub remote_plugin_id: Option, - pub plugin_name: String, - pub connector_ids: Vec, -} - -pub(crate) struct PluginInstallRequestedInput { - pub tracking: TrackEventsContext, - pub request: PluginInstallRequested, -} - -pub(crate) struct PluginStateChangedInput { - pub plugin: PluginTelemetryMetadata, - pub state: PluginState, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum PluginInstallSource { - Manual, - ExternalAgentMigration, -} - -pub(crate) struct PluginInstallFailedInput { - pub plugin: PluginTelemetryMetadata, - pub source: PluginInstallSource, - pub error_type: String, - pub sub_error_type: Option, -} - -pub struct ExternalAgentConfigImportCompletedInput { - pub import_id: String, - pub source: String, - pub provider_id: String, - pub item_type: String, - pub success_count: usize, - pub failed_count: usize, -} - -pub struct ExternalAgentConfigImportFailureInput { - pub import_id: String, - pub source: String, - pub provider_id: String, - pub item_type: String, - pub failure_stage: String, - pub error_type: String, - pub sub_error_type: Option, -} - -#[derive(Clone, Copy)] -pub(crate) enum PluginState { - Installed, - Uninstalled, - Enabled, - Disabled, -} diff --git a/codex-rs/analytics/src/guardian_v2.rs b/codex-rs/analytics/src/guardian_v2.rs deleted file mode 100644 index 0929d9aa..00000000 --- a/codex-rs/analytics/src/guardian_v2.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Guardian V2 classifier and fast-decision facts, enriched by the existing reducer. -//! Payloads contain attribution and bounded outcomes, never prompts or tool arguments. - -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexRuntimeMetadata; -use codex_protocol::protocol::ThreadSource; -use serde::Serialize; - -#[derive(Serialize)] -pub struct GuardianV2Event { - pub thread_id: String, - pub turn_id: String, - pub item_id: Option, - pub model: Option, - pub occurred_at_ms: u64, - #[serde(flatten)] - pub kind: GuardianV2EventKind, -} - -#[derive(Serialize)] -#[serde(untagged)] -pub enum GuardianV2EventKind { - Classification { - guardian_context_mode: &'static str, - outcome: &'static str, - risk_level: Option<&'static str>, - duration_ms: u64, - }, - FastDecision { - decision: &'static str, - }, -} - -#[derive(Serialize)] -pub(crate) struct GuardianV2EventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: GuardianV2EventParams, -} - -#[derive(Serialize)] -pub(crate) struct GuardianV2EventParams { - pub(crate) session_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - #[serde(flatten)] - pub(crate) guardian_v2: GuardianV2Event, -} diff --git a/codex-rs/analytics/src/lib.rs b/codex-rs/analytics/src/lib.rs deleted file mode 100644 index 0828bb3a..00000000 --- a/codex-rs/analytics/src/lib.rs +++ /dev/null @@ -1,124 +0,0 @@ -// aKode: event upload is disabled (see `client.rs`); the upstream sending -// machinery is kept only until it is pruned, so dead-code warnings are expected. -#![allow(dead_code)] -mod accepted_lines; -#[cfg(debug_assertions)] -mod analytics_capture; -mod client; -mod events; -mod facts; -mod guardian_v2; -mod product_attribution; -mod reducer; -mod thread_hint; -mod turn_critical_path; - -use std::time::SystemTime; -use std::time::UNIX_EPOCH; - -pub use accepted_lines::fingerprint_hash; -pub use client::AnalyticsEventsClient; -pub use events::AppServerRpcTransport; -pub use events::GuardianAdditionalPermissions; -pub use events::GuardianApprovalRequestSource; -pub use events::GuardianReviewAnalyticsResult; -pub use events::GuardianReviewDecision; -pub use events::GuardianReviewEventParams; -pub use events::GuardianReviewFailureReason; -pub use events::GuardianReviewSessionAnalyticsParams; -pub use events::GuardianReviewSessionKind; -pub use events::GuardianReviewTerminalStatus; -pub use events::GuardianReviewTrackContext; -pub use events::GuardianReviewedAction; -pub use facts::AnalyticsJsonRpcError; -pub use facts::AppInvocation; -pub use facts::ArtifactOperation; -pub use facts::ArtifactOperationLifecycle; -pub use facts::CodeModeToolCallFact; -pub use facts::CodeModeToolCallStatus; -pub use facts::CodexCompactionEvent; -pub use facts::CodexErrKind; -pub use facts::CodexGoalEvent; -pub use facts::CodexTurnSteerEvent; -pub use facts::CompactionImplementation; -pub use facts::CompactionPhase; -pub use facts::CompactionReason; -pub use facts::CompactionStatus; -pub use facts::CompactionStrategy; -pub use facts::CompactionTrigger; -pub use facts::ControlToolCallFact; -pub use facts::ControlToolCallStatus; -pub use facts::ElicitationType; -pub use facts::ExternalAgentConfigImportCompletedInput; -pub use facts::ExternalAgentConfigImportFailureInput; -pub use facts::GoalEventKind; -pub use facts::HookRunFact; -pub use facts::ImageDetailSetting; -pub use facts::ImagePreparationFact; -pub use facts::ImagePreparationMetadata; -pub use facts::InputError; -pub use facts::InvocationType; -pub use facts::McpToolCallElicitation; -pub use facts::PluginInstallRequestSource; -pub use facts::PluginInstallRequested; -pub use facts::PluginInstallRequestedPlugin; -pub use facts::PluginInstallSource; -pub use facts::PluginMeasurementRow; -pub use facts::PluginMeasurementsInput; -pub use facts::SkillInvocation; -pub use facts::SkillInvocationLocation; -pub use facts::SubAgentThreadStartedInput; -pub use facts::ThreadInitializationMode; -pub use facts::TrackEventsContext; -pub use facts::TurnAnalyticsMetadata; -pub use facts::TurnCodexErrorFact; -pub use facts::TurnProfile; -pub use facts::TurnProfileFact; -pub use facts::TurnResolvedConfigFact; -pub use facts::TurnStatus; -pub use facts::TurnSteerRejectionReason; -pub use facts::TurnSteerRequestError; -pub use facts::TurnSteerResult; -pub use facts::TurnTokenUsageFact; -pub use facts::build_track_events_context; -pub use guardian_v2::GuardianV2Event; -pub use guardian_v2::GuardianV2EventKind; -pub use product_attribution::ThreadProductUpdate; -pub use thread_hint::ThreadHintStatus; -pub use thread_hint::ThreadHintStatusEvent; -pub use turn_critical_path::TurnCriticalPath; -pub use turn_critical_path::TurnCriticalPathDurations; - -#[cfg(test)] -mod tests; - -pub fn now_unix_seconds() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs() -} - -pub fn now_unix_millis() -> u64 { - u64::try_from( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis(), - ) - .unwrap_or(u64::MAX) -} - -pub(crate) fn serialize_enum_as_string(value: &T) -> Option { - serde_json::to_value(value) - .ok() - .and_then(|value| value.as_str().map(str::to_string)) -} - -pub(crate) fn usize_to_u64(value: usize) -> u64 { - u64::try_from(value).unwrap_or(u64::MAX) -} - -pub(crate) fn option_i64_to_u64(value: Option) -> Option { - value.and_then(|value| u64::try_from(value).ok()) -} diff --git a/codex-rs/analytics/src/product_attribution.rs b/codex-rs/analytics/src/product_attribution.rs deleted file mode 100644 index da5958f3..00000000 --- a/codex-rs/analytics/src/product_attribution.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Keep per-thread product attribution separate from the shared analytics identity. - -use crate::events::TrackEventRequest; -use std::collections::HashMap; -use std::collections::VecDeque; - -pub(crate) const MAX_THREAD_PRODUCTS: usize = 4096; -const MAX_PRODUCT_BATCHES: usize = 16; - -/// An explicit change to a thread's product attribution, independent of authentication. -#[derive(Clone)] -pub enum ThreadProductUpdate { - Set(String), - Clear, -} - -#[derive(Default)] -pub(crate) struct ThreadProducts { - pub(crate) products: HashMap, - pub(crate) registered_threads: VecDeque, -} - -impl ThreadProducts { - pub(crate) fn get(&self, thread_id: &str) -> Option<&str> { - self.products.get(thread_id).map(String::as_str) - } - - pub(crate) fn register(&mut self, thread_id: String, product: Option) { - self.registered_threads.retain(|id| id != &thread_id); - self.products.remove(&thread_id); - let Some(product) = product else { - return; - }; - // Attribution is best-effort. Evicted threads have no product header. - if self.products.len() >= MAX_THREAD_PRODUCTS - && let Some(oldest) = self.registered_threads.pop_front() - { - self.products.remove(&oldest); - } - self.registered_threads.push_back(thread_id.clone()); - self.products.insert(thread_id, product); - } -} - -/// Preserve order within each product, with a bounded number of concurrent streams. -/// Too many products drops only attribution, preserving the original event order. -pub(crate) fn product_event_batches( - events: Vec, - thread_products: &ThreadProducts, -) -> Vec<(Option<&str>, Vec)> { - let products: std::collections::HashSet<_> = events - .iter() - .map(|event| event_thread_id(event).and_then(|id| thread_products.get(id))) - .collect(); - if products.len() > MAX_PRODUCT_BATCHES { - return vec![(None, events)]; - } - let mut batches: Vec<(Option<&str>, Vec)> = Vec::new(); - for event in events { - let product = event_thread_id(&event).and_then(|thread_id| thread_products.get(thread_id)); - if let Some((_, batch)) = batches.iter_mut().find(|(sku, _)| *sku == product) { - batch.push(event); - } else { - batches.push((product, vec![event])); - } - } - batches -} - -fn event_thread_id(event: &TrackEventRequest) -> Option<&str> { - match event { - TrackEventRequest::SkillInvocation(event) => event.event_params.thread_id.as_deref(), - TrackEventRequest::ThreadInitialized(event) => Some(&event.event_params.thread_id), - TrackEventRequest::ThreadArchive(event) => Some(&event.event_params.thread_id), - TrackEventRequest::GuardianReview(event) => { - Some(&event.event_params.guardian_review.thread_id) - } - TrackEventRequest::GuardianV2(event) => Some(&event.event_params.guardian_v2.thread_id), - TrackEventRequest::AppMentioned(event) => event.event_params.thread_id.as_deref(), - TrackEventRequest::AppUsed(event) => event.event_params.app.thread_id.as_deref(), - TrackEventRequest::HookRun(event) => event.event_params.thread_id.as_deref(), - TrackEventRequest::Compaction(event) => Some(&event.event_params.thread_id), - TrackEventRequest::Goal(event) => Some(&event.event_params.thread_id), - TrackEventRequest::ThreadHintStatus(event) => Some(&event.event_params.thread_id), - TrackEventRequest::TurnEvent(event) => Some(&event.event_params.thread_id), - TrackEventRequest::TurnSteer(event) => Some(&event.event_params.thread_id), - TrackEventRequest::ArtifactOperation(event) => Some(&event.event_params.thread_id), - TrackEventRequest::CommandExecution(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::PluginMeasurement(event) => Some(&event.event_params.thread_id), - TrackEventRequest::FileChange(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::CuaToolCallStarted(event) => Some(&event.event_params.thread_id), - TrackEventRequest::McpToolCall(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::DynamicToolCall(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::ControlToolCall(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::CollabAgentToolCall(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::WebSearch(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::ImageGeneration(event) => Some(&event.event_params.base.thread_id), - TrackEventRequest::AcceptedLineFingerprints(event) => Some(&event.event_params.thread_id), - TrackEventRequest::ReviewEvent(event) => Some(&event.event_params.thread_id), - TrackEventRequest::PluginUsed(event) => event.event_params.thread_id.as_deref(), - TrackEventRequest::PluginInstallRequested(event) => Some(&event.event_params.thread_id), - TrackEventRequest::PluginInstalled(_) - | TrackEventRequest::PluginUninstalled(_) - | TrackEventRequest::PluginEnabled(_) - | TrackEventRequest::PluginDisabled(_) - | TrackEventRequest::PluginInstallFailed(_) - | TrackEventRequest::ExternalAgentConfigImportCompleted(_) - | TrackEventRequest::ExternalAgentConfigImportFailure(_) => None, - } -} diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs deleted file mode 100644 index e9a59cac..00000000 --- a/codex-rs/analytics/src/reducer.rs +++ /dev/null @@ -1,4414 +0,0 @@ -use crate::accepted_lines::AcceptedLineFingerprintEventInput; -use crate::accepted_lines::accepted_line_counts_from_unified_diff; -use crate::accepted_lines::accepted_line_fingerprint_event_requests; -use crate::accepted_lines::accepted_line_repo_hash_for_cwd; -use crate::events::AppServerRpcTransport; -use crate::events::CodexAppMentionedEventRequest; -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexAppUsedEventRequest; -use crate::events::CodexAppUsedMetadata; -use crate::events::CodexCollabAgentToolCallEventParams; -use crate::events::CodexCollabAgentToolCallEventRequest; -use crate::events::CodexCommandExecutionEventParams; -use crate::events::CodexCommandExecutionEventRequest; -use crate::events::CodexCompactionEventRequest; -use crate::events::CodexControlToolCallEventParams; -use crate::events::CodexControlToolCallEventRequest; -use crate::events::CodexCuaToolCallStartedEventParams; -use crate::events::CodexCuaToolCallStartedEventRequest; -use crate::events::CodexDynamicToolCallEventParams; -use crate::events::CodexDynamicToolCallEventRequest; -use crate::events::CodexFileChangeEventParams; -use crate::events::CodexFileChangeEventRequest; -use crate::events::CodexGoalEventRequest; -use crate::events::CodexHookRunEventRequest; -use crate::events::CodexImageGenerationEventParams; -use crate::events::CodexImageGenerationEventRequest; -use crate::events::CodexMcpToolCallEventParams; -use crate::events::CodexMcpToolCallEventRequest; -use crate::events::CodexOnboardingExternalAgentImportCompleteEventRequest; -use crate::events::CodexOnboardingExternalAgentImportCompleteMetadata; -use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest; -use crate::events::CodexOnboardingExternalAgentImportFailureMetadata; -use crate::events::CodexPluginEventRequest; -use crate::events::CodexPluginInstallFailedEventRequest; -use crate::events::CodexPluginInstallFailedMetadata; -use crate::events::CodexPluginInstallRequestedEventRequest; -use crate::events::CodexPluginMeasurementEventParams; -use crate::events::CodexPluginMeasurementEventRequest; -use crate::events::CodexPluginUsedEventRequest; -use crate::events::CodexReviewEventParams; -use crate::events::CodexReviewEventRequest; -use crate::events::CodexRuntimeMetadata; -use crate::events::CodexToolItemEventBase; -use crate::events::CodexTurnEventParams; -use crate::events::CodexTurnEventRequest; -use crate::events::CodexTurnSteerEventParams; -use crate::events::CodexTurnSteerEventRequest; -use crate::events::CodexWebSearchEventParams; -use crate::events::CodexWebSearchEventRequest; -use crate::events::FinalApprovalOutcome; -use crate::events::GuardianReviewEventParams; -use crate::events::GuardianReviewEventPayload; -use crate::events::GuardianReviewEventRequest; -use crate::events::ReviewResolution; -use crate::events::ReviewStatus; -use crate::events::ReviewSubjectKind; -use crate::events::ReviewTrigger; -use crate::events::Reviewer; -use crate::events::SkillInvocationEventParams; -use crate::events::SkillInvocationEventRequest; -use crate::events::ThreadArchiveAction; -use crate::events::ThreadArchiveEvent; -use crate::events::ThreadArchiveEventParams; -use crate::events::ThreadInitializedEvent; -use crate::events::ThreadInitializedEventParams; -use crate::events::ToolEventType; -use crate::events::ToolItemFailureKind; -use crate::events::ToolItemTerminalStatus; -use crate::events::TrackEventRequest; -use crate::events::WebSearchActionKind; -use crate::events::codex_app_metadata; -use crate::events::codex_artifact_operation_event_request; -use crate::events::codex_compaction_event_params; -use crate::events::codex_goal_event_params; -use crate::events::codex_hook_run_metadata; -use crate::events::codex_plugin_install_requested_metadata; -use crate::events::codex_plugin_metadata; -use crate::events::codex_plugin_used_metadata; -use crate::events::plugin_state_event_type; -use crate::events::subagent_source_name; -use crate::events::subagent_thread_started_event_request; -use crate::facts::AnalyticsFact; -use crate::facts::AnalyticsJsonRpcError; -use crate::facts::AppMentionedInput; -use crate::facts::AppUsedInput; -use crate::facts::ArtifactOperationInput; -use crate::facts::CodeModeToolCallFact; -use crate::facts::CodeModeToolCallStatus; -use crate::facts::CodexCompactionEvent; -use crate::facts::CodexGoalEvent; -use crate::facts::ControlToolCallFact; -use crate::facts::ControlToolCallStatus; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::ExternalAgentConfigImportCompletedInput; -use crate::facts::ExternalAgentConfigImportFailureInput; -use crate::facts::HookRunInput; -use crate::facts::ImagePreparationFact; -use crate::facts::ImagePreparationMetadata; -use crate::facts::InvocationType; -use crate::facts::McpToolCallElicitation; -use crate::facts::PluginInstallFailedInput; -use crate::facts::PluginInstallRequestedInput; -use crate::facts::PluginMeasurementRow; -use crate::facts::PluginMeasurementsInput; -use crate::facts::PluginState; -use crate::facts::PluginStateChangedInput; -use crate::facts::PluginUsedInput; -use crate::facts::SkillInvocationLocation; -use crate::facts::SkillInvokedInput; -use crate::facts::SubAgentThreadStartedInput; -use crate::facts::ThreadInitializationMode; -use crate::facts::TurnAnalyticsMetadata; -use crate::facts::TurnCodexError; -use crate::facts::TurnCodexErrorFact; -use crate::facts::TurnProfile; -use crate::facts::TurnProfileFact; -use crate::facts::TurnResolvedConfigFact; -use crate::facts::TurnStatus; -use crate::facts::TurnSteerRejectionReason; -use crate::facts::TurnSteerResult; -use crate::facts::TurnTokenUsageFact; -use crate::guardian_v2::GuardianV2EventKind; -use crate::guardian_v2::GuardianV2EventParams; -use crate::guardian_v2::GuardianV2EventRequest; -use crate::now_unix_millis; -use crate::now_unix_seconds; -use crate::option_i64_to_u64; -use crate::serialize_enum_as_string; -use crate::usize_to_u64; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponse; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::CollabAgentStatus; -use codex_app_server_protocol::CollabAgentTool; -use codex_app_server_protocol::CollabAgentToolCallStatus; -use codex_app_server_protocol::CommandAction; -use codex_app_server_protocol::CommandExecutionApprovalDecision; -use codex_app_server_protocol::CommandExecutionApprovalKind; -use codex_app_server_protocol::CommandExecutionSource; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::DynamicToolCallOutputContentItem; -use codex_app_server_protocol::DynamicToolCallStatus; -use codex_app_server_protocol::FileChangeApprovalDecision; -use codex_app_server_protocol::GuardianApprovalReviewAction; -use codex_app_server_protocol::GuardianApprovalReviewStatus; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::McpToolCallStatus; -use codex_app_server_protocol::NetworkPolicyRuleAction; -use codex_app_server_protocol::PatchApplyStatus; -use codex_app_server_protocol::PatchChangeKind; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::RequestPermissionProfile; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ServerResponse; -use codex_app_server_protocol::SubAgentActivityKind; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::TurnSteerResponse; -use codex_app_server_protocol::UserInput; -use codex_app_server_protocol::WebSearchAction; -use codex_git_utils::SanitizedGitUrl; -use codex_git_utils::get_git_origin_url; -use codex_git_utils::get_git_repo_root; -use codex_login::default_client::originator; -use codex_protocol::config_types::ModeKind; -use codex_protocol::config_types::Personality; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::items::ModelInvocationContext; -use codex_protocol::items::is_safe_plugin_relative_path; -use codex_protocol::mcp::is_node_repl_backed_connector; -use codex_protocol::models::PermissionProfile; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SkillScope; -use codex_protocol::protocol::ThreadSource; -use codex_protocol::protocol::TokenUsage; -use codex_protocol::request_permissions::PermissionGrantScope as CorePermissionGrantScope; -use codex_protocol::request_permissions::RequestPermissionsResponse as CoreRequestPermissionsResponse; -use codex_utils_path_uri::PathUri; -use sha1::Digest; -use std::collections::HashMap; -use std::collections::HashSet; -use std::collections::VecDeque; -use std::path::Path; -use std::path::PathBuf; -use std::sync::Arc; -const MAX_TOOL_RESPONSE_ENTRIES: usize = 256; -const MAX_RECENT_VOICE_SESSION_WINDOWS: usize = 16; - -pub(crate) const MAX_PLUGIN_MEASUREMENTS_PER_BATCH: usize = 100; -const MAX_PLUGIN_MEASUREMENT_DIMENSIONS: usize = 8; -const MAX_PLUGIN_MEASUREMENT_IDENTIFIER_BYTES: usize = 64; - -pub(crate) fn valid_plugin_measurement_identifier(value: &str) -> bool { - let mut characters = value.chars(); - matches!(characters.next(), Some('a'..='z')) - && value.len() <= MAX_PLUGIN_MEASUREMENT_IDENTIFIER_BYTES - && characters.all(|character| { - character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' - }) -} - -pub(crate) fn valid_plugin_measurement_row(row: &PluginMeasurementRow) -> bool { - row.number_value.is_finite() - && valid_plugin_measurement_identifier(&row.measurement_name) - && row.dimensions.len() <= MAX_PLUGIN_MEASUREMENT_DIMENSIONS - && row.dimensions.iter().all(|(name, value)| { - valid_plugin_measurement_identifier(name) && valid_plugin_measurement_identifier(value) - }) -} - -// Match the fact queue capacity: analytics must not retain an unlimited number -// of incomplete turns when lifecycle facts are dropped. -const MAX_PENDING_TURNS: usize = 256; - -#[derive(Default)] -pub(crate) struct AnalyticsReducer { - requests: HashMap<(u64, RequestId), RequestState>, - turns: HashMap, - turn_order: VecDeque, - connections: HashMap, - threads: HashMap, - tool_items_started_at_ms: HashMap)>, - tool_response_states: HashMap<(String, String), ToolResponseState>, - code_mode_cells: HashMap>, - pending_reviews: HashMap, - item_review_summaries: HashMap, - // Bounded to 256 entries, keeping linear lookups small; evict the oldest entry when full. - pending_mcp_tool_elicitations: VecDeque<(ToolItemKey, ElicitationType)>, -} - -struct ConnectionState { - app_server_client: CodexAppServerClientMetadata, - runtime: CodexRuntimeMetadata, -} - -#[derive(Default)] -struct ThreadAnalyticsState { - connection_id: Option, - metadata: Option, - originator: Option, - active_voice_session: Option, - recent_voice_sessions: VecDeque, - active_turn_id: Option, - pending_voice_handoffs: VecDeque>, -} - -#[derive(Clone)] -struct VoiceSessionWindow { - session_id: Option, - started_at: u64, - closed_at: Option, -} - -impl ThreadAnalyticsState { - fn app_server_client( - &self, - connection_state: &ConnectionState, - ) -> CodexAppServerClientMetadata { - let mut app_server_client = connection_state.app_server_client.clone(); - if let Some(originator) = self.originator.as_ref() { - app_server_client.product_client_id.clone_from(originator); - } - app_server_client - } - - fn active_voice_session_id(&self) -> Option { - self.active_voice_session - .as_ref() - .and_then(|session| session.session_id.clone()) - } - - fn voice_session_id_at(&self, timestamp: u64) -> Option { - self.active_voice_session - .iter() - .chain(self.recent_voice_sessions.iter().rev()) - .find(|session| { - session.started_at <= timestamp - && session - .closed_at - .is_none_or(|closed_at| timestamp <= closed_at) - }) - .and_then(|session| session.session_id.clone()) - } -} - -#[derive(Clone, Copy)] -struct AnalyticsDropSite<'a> { - event_name: &'static str, - thread_id: &'a str, - turn_id: Option<&'a str>, - review_id: Option<&'a str>, - item_id: Option<&'a str>, -} - -impl<'a> AnalyticsDropSite<'a> { - fn guardian(input: &'a GuardianReviewEventParams) -> Self { - Self { - event_name: "guardian", - thread_id: &input.thread_id, - turn_id: Some(&input.turn_id), - review_id: Some(&input.review_id), - item_id: None, - } - } - - fn review(input: &'a PendingReviewState) -> Self { - Self { - event_name: "review", - thread_id: &input.thread_id, - turn_id: Some(&input.turn_id), - review_id: Some(&input.review_id), - item_id: input.item_id.as_deref(), - } - } - - fn compaction(input: &'a CodexCompactionEvent) -> Self { - Self { - event_name: "compaction", - thread_id: &input.thread_id, - turn_id: Some(&input.turn_id), - review_id: None, - item_id: None, - } - } - - fn goal(input: &'a CodexGoalEvent) -> Self { - Self { - event_name: "goal", - thread_id: &input.thread_id, - turn_id: input.turn_id.as_deref(), - review_id: None, - item_id: None, - } - } - - fn tool_item( - notification: &'a codex_app_server_protocol::ItemCompletedNotification, - item_id: &'a str, - ) -> Self { - Self { - event_name: "tool item", - thread_id: ¬ification.thread_id, - turn_id: Some(¬ification.turn_id), - review_id: None, - item_id: Some(item_id), - } - } - - fn cua_tool_call_started(thread_id: &'a str, turn_id: &'a str, item_id: &'a str) -> Self { - Self { - event_name: "CUA tool call start", - thread_id, - turn_id: Some(turn_id), - review_id: None, - item_id: Some(item_id), - } - } - - fn turn_steer(thread_id: &'a str) -> Self { - Self { - event_name: "turn steer", - thread_id, - turn_id: None, - review_id: None, - item_id: None, - } - } - - fn turn(thread_id: &'a str, turn_id: &'a str) -> Self { - Self { - event_name: "turn", - thread_id, - turn_id: Some(turn_id), - review_id: None, - item_id: None, - } - } -} - -enum MissingAnalyticsContext { - ThreadConnection, - Connection { connection_id: u64 }, - ThreadMetadata, -} - -#[derive(Clone)] -struct PendingReviewState { - thread_id: String, - turn_id: String, - item_id: Option, - review_id: String, - subject_kind: ReviewSubjectKind, - subject_name: String, - trigger: ReviewTrigger, - started_at_ms: u64, - requested_additional_permissions: bool, - requested_network_access: bool, -} - -#[derive(Clone, Default)] -struct ItemReviewSummary { - review_count: u64, - guardian_review_count: u64, - user_review_count: u64, - final_approval_outcome: Option, - requested_additional_permissions: bool, - requested_network_access: bool, -} - -#[derive(Clone)] -struct ThreadMetadataState { - session_id: String, - thread_source: Option, - initialization_mode: ThreadInitializationMode, - subagent_source: Option, - parent_thread_id: Option, -} - -impl ThreadMetadataState { - fn from_thread_metadata( - session_id: String, - session_source: &SessionSource, - thread_source: Option, - parent_thread_id: Option, - initialization_mode: ThreadInitializationMode, - ) -> Self { - let subagent_source = match session_source { - SessionSource::SubAgent(subagent_source) => Some(subagent_source_name(subagent_source)), - SessionSource::Cli - | SessionSource::VSCode - | SessionSource::Exec - | SessionSource::Mcp - | SessionSource::Custom(_) - | SessionSource::Internal(_) - | SessionSource::Unknown => None, - }; - Self { - session_id, - thread_source, - initialization_mode, - subagent_source, - parent_thread_id, - } - } -} - -enum RequestState { - TurnStart(PendingTurnStartState), - TurnSteer(PendingTurnSteerState), - ExplicitClientInterrupt(PendingTurnInterruptState), -} - -struct PendingTurnStartState { - thread_id: String, - num_input_images: usize, -} - -struct PendingTurnSteerState { - thread_id: String, - expected_turn_id: String, - num_input_images: usize, - created_at: u64, -} - -struct PendingTurnInterruptState { - turn_id: String, - requested_at_ms: u64, -} - -#[derive(Clone)] -struct CompletedTurnState { - status: Option, - turn_error: Option, - completed_at: u64, - duration_ms: Option, -} - -#[derive(Default)] -struct TurnState { - connection_id: Option, - thread_id: Option, - voice_session_id: Option, - num_input_images: Option, - image_preparations: Vec, - resolved_config: Option, - started_at: Option, - token_usage: Option, - profile: Option, - completed: Option, - explicit_client_interrupt_requested_at_ms: Option, - codex_error: Option, - latest_diff: Option, - steer_count: usize, - tool_counts: TurnToolCounts, - completed_cua_tool_item_ids: HashSet, - resource_skill_invocations: HashSet, - turn_event_emitted: bool, -} - -#[derive(Clone, Hash, Eq, PartialEq)] -struct ToolItemKey { - thread_id: String, - turn_id: String, - item_id: String, -} - -#[derive(Default)] -struct ToolResponseState { - response_ids_by_call_id: HashMap, - cell_ids_by_child_call_id: HashMap, - pending_tool_events: VecDeque, -} - -struct CodeModeCellState { - parent_call_id: String, - originating_response_id: Option, - closed_in_turn_id: Option, -} - -enum ToolEventEmission { - ImmediateUnlessCorrelated, - AwaitResponse, -} - -#[derive(Default)] -struct TurnToolCounts { - total: usize, - shell_command: usize, - file_change: usize, - mcp_tool_call: usize, - dynamic_tool_call: usize, - subagent_tool_call: usize, - subagent_tool_call_ids: HashSet, - web_search: usize, - image_generation: usize, -} - -impl TurnToolCounts { - fn record(&mut self, item: &ThreadItemPayload) { - match item { - ThreadItemPayload::CommandExecution { .. } => self.shell_command += 1, - ThreadItemPayload::FileChange { .. } => self.file_change += 1, - ThreadItemPayload::McpToolCall { .. } => self.mcp_tool_call += 1, - ThreadItemPayload::DynamicToolCall { .. } => self.dynamic_tool_call += 1, - ThreadItemPayload::SubAgentActivity { - kind: SubAgentActivityKind::Completed, - .. - } => return, - ThreadItemPayload::CollabAgentToolCall { id, .. } - | ThreadItemPayload::SubAgentActivity { id, .. } => { - if !self.subagent_tool_call_ids.insert(id.clone()) { - return; - } - self.subagent_tool_call += 1; - } - ThreadItemPayload::WebSearch(_) => self.web_search += 1, - ThreadItemPayload::ImageGeneration(_) => self.image_generation += 1, - ThreadItemPayload::UserMessage { .. } - | ThreadItemPayload::HookPrompt { .. } - | ThreadItemPayload::AgentMessage { .. } - | ThreadItemPayload::FunctionCallOutput { .. } - | ThreadItemPayload::Plan { .. } - | ThreadItemPayload::Reasoning { .. } - | ThreadItemPayload::ImageView { .. } - | ThreadItemPayload::Sleep(_) - | ThreadItemPayload::EnteredReviewMode { .. } - | ThreadItemPayload::ExitedReviewMode { .. } - | ThreadItemPayload::ContextCompaction { .. } => return, - } - self.total += 1; - } -} - -impl AnalyticsReducer { - fn turn_state(&mut self, turn_id: String) -> &mut TurnState { - if !self.turns.contains_key(&turn_id) { - // Remove stale ordering entries before evicting the oldest retained turn. - // At capacity this may discard incomplete or pending background-tool analytics. - self.turn_order.retain(|id| self.turns.contains_key(id)); - if self.turns.len() >= MAX_PENDING_TURNS - && let Some(oldest) = self.turn_order.pop_front() - { - self.discard_turn(&oldest); - } - self.turn_order.push_back(turn_id.clone()); - } - self.turns.entry(turn_id).or_default() - } - - fn discard_turn(&mut self, turn_id: &str) { - self.turns.remove(turn_id); - self.tool_items_started_at_ms - .retain(|key, _| key.turn_id != turn_id); - self.tool_response_states - .retain(|(_, pending_turn_id), _| pending_turn_id != turn_id); - self.pending_reviews - .retain(|_, review| review.turn_id != turn_id); - self.item_review_summaries - .retain(|key, _| key.turn_id != turn_id); - self.pending_mcp_tool_elicitations - .retain(|(key, _)| key.turn_id != turn_id); - } - - pub(crate) async fn ingest(&mut self, input: AnalyticsFact, out: &mut Vec) { - match input { - AnalyticsFact::Initialize { - connection_id, - params, - product_client_id, - runtime, - rpc_transport, - } => { - self.ingest_initialize( - connection_id, - params, - product_client_id, - runtime, - rpc_transport, - ); - } - AnalyticsFact::ClientRequest { - connection_id, - request_id, - request, - } => { - self.ingest_request(connection_id, request_id, *request); - } - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id, - request_id, - turn_id, - requested_at_ms, - } => { - self.requests.insert( - (connection_id, request_id), - RequestState::ExplicitClientInterrupt(PendingTurnInterruptState { - turn_id, - requested_at_ms, - }), - ); - } - AnalyticsFact::ClientResponse { - connection_id, - request_id, - response, - thread_originator, - } => { - if let Some(response) = response.into_client_response(request_id) { - self.ingest_response(connection_id, response, thread_originator, out) - .await; - } - } - AnalyticsFact::ErrorResponse { - connection_id, - request_id, - error: _, - error_type, - } => { - self.ingest_error_response(connection_id, request_id, error_type, out); - } - AnalyticsFact::Notification(notification) => { - self.ingest_notification(*notification, out).await; - } - AnalyticsFact::ServerRequest { - connection_id, - request, - } => { - self.ingest_server_request(connection_id, *request); - } - AnalyticsFact::ServerResponse { - completed_at_ms, - response, - } => { - self.ingest_server_response(completed_at_ms, *response, out); - } - AnalyticsFact::EffectivePermissionsApprovalResponse { - completed_at_ms, - request_id, - response, - } => { - self.ingest_effective_permissions_approval_response( - completed_at_ms, - request_id, - *response, - out, - ); - } - AnalyticsFact::ServerRequestAborted { - completed_at_ms, - request_id, - } => { - self.ingest_server_request_aborted(completed_at_ms, request_id, out); - } - AnalyticsFact::RealtimeHandoffRequested { thread_id } => { - let thread = self.threads.entry(thread_id).or_default(); - // ThreadRealtimeStarted already attributes an active turn; only a new turn - // needs the handoff queued after the realtime session closes. - if thread.active_turn_id.is_none() { - thread - .pending_voice_handoffs - .push_back(thread.active_voice_session_id()); - } - } - AnalyticsFact::RealtimeSessionStarted { - thread_id, - realtime_session_id, - started_at, - } => { - self.start_voice_session(thread_id, realtime_session_id, started_at); - } - AnalyticsFact::RealtimeSessionUpdated { - thread_id, - realtime_session_id, - } => { - self.set_active_voice_session_id(thread_id, Some(realtime_session_id)); - } - AnalyticsFact::RealtimeSessionClosed { - thread_id, - closed_at, - } => { - self.close_voice_session(&thread_id, closed_at); - } - AnalyticsFact::Custom(input) => match input { - CustomAnalyticsFact::ArtifactOperation(input) => { - self.ingest_artifact_operation(input, out); - } - CustomAnalyticsFact::CodeModeToolCall(input) => { - self.ingest_code_mode_tool_call(input, out); - } - CustomAnalyticsFact::ControlToolCall(input) => { - self.ingest_control_tool_call(input, out); - } - CustomAnalyticsFact::SubAgentThreadStarted(input) => { - self.ingest_subagent_thread_started(input, out); - } - CustomAnalyticsFact::Compaction(input) => { - self.ingest_compaction(*input, out); - } - CustomAnalyticsFact::Goal(input) => { - self.ingest_goal(*input, out); - } - CustomAnalyticsFact::ThreadHintStatus(input) => { - if let Some((connection, thread, metadata)) = - self.thread_context_or_warn(AnalyticsDropSite { - event_name: "codex_thread_hint_status", - thread_id: &input.thread_id, - turn_id: None, - review_id: None, - item_id: None, - }) - { - out.push(TrackEventRequest::ThreadHintStatus(Box::new( - crate::thread_hint::ThreadHintStatusEventRequest { - event_type: "codex_thread_hint_status", - event_params: crate::thread_hint::ThreadHintStatusEventParams { - thread_id: input.thread_id, - session_id: metadata.session_id.clone(), - app_server_client: thread.app_server_client(connection), - runtime: connection.runtime.clone(), - thread_source: metadata.thread_source.clone(), - subagent_source: metadata.subagent_source.clone(), - parent_thread_id: metadata.parent_thread_id.clone(), - status: input.status, - occurred_at_ms: input.occurred_at_ms, - }, - }, - ))); - } - } - CustomAnalyticsFact::GuardianV2(input) => { - let event_type = match &input.kind { - GuardianV2EventKind::Classification { .. } => { - "codex_guardian_v2_classification" - } - GuardianV2EventKind::FastDecision { .. } => { - "codex_guardian_v2_fast_decision" - } - }; - if let Some((connection, thread, metadata)) = - self.thread_context_or_warn(AnalyticsDropSite { - event_name: event_type, - thread_id: &input.thread_id, - turn_id: Some(&input.turn_id), - review_id: None, - item_id: input.item_id.as_deref(), - }) - { - out.push(TrackEventRequest::GuardianV2(Box::new( - GuardianV2EventRequest { - event_type, - event_params: GuardianV2EventParams { - session_id: metadata.session_id.clone(), - app_server_client: thread.app_server_client(connection), - runtime: connection.runtime.clone(), - thread_source: metadata.thread_source.clone(), - subagent_source: metadata.subagent_source.clone(), - parent_thread_id: metadata.parent_thread_id.clone(), - guardian_v2: *input, - }, - }, - ))); - } - } - CustomAnalyticsFact::GuardianReview(input) => { - self.ingest_guardian_review(*input, out); - } - CustomAnalyticsFact::TurnResolvedConfig(input) => { - self.ingest_turn_resolved_config(*input, out).await; - } - CustomAnalyticsFact::TurnTokenUsage(input) => { - self.ingest_turn_token_usage(*input, out).await; - } - CustomAnalyticsFact::TurnProfile(input) => { - self.ingest_turn_profile(*input, out).await; - } - CustomAnalyticsFact::TurnCodexError(input) => { - self.ingest_turn_codex_error(*input); - } - CustomAnalyticsFact::ImagePreparation(input) => { - self.ingest_image_preparation(*input); - } - CustomAnalyticsFact::SkillInvoked(input) => { - self.ingest_skill_invoked(input, out).await; - } - CustomAnalyticsFact::AppMentioned(input) => { - self.ingest_app_mentioned(input, out); - } - CustomAnalyticsFact::AppUsed(input) => { - self.ingest_app_used(input, out); - } - CustomAnalyticsFact::McpToolCallElicitation(input) => { - let McpToolCallElicitation { - thread_id, - turn_id, - item_id, - elicitation_type, - } = input; - let key = ToolItemKey { - thread_id, - turn_id, - item_id, - }; - if self - .pending_mcp_tool_elicitations - .iter() - .any(|(pending, _)| pending == &key) - { - return; - } - if self.pending_mcp_tool_elicitations.len() >= MAX_TOOL_RESPONSE_ENTRIES { - self.pending_mcp_tool_elicitations.pop_front(); - tracing::warn!( - "expiring oldest MCP elicitation classification: state is full" - ); - } - self.pending_mcp_tool_elicitations - .push_back((key, elicitation_type)); - } - CustomAnalyticsFact::HookRun(input) => { - self.ingest_hook_run(input, out); - } - CustomAnalyticsFact::PluginUsed(input) => { - self.ingest_plugin_used(input, out); - } - CustomAnalyticsFact::PluginInstallRequested(input) => { - self.ingest_plugin_install_requested(input, out); - } - CustomAnalyticsFact::PluginStateChanged(input) => { - self.ingest_plugin_state_changed(input, out); - } - CustomAnalyticsFact::PluginInstallFailed(input) => { - self.ingest_plugin_install_failed(input, out); - } - CustomAnalyticsFact::PluginMeasurements(input) => { - self.ingest_plugin_measurements(input, out); - } - CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input) => { - self.ingest_external_agent_config_import_completed(input, out); - } - CustomAnalyticsFact::ExternalAgentConfigImportFailure(input) => { - self.ingest_external_agent_config_import_failure(input, out); - } - }, - } - } - - fn ingest_artifact_operation( - &mut self, - input: ArtifactOperationInput, - out: &mut Vec, - ) { - out.push(TrackEventRequest::ArtifactOperation( - codex_artifact_operation_event_request(input.tracking, input.operation), - )); - } - - fn ingest_code_mode_tool_call( - &mut self, - input: CodeModeToolCallFact, - out: &mut Vec, - ) { - let thread_id = match &input { - CodeModeToolCallFact::CellStarted { thread_id, .. } - | CodeModeToolCallFact::ChildStarted { thread_id, .. } - | CodeModeToolCallFact::CellClosed { thread_id, .. } - | CodeModeToolCallFact::SamplingResponseCompleted { thread_id, .. } - | CodeModeToolCallFact::Completed { thread_id, .. } => thread_id, - }; - let has_thread_context = self.threads.get(thread_id).is_some_and(|thread| { - thread.metadata.is_some() - && self - .thread_connection_id(thread_id) - .is_some_and(|connection_id| self.connections.contains_key(&connection_id)) - }); - if !has_thread_context { - return; - } - - match input { - CodeModeToolCallFact::CellStarted { - thread_id, - turn_id, - call_id, - cell_id, - } => { - let cells = self.code_mode_cells.entry(thread_id.clone()).or_default(); - if cells.contains_key(&cell_id) || cells.len() < MAX_TOOL_RESPONSE_ENTRIES { - let originating_response_id = self - .tool_response_states - .get(&(thread_id, turn_id)) - .and_then(|state| state.response_ids_by_call_id.get(&call_id)) - .cloned(); - cells.insert( - cell_id, - CodeModeCellState { - parent_call_id: call_id, - originating_response_id, - closed_in_turn_id: None, - }, - ); - } - } - CodeModeToolCallFact::ChildStarted { - thread_id, - turn_id, - call_id, - cell_id, - } => { - if self - .code_mode_cells - .get(&thread_id) - .is_some_and(|cells| cells.contains_key(&cell_id)) - { - let state = self - .tool_response_states - .entry((thread_id, turn_id)) - .or_default(); - if state.cell_ids_by_child_call_id.contains_key(&call_id) - || state.cell_ids_by_child_call_id.len() < MAX_TOOL_RESPONSE_ENTRIES - { - state.cell_ids_by_child_call_id.insert(call_id, cell_id); - } - } - } - CodeModeToolCallFact::CellClosed { - thread_id, - turn_id, - cell_id, - } => { - if let Some(cell) = self - .code_mode_cells - .get_mut(&thread_id) - .and_then(|cells| cells.get_mut(&cell_id)) - { - cell.closed_in_turn_id = Some(turn_id); - } - } - CodeModeToolCallFact::SamplingResponseCompleted { - thread_id, - turn_id, - response_id, - tool_call_ids, - } => { - self.ingest_sampling_response_completed( - thread_id, - turn_id, - response_id, - tool_call_ids, - out, - ); - } - CodeModeToolCallFact::Completed { - thread_id, - turn_id, - turn_metadata, - call_id, - cell_id, - tool_name, - started_at_ms, - completed_at_ms, - status, - } => { - let drop_site = AnalyticsDropSite { - event_name: "code mode tool", - thread_id: &thread_id, - turn_id: Some(&turn_id), - review_id: None, - item_id: Some(&call_id), - }; - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(drop_site) - else { - return; - }; - let terminal_status = match status { - CodeModeToolCallStatus::Completed => ToolItemTerminalStatus::Completed, - CodeModeToolCallStatus::Failed => ToolItemTerminalStatus::Failed, - CodeModeToolCallStatus::Interrupted => ToolItemTerminalStatus::Interrupted, - }; - let success = status == CodeModeToolCallStatus::Completed; - let mut base = tool_item_base( - &thread_id, - &turn_id, - call_id, - tool_name.clone(), - ToolItemOutcome { - terminal_status, - failure_kind: (status == CodeModeToolCallStatus::Failed) - .then_some(ToolItemFailureKind::ToolError), - execution_duration_ms: observed_duration_ms(started_at_ms, completed_at_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary: None, - }, - ); - base.cell_id = cell_id; - let event = TrackEventRequest::DynamicToolCall(CodexDynamicToolCallEventRequest { - event_type: "codex_dynamic_tool_call_event", - event_params: CodexDynamicToolCallEventParams { - base, - dynamic_tool_name: tool_name, - success: Some(success), - output_content_item_count: None, - output_text_item_count: None, - output_image_item_count: None, - output_audio_item_count: None, - }, - }); - let counts = &mut self.turn_state(turn_id.clone()).tool_counts; - counts.total += 1; - counts.dynamic_tool_call += 1; - self.record_tool_event( - &thread_id, - &turn_id, - Some(turn_metadata.as_ref()), - event, - ToolEventEmission::AwaitResponse, - out, - ); - } - } - } - - fn ingest_control_tool_call( - &mut self, - input: ControlToolCallFact, - out: &mut Vec, - ) { - let ControlToolCallFact { - thread_id, - turn_id, - turn_metadata, - call_id, - cell_id, - tool_name, - started_at_ms, - completed_at_ms, - status, - } = input; - let drop_site = AnalyticsDropSite { - event_name: "control tool", - thread_id: &thread_id, - turn_id: Some(&turn_id), - review_id: None, - item_id: Some(&call_id), - }; - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(drop_site) - else { - return; - }; - let mut base = tool_item_base( - &thread_id, - &turn_id, - call_id, - tool_name, - ToolItemOutcome { - terminal_status: match status { - ControlToolCallStatus::Completed => ToolItemTerminalStatus::Completed, - ControlToolCallStatus::Failed => ToolItemTerminalStatus::Failed, - ControlToolCallStatus::Rejected => ToolItemTerminalStatus::Rejected, - ControlToolCallStatus::Interrupted => ToolItemTerminalStatus::Interrupted, - }, - failure_kind: match status { - ControlToolCallStatus::Failed => Some(ToolItemFailureKind::ToolError), - ControlToolCallStatus::Rejected => Some(ToolItemFailureKind::PolicyForbidden), - ControlToolCallStatus::Completed | ControlToolCallStatus::Interrupted => None, - }, - execution_duration_ms: observed_duration_ms(started_at_ms, completed_at_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary: None, - }, - ); - base.cell_id = cell_id; - let event = TrackEventRequest::ControlToolCall(CodexControlToolCallEventRequest { - event_type: "codex_control_tool_call_event", - event_params: CodexControlToolCallEventParams { - base, - success: status == ControlToolCallStatus::Completed, - }, - }); - self.turn_state(turn_id.clone()).tool_counts.total += 1; - self.record_tool_event( - &thread_id, - &turn_id, - Some(turn_metadata.as_ref()), - event, - ToolEventEmission::AwaitResponse, - out, - ); - } - - fn ingest_sampling_response_completed( - &mut self, - thread_id: String, - turn_id: String, - response_id: String, - tool_call_ids: Vec, - out: &mut Vec, - ) { - let turn_key = (thread_id.clone(), turn_id); - let state = self.tool_response_states.entry(turn_key).or_default(); - for call_id in tool_call_ids { - if state.response_ids_by_call_id.contains_key(&call_id) - || state.response_ids_by_call_id.len() < MAX_TOOL_RESPONSE_ENTRIES - { - state - .response_ids_by_call_id - .insert(call_id, response_id.clone()); - } - } - if let Some(cells) = self.code_mode_cells.get_mut(&thread_id) { - for cell in cells.values_mut() { - if cell.originating_response_id.is_none() - && let Some(originating_response_id) = - state.response_ids_by_call_id.get(&cell.parent_call_id) - { - cell.originating_response_id = Some(originating_response_id.clone()); - } - } - } - - let mut remaining = VecDeque::new(); - while let Some(mut event) = state.pending_tool_events.pop_front() { - enrich_tool_response_event(&mut event, state, self.code_mode_cells.get(&thread_id)); - let is_subsequent_response = tool_event_base_mut(&mut event) - .and_then(|base| base.originating_response_id.as_deref()) - .is_some_and(|originating_response_id| originating_response_id != response_id); - if is_subsequent_response { - if let Some(base) = tool_event_base_mut(&mut event) { - base.subsequent_response_id = Some(response_id.clone()); - } - out.push(event); - } else { - remaining.push_back(event); - } - } - state.pending_tool_events = remaining; - } - - fn record_tool_event( - &mut self, - thread_id: &str, - turn_id: &str, - turn_metadata: Option<&dyn TurnAnalyticsMetadata>, - mut event: TrackEventRequest, - emission: ToolEventEmission, - out: &mut Vec, - ) { - let Some(base) = tool_event_base_mut(&mut event) else { - out.push(event); - return; - }; - base.root_turn_id = turn_metadata.and_then(TurnAnalyticsMetadata::root_turn_id); - base.turn_trigger = turn_metadata.and_then(TurnAnalyticsMetadata::turn_trigger); - let state = self - .tool_response_states - .entry((thread_id.to_string(), turn_id.to_string())) - .or_default(); - enrich_tool_response_event(&mut event, state, self.code_mode_cells.get(thread_id)); - let is_correlated = tool_event_base_mut(&mut event) - .is_some_and(|base| base.cell_id.is_some() || base.originating_response_id.is_some()); - if matches!(emission, ToolEventEmission::ImmediateUnlessCorrelated) && !is_correlated { - out.push(event); - return; - } - if state.pending_tool_events.len() == MAX_TOOL_RESPONSE_ENTRIES - && let Some(oldest) = state.pending_tool_events.pop_front() - { - out.push(oldest); - } - state.pending_tool_events.push_back(event); - } - - fn flush_pending_tool_events( - &mut self, - thread_id: &str, - turn_id: &str, - out: &mut Vec, - ) { - let key = (thread_id.to_string(), turn_id.to_string()); - if let Some(state) = self.tool_response_states.remove(&key) { - out.extend(state.pending_tool_events); - } - let cells = self.code_mode_cells.get_mut(thread_id); - let remove_cells = cells.is_some_and(|cells| { - cells.retain(|_, cell| cell.closed_in_turn_id.as_deref() != Some(turn_id)); - cells.is_empty() - }); - if remove_cells { - self.code_mode_cells.remove(thread_id); - } - } - - pub(crate) fn flush(&mut self, out: &mut Vec) { - for state in self.tool_response_states.values_mut() { - out.extend(state.pending_tool_events.drain(..)); - } - } - - pub(crate) fn flush_thread(&mut self, thread_id: &str, out: &mut Vec) { - for ((pending_thread_id, _), state) in &mut self.tool_response_states { - if pending_thread_id == thread_id { - out.extend(state.pending_tool_events.drain(..)); - } - } - } - - fn ingest_initialize( - &mut self, - connection_id: u64, - params: InitializeParams, - product_client_id: String, - runtime: CodexRuntimeMetadata, - rpc_transport: AppServerRpcTransport, - ) { - self.connections.insert( - connection_id, - ConnectionState { - app_server_client: CodexAppServerClientMetadata { - product_client_id, - client_name: Some(params.client_info.name), - client_version: Some(params.client_info.version), - rpc_transport, - experimental_api_enabled: params - .capabilities - .map(|capabilities| capabilities.experimental_api), - }, - runtime, - }, - ); - } - - fn ingest_subagent_thread_started( - &mut self, - input: SubAgentThreadStartedInput, - out: &mut Vec, - ) { - let parent_thread_id = input.parent_thread_id.clone(); - let parent_connection_id = parent_thread_id - .as_deref() - .and_then(|parent_thread_id| self.thread_connection_id(parent_thread_id)); - let thread_state = self.threads.entry(input.thread_id.clone()).or_default(); - thread_state - .originator - .get_or_insert_with(|| input.product_client_id.clone()); - if thread_state.metadata.is_none() - || matches!(input.initialization_mode, ThreadInitializationMode::Resumed) - { - thread_state.metadata = Some(ThreadMetadataState { - session_id: input.session_id.clone(), - thread_source: input.thread_source.clone(), - initialization_mode: input.initialization_mode, - subagent_source: Some(subagent_source_name(&input.subagent_source)), - parent_thread_id, - }); - } - if thread_state.connection_id.is_none() { - thread_state.connection_id = parent_connection_id; - } - // Guardian prewarm can register lineage before parent client metadata is set. - // Keep the existing completeness requirement for the initialization event. - if input.client_name.is_some() && input.client_version.is_some() { - out.push(TrackEventRequest::ThreadInitialized( - subagent_thread_started_event_request(input), - )); - } - } - - fn ingest_guardian_review( - &mut self, - input: GuardianReviewEventParams, - out: &mut Vec, - ) { - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(AnalyticsDropSite::guardian(&input)) - else { - return; - }; - out.push(TrackEventRequest::GuardianReview(Box::new( - GuardianReviewEventRequest { - event_type: "codex_guardian_review", - event_params: GuardianReviewEventPayload { - session_id: thread_metadata.session_id.clone(), - app_server_client: thread_state.app_server_client(connection_state), - runtime: connection_state.runtime.clone(), - guardian_review: input, - }, - }, - ))); - } - - fn ingest_request( - &mut self, - connection_id: u64, - request_id: RequestId, - request: ClientRequest, - ) { - match request { - ClientRequest::TurnStart { params, .. } => { - self.requests.insert( - (connection_id, request_id), - RequestState::TurnStart(PendingTurnStartState { - thread_id: params.thread_id, - num_input_images: num_input_images(¶ms.input), - }), - ); - } - ClientRequest::TurnSteer { params, .. } => { - self.requests.insert( - (connection_id, request_id), - RequestState::TurnSteer(PendingTurnSteerState { - thread_id: params.thread_id, - expected_turn_id: params.expected_turn_id, - num_input_images: num_input_images(¶ms.input), - created_at: now_unix_seconds(), - }), - ); - } - _ => {} - } - } - - async fn ingest_turn_resolved_config( - &mut self, - mut input: TurnResolvedConfigFact, - out: &mut Vec, - ) { - let turn_id = input.turn_id.clone(); - let thread_id = input.thread_id.clone(); - let num_input_images = input.num_input_images; - let turn_state = self.turn_state(turn_id.clone()); - turn_state.thread_id = Some(thread_id); - turn_state.num_input_images = Some(num_input_images); - // Keep the first received plugin inventory, including unknown or empty, - // while the remaining resolved config continues updating. - if let Some(initial_config) = &turn_state.resolved_config { - input.active_plugin_ids_at_turn_start = - initial_config.active_plugin_ids_at_turn_start.clone(); - } - turn_state.resolved_config = Some(input); - self.maybe_emit_turn_event(&turn_id, out).await; - } - - async fn ingest_turn_token_usage( - &mut self, - input: TurnTokenUsageFact, - out: &mut Vec, - ) { - let turn_id = input.turn_id.clone(); - let turn_state = self.turn_state(turn_id.clone()); - turn_state.thread_id = Some(input.thread_id); - turn_state.token_usage = Some(input.token_usage); - self.maybe_emit_turn_event(&turn_id, out).await; - } - - async fn ingest_turn_profile( - &mut self, - input: TurnProfileFact, - out: &mut Vec, - ) { - let TurnProfileFact { turn_id, profile } = input; - let turn_state = self.turn_state(turn_id.clone()); - turn_state.profile = Some(profile); - self.maybe_emit_turn_event(&turn_id, out).await; - } - - fn ingest_turn_codex_error(&mut self, input: TurnCodexErrorFact) { - let TurnCodexErrorFact { - turn_id, - thread_id, - error, - } = input; - let turn_state = self.turn_state(turn_id); - turn_state.thread_id.get_or_insert(thread_id); - turn_state.codex_error = Some(error); - } - - fn ingest_image_preparation(&mut self, input: ImagePreparationFact) { - let turn_state = self.turn_state(input.turn_id); - turn_state.image_preparations.push(input.metadata); - } - - async fn ingest_skill_invoked( - &mut self, - input: SkillInvokedInput, - out: &mut Vec, - ) { - let SkillInvokedInput { - tracking, - invocations, - } = input; - for invocation in invocations { - let (skill_id, skill_scope) = match invocation.location { - SkillInvocationLocation::Host { path, scope } => { - let skill_scope = match scope { - SkillScope::User => "user", - SkillScope::Repo => "repo", - SkillScope::System => "system", - SkillScope::Admin => "admin", - }; - let repo_root = path - .to_abs_path() - .ok() - .and_then(|path| get_git_repo_root(path.as_path())); - let repo_url = if let Some(root) = repo_root.as_ref() { - get_git_origin_url(root).await - } else { - None - }; - let skill_id = skill_id_for_local_skill( - repo_url.as_ref().map(SanitizedGitUrl::as_str), - repo_root.as_deref(), - &path, - invocation.skill_name.as_str(), - ); - (skill_id, Some(skill_scope.to_string())) - } - SkillInvocationLocation::Resource { - id, - skill_id, - scope, - } => { - if matches!(invocation.invocation_type, InvocationType::Implicit) { - let turn_state = self.turn_state(tracking.turn_id.clone()); - if !turn_state.resource_skill_invocations.insert(id.clone()) { - continue; - } - } - let skill_id = skill_id - .unwrap_or_else(|| format!("{:x}", sha1::Sha1::digest(id.as_bytes()))); - let skill_scope = scope - .map(|scope| match scope { - SkillScope::User => "user", - SkillScope::Repo => "repo", - SkillScope::System => "system", - SkillScope::Admin => "admin", - }) - .map(str::to_owned); - (skill_id, skill_scope) - } - }; - let turn = tracking.turn_metadata.as_deref(); - out.push(TrackEventRequest::SkillInvocation( - SkillInvocationEventRequest { - event_type: "skill_invocation", - skill_id, - skill_name: invocation.skill_name.clone(), - event_params: SkillInvocationEventParams { - turn_trigger: turn.and_then(TurnAnalyticsMetadata::turn_trigger), - thread_id: Some(tracking.thread_id.clone()), - turn_id: Some(tracking.turn_id.clone()), - voice_session_id: self - .turns - .get(&tracking.turn_id) - .and_then(|turn| turn.voice_session_id.clone()), - invoke_type: Some(invocation.invocation_type), - model_slug: Some(tracking.model_slug.clone()), - product_client_id: Some(tracking.product_client_id.clone()), - skill_scope, - plugin_id: invocation.plugin_id, - remote_plugin_id: invocation.remote_plugin_id, - }, - }, - )); - } - } - - fn ingest_app_mentioned(&mut self, input: AppMentionedInput, out: &mut Vec) { - let AppMentionedInput { tracking, mentions } = input; - out.extend(mentions.into_iter().map(|mention| { - let event_params = codex_app_metadata(&tracking, mention); - TrackEventRequest::AppMentioned(CodexAppMentionedEventRequest { - event_type: "codex_app_mentioned", - event_params, - }) - })); - } - - fn ingest_app_used(&mut self, input: AppUsedInput, out: &mut Vec) { - let AppUsedInput { - tracking, - app, - elicitation_type, - } = input; - let event_params = CodexAppUsedMetadata { - app: codex_app_metadata(&tracking, app), - voice_session_id: self - .turns - .get(&tracking.turn_id) - .and_then(|turn| turn.voice_session_id.clone()), - elicitation_type, - }; - out.push(TrackEventRequest::AppUsed(CodexAppUsedEventRequest { - event_type: "codex_app_used", - event_params, - })); - } - - fn ingest_hook_run(&mut self, input: HookRunInput, out: &mut Vec) { - let HookRunInput { tracking, hook } = input; - out.push(TrackEventRequest::HookRun(CodexHookRunEventRequest { - event_type: "codex_hook_run", - event_params: codex_hook_run_metadata(&tracking, hook), - })); - } - - fn ingest_plugin_used(&mut self, input: PluginUsedInput, out: &mut Vec) { - let PluginUsedInput { tracking, plugin } = input; - out.push(TrackEventRequest::PluginUsed(CodexPluginUsedEventRequest { - event_type: "codex_plugin_used", - event_params: codex_plugin_used_metadata(&tracking, plugin), - })); - } - - fn ingest_plugin_install_requested( - &mut self, - input: PluginInstallRequestedInput, - out: &mut Vec, - ) { - let PluginInstallRequestedInput { tracking, request } = input; - out.push(TrackEventRequest::PluginInstallRequested( - CodexPluginInstallRequestedEventRequest { - event_type: "codex_plugin_install_requested", - event_params: codex_plugin_install_requested_metadata(&tracking, request), - }, - )); - } - - fn ingest_plugin_state_changed( - &mut self, - input: PluginStateChangedInput, - out: &mut Vec, - ) { - let PluginStateChangedInput { plugin, state } = input; - let event = CodexPluginEventRequest { - event_type: plugin_state_event_type(state), - event_params: codex_plugin_metadata(plugin), - }; - out.push(match state { - PluginState::Installed => TrackEventRequest::PluginInstalled(event), - PluginState::Uninstalled => TrackEventRequest::PluginUninstalled(event), - PluginState::Enabled => TrackEventRequest::PluginEnabled(event), - PluginState::Disabled => TrackEventRequest::PluginDisabled(event), - }); - } - - fn ingest_plugin_install_failed( - &mut self, - input: PluginInstallFailedInput, - out: &mut Vec, - ) { - let PluginInstallFailedInput { - plugin, - source, - error_type, - sub_error_type, - } = input; - out.push(TrackEventRequest::PluginInstallFailed( - CodexPluginInstallFailedEventRequest { - event_type: "codex_plugin_install_failed", - event_params: CodexPluginInstallFailedMetadata { - plugin: codex_plugin_metadata(plugin), - source, - error_type, - sub_error_type, - }, - }, - )); - } - - fn ingest_external_agent_config_import_completed( - &mut self, - input: ExternalAgentConfigImportCompletedInput, - out: &mut Vec, - ) { - out.push(TrackEventRequest::ExternalAgentConfigImportCompleted( - CodexOnboardingExternalAgentImportCompleteEventRequest { - event_type: "codex_onboarding_external_agent_import_complete", - event_params: CodexOnboardingExternalAgentImportCompleteMetadata { - import_id: input.import_id, - source: input.source, - provider_id: input.provider_id, - item_type: input.item_type, - success_count: input.success_count, - failed_count: input.failed_count, - product_client_id: Some(originator().value), - }, - }, - )); - } - - fn ingest_external_agent_config_import_failure( - &mut self, - input: ExternalAgentConfigImportFailureInput, - out: &mut Vec, - ) { - out.push(TrackEventRequest::ExternalAgentConfigImportFailure( - CodexOnboardingExternalAgentImportFailureEventRequest { - event_type: "codex_onboarding_external_agent_import_failure", - event_params: CodexOnboardingExternalAgentImportFailureMetadata { - import_id: input.import_id, - source: input.source, - provider_id: input.provider_id, - item_type: input.item_type, - failure_stage: input.failure_stage, - error_type: input.error_type, - sub_error_type: input.sub_error_type, - product_client_id: Some(originator().value), - }, - }, - )); - } - - async fn ingest_response( - &mut self, - connection_id: u64, - response: ClientResponse, - thread_originator: Option, - out: &mut Vec, - ) { - match response { - ClientResponse::ThreadStart { response, .. } => { - self.emit_thread_initialized( - connection_id, - response.thread, - response.model, - ThreadInitializationMode::New, - thread_originator, - out, - ); - } - ClientResponse::ThreadResume { response, .. } => { - self.emit_thread_initialized( - connection_id, - response.thread, - response.model, - ThreadInitializationMode::Resumed, - thread_originator, - out, - ); - } - ClientResponse::ThreadFork { response, .. } => { - self.emit_thread_initialized( - connection_id, - response.thread, - response.model, - ThreadInitializationMode::Forked, - thread_originator, - out, - ); - } - ClientResponse::TurnStart { - request_id, - response, - } => { - let turn_id = response.turn.id; - let Some(RequestState::TurnStart(pending_request)) = - self.requests.remove(&(connection_id, request_id)) - else { - return; - }; - let turn_state = self.turn_state(turn_id.clone()); - turn_state.connection_id = Some(connection_id); - turn_state.thread_id = Some(pending_request.thread_id); - turn_state.num_input_images = Some(pending_request.num_input_images); - self.maybe_emit_turn_event(&turn_id, out).await; - } - ClientResponse::TurnSteer { - request_id, - response, - } => { - self.ingest_turn_steer_response(connection_id, request_id, response, out); - } - ClientResponse::TurnInterrupt { request_id, .. } => { - let Some(RequestState::ExplicitClientInterrupt(pending_request)) = - self.requests.remove(&(connection_id, request_id)) - else { - return; - }; - let turn_id = pending_request.turn_id; - let turn_state = self.turn_state(turn_id.clone()); - let earliest_requested_at_ms = turn_state - .explicit_client_interrupt_requested_at_ms - .get_or_insert(pending_request.requested_at_ms); - *earliest_requested_at_ms = - (*earliest_requested_at_ms).min(pending_request.requested_at_ms); - self.maybe_emit_turn_event(&turn_id, out).await; - } - _ => {} - } - } - - fn ingest_server_request(&mut self, _connection_id: u64, request: ServerRequest) { - match request { - ServerRequest::CommandExecutionRequestApproval { request_id, params } => { - let is_stdin_review = match params.kind { - CommandExecutionApprovalKind::WriteStdin => true, - CommandExecutionApprovalKind::Command - | CommandExecutionApprovalKind::HumanCommand => false, - }; - let is_network_access_review = params.network_approval_context.is_some(); - let requested_network_access = is_network_access_review - || params - .proposed_network_policy_amendments - .as_ref() - .is_some_and(|amendments| !amendments.is_empty()) - || params - .additional_permissions - .as_ref() - .and_then(|permissions| permissions.network.as_ref()) - .and_then(|network| network.enabled) - .unwrap_or(false); - let requested_additional_permissions = params.additional_permissions.is_some(); - let trigger = if is_stdin_review { - ReviewTrigger::Initial - } else if params.kind != CommandExecutionApprovalKind::HumanCommand - && params.approval_id.is_some() - { - ReviewTrigger::ExecveIntercept - } else if requested_network_access { - ReviewTrigger::NetworkPolicyDenial - } else if requested_additional_permissions { - ReviewTrigger::SandboxDenial - } else { - ReviewTrigger::Initial - }; - let Some(started_at_ms) = option_i64_to_u64(Some(params.started_at_ms)) else { - return; - }; - self.turn_state(params.turn_id.clone()).thread_id = Some(params.thread_id.clone()); - self.pending_reviews.insert( - request_id.clone(), - PendingReviewState { - thread_id: params.thread_id, - turn_id: params.turn_id, - item_id: Some(params.item_id), - review_id: user_review_id(&request_id), - subject_kind: if is_stdin_review { - ReviewSubjectKind::WriteStdin - } else if is_network_access_review { - ReviewSubjectKind::NetworkAccess - } else { - ReviewSubjectKind::CommandExecution - }, - subject_name: if is_stdin_review { - "write_stdin".to_string() - } else if is_network_access_review { - "network_access".to_string() - } else { - "command_execution".to_string() - }, - trigger, - started_at_ms, - requested_additional_permissions, - requested_network_access, - }, - ); - } - ServerRequest::FileChangeRequestApproval { request_id, params } => { - let requested_additional_permissions = params.grant_root.is_some(); - let Some(started_at_ms) = option_i64_to_u64(Some(params.started_at_ms)) else { - return; - }; - self.turn_state(params.turn_id.clone()).thread_id = Some(params.thread_id.clone()); - self.pending_reviews.insert( - request_id.clone(), - PendingReviewState { - thread_id: params.thread_id, - turn_id: params.turn_id, - item_id: Some(params.item_id), - review_id: user_review_id(&request_id), - subject_kind: ReviewSubjectKind::FileChange, - subject_name: "apply_patch".to_string(), - trigger: if requested_additional_permissions { - ReviewTrigger::SandboxDenial - } else { - ReviewTrigger::Initial - }, - started_at_ms, - requested_additional_permissions, - requested_network_access: false, - }, - ); - } - ServerRequest::PermissionsRequestApproval { request_id, params } => { - let requested_network_access = params - .permissions - .network - .as_ref() - .and_then(|network| network.enabled) - .unwrap_or(false); - let requested_additional_permissions = - requested_network_access || params.permissions.file_system.is_some(); - let trigger = if requested_network_access { - ReviewTrigger::NetworkPolicyDenial - } else if requested_additional_permissions { - ReviewTrigger::SandboxDenial - } else { - ReviewTrigger::Initial - }; - let Some(started_at_ms) = option_i64_to_u64(Some(params.started_at_ms)) else { - return; - }; - self.turn_state(params.turn_id.clone()).thread_id = Some(params.thread_id.clone()); - self.pending_reviews.insert( - request_id.clone(), - PendingReviewState { - thread_id: params.thread_id, - turn_id: params.turn_id, - item_id: Some(params.item_id), - review_id: user_review_id(&request_id), - subject_kind: ReviewSubjectKind::Permissions, - subject_name: "permissions".to_string(), - trigger, - started_at_ms, - requested_additional_permissions, - requested_network_access, - }, - ); - } - _ => {} - } - } - - fn ingest_server_response( - &mut self, - completed_at_ms: u64, - response: ServerResponse, - out: &mut Vec, - ) { - match response { - ServerResponse::CommandExecutionRequestApproval { - request_id, - response, - } => { - let Some(pending_review) = self.pending_reviews.remove(&request_id) else { - return; - }; - let (status, resolution) = command_execution_review_result(response.decision); - self.emit_review_event( - pending_review, - Reviewer::User, - status, - resolution, - completed_at_ms, - out, - ); - } - ServerResponse::FileChangeRequestApproval { - request_id, - response, - } => { - let Some(pending_review) = self.pending_reviews.remove(&request_id) else { - return; - }; - let (status, resolution) = file_change_review_result(response.decision); - self.emit_review_event( - pending_review, - Reviewer::User, - status, - resolution, - completed_at_ms, - out, - ); - } - _ => {} - } - } - - fn ingest_effective_permissions_approval_response( - &mut self, - completed_at_ms: u64, - request_id: RequestId, - response: CoreRequestPermissionsResponse, - out: &mut Vec, - ) { - let Some(pending_review) = self.pending_reviews.remove(&request_id) else { - return; - }; - let (status, resolution) = effective_permissions_review_result(&response); - self.emit_review_event( - pending_review, - Reviewer::User, - status, - resolution, - completed_at_ms, - out, - ); - } - - fn ingest_server_request_aborted( - &mut self, - completed_at_ms: u64, - request_id: RequestId, - out: &mut Vec, - ) { - let Some(pending_review) = self.pending_reviews.remove(&request_id) else { - return; - }; - self.emit_review_event( - pending_review, - Reviewer::User, - ReviewStatus::Aborted, - ReviewResolution::None, - completed_at_ms, - out, - ); - } - - fn ingest_error_response( - &mut self, - connection_id: u64, - request_id: RequestId, - error_type: Option, - out: &mut Vec, - ) { - let Some(request) = self.requests.remove(&(connection_id, request_id)) else { - return; - }; - self.ingest_request_error_response(connection_id, request, error_type, out); - } - - fn ingest_request_error_response( - &mut self, - connection_id: u64, - request: RequestState, - error_type: Option, - out: &mut Vec, - ) { - match request { - RequestState::TurnStart(_) => {} - RequestState::TurnSteer(pending_request) => { - self.ingest_turn_steer_error_response( - connection_id, - pending_request, - error_type, - out, - ); - } - RequestState::ExplicitClientInterrupt(_) => {} - } - } - - fn ingest_turn_steer_error_response( - &mut self, - connection_id: u64, - pending_request: PendingTurnSteerState, - error_type: Option, - out: &mut Vec, - ) { - self.emit_turn_steer_event( - connection_id, - pending_request, - /*accepted_turn_id*/ None, - TurnSteerResult::Rejected, - rejection_reason_from_error_type(error_type), - out, - ); - } - - fn thread_archive_event_params( - &self, - thread_id: String, - action: ThreadArchiveAction, - ) -> ThreadArchiveEventParams { - let thread_state = self.threads.get(&thread_id); - let connection_state = self - .thread_connection_id(&thread_id) - .and_then(|connection_id| self.connections.get(&connection_id)); - let thread_metadata = thread_state.and_then(|thread_state| thread_state.metadata.as_ref()); - - ThreadArchiveEventParams { - thread_id, - action, - occurred_at_ms: now_unix_millis(), - app_server_client: thread_state - .zip(connection_state) - .map(|(thread_state, connection_state)| { - thread_state.app_server_client(connection_state) - }), - runtime: connection_state.map(|connection_state| connection_state.runtime.clone()), - thread_source: thread_metadata - .and_then(|thread_metadata| thread_metadata.thread_source.as_ref()) - .filter(|thread_source| { - !matches!(thread_source, ThreadSource::Feature(feature) if feature != "automation") - }) - .cloned(), - parent_thread_id: thread_metadata - .and_then(|thread_metadata| thread_metadata.parent_thread_id.clone()), - } - } - - async fn ingest_notification( - &mut self, - notification: ServerNotification, - out: &mut Vec, - ) { - match notification { - ServerNotification::ThreadArchived(notification) => { - out.push(TrackEventRequest::ThreadArchive(ThreadArchiveEvent { - event_type: "codex_thread_archive_event", - event_params: self.thread_archive_event_params( - notification.thread_id, - ThreadArchiveAction::Archived, - ), - })); - } - ServerNotification::ThreadUnarchived(notification) => { - out.push(TrackEventRequest::ThreadArchive(ThreadArchiveEvent { - event_type: "codex_thread_archive_event", - event_params: self.thread_archive_event_params( - notification.thread_id, - ThreadArchiveAction::Unarchived, - ), - })); - } - ServerNotification::ItemStarted(notification) => { - let Some(item_id) = tracked_tool_item_id(¬ification.item.payload) else { - return; - }; - let Some(started_at_ms) = option_i64_to_u64(Some(notification.started_at_ms)) - else { - return; - }; - let model_context = match ¬ification.item.payload { - ThreadItemPayload::CommandExecution { model_context, .. } => { - model_context.clone() - } - _ => None, - }; - self.turn_state(notification.turn_id.clone()) - .thread_id - .get_or_insert(notification.thread_id.clone()); - let key = ToolItemKey { - thread_id: notification.thread_id.clone(), - turn_id: notification.turn_id.clone(), - item_id: item_id.to_string(), - }; - let cua_identity = cua_mcp_tool_identity(¬ification.item.payload); - if cua_identity.is_some() - && self - .turns - .get(¬ification.turn_id) - .is_some_and(|turn| turn.completed_cua_tool_item_ids.contains(item_id)) - { - return; - } - let first_notification = !self.tool_items_started_at_ms.contains_key(&key); - self.tool_items_started_at_ms - .entry(key) - .and_modify(|(timestamp, _)| *timestamp = started_at_ms) - .or_insert((started_at_ms, model_context)); - if !first_notification { - return; - } - let Some((server, tool, plugin_id, connector_id)) = cua_identity else { - return; - }; - let Some((connection_state, thread_state, thread_metadata)) = self - .thread_context_or_warn(AnalyticsDropSite::cua_tool_call_started( - ¬ification.thread_id, - ¬ification.turn_id, - item_id, - )) - else { - return; - }; - let attribution = tool_response_attribution( - item_id, - /*cell_id*/ None, - self.tool_response_states - .get(&(notification.thread_id.clone(), notification.turn_id.clone())), - self.code_mode_cells.get(¬ification.thread_id), - ); - let turn_metadata = self - .turns - .get(¬ification.turn_id) - .and_then(|turn| turn.resolved_config.as_ref()) - .map(|config| config.turn_metadata.as_ref()); - out.push(TrackEventRequest::CuaToolCallStarted( - CodexCuaToolCallStartedEventRequest { - event_type: "codex_cua_tool_call_started", - event_params: CodexCuaToolCallStartedEventParams { - thread_id: notification.thread_id, - session_id: thread_metadata.session_id.clone(), - turn_id: notification.turn_id, - root_turn_id: turn_metadata - .and_then(TurnAnalyticsMetadata::root_turn_id), - turn_trigger: turn_metadata - .and_then(TurnAnalyticsMetadata::turn_trigger), - item_id: item_id.to_string(), - cell_id: attribution.cell_id, - parent_call_id: attribution.parent_call_id, - originating_response_id: attribution.originating_response_id, - app_server_client: thread_state.app_server_client(connection_state), - runtime: connection_state.runtime.clone(), - thread_source: thread_metadata.thread_source.clone(), - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id.clone(), - tool_event_type: attribution.tool_event_type, - started_at_ms, - mcp_server_name: server.to_string(), - mcp_tool_name: tool.to_string(), - plugin_id: plugin_id.map(str::to_string), - connector_id: connector_id.map(str::to_string), - }, - }, - )); - } - ServerNotification::ItemCompleted(notification) => { - if matches!( - notification.item.payload, - ThreadItemPayload::SubAgentActivity { .. } - ) { - let Some(turn_state) = self.turns.get_mut(¬ification.turn_id) else { - tracing::warn!( - thread_id = %notification.thread_id, - turn_id = %notification.turn_id, - "dropping sub-agent activity tool count update: missing turn state" - ); - return; - }; - turn_state.tool_counts.record(¬ification.item.payload); - return; - } - let Some(item_id) = tracked_tool_item_id(¬ification.item.payload) else { - return; - }; - let key = ToolItemKey { - thread_id: notification.thread_id.clone(), - turn_id: notification.turn_id.clone(), - item_id: item_id.to_string(), - }; - let is_cua = cua_mcp_tool_identity(¬ification.item.payload).is_some(); - if is_cua - && self - .turns - .get(¬ification.turn_id) - .is_some_and(|turn| turn.completed_cua_tool_item_ids.contains(item_id)) - { - return; - } - let elicitation_type = if matches!( - notification.item.payload, - ThreadItemPayload::McpToolCall { .. } - ) { - // Producers enqueue known classifications before completion on - // the same analytics queue, so completed keys need no history. - self.pending_mcp_tool_elicitations - .iter() - .position(|(pending, _)| pending == &key) - .and_then(|index| self.pending_mcp_tool_elicitations.remove(index)) - .map(|(_, elicitation_type)| elicitation_type) - } else { - None - }; - let Some(turn_state) = self.turns.get_mut(¬ification.turn_id) else { - tracing::warn!( - thread_id = %notification.thread_id, - turn_id = %notification.turn_id, - item_id, - "dropping turn tool count update: missing turn state" - ); - return; - }; - turn_state.tool_counts.record(¬ification.item.payload); - let Some((started_at_ms, model_context)) = - self.tool_items_started_at_ms.remove(&key) - else { - tracing::warn!( - thread_id = %notification.thread_id, - turn_id = %notification.turn_id, - item_id, - "dropping tool item analytics event: missing item started notification" - ); - return; - }; - let Some(completed_at_ms) = option_i64_to_u64(Some(notification.completed_at_ms)) - else { - return; - }; - let Some((connection_state, thread_state, thread_metadata)) = self - .thread_context_or_warn(AnalyticsDropSite::tool_item(¬ification, item_id)) - else { - return; - }; - if let Some(mut event) = tool_item_event(ToolItemEventInput { - thread_id: ¬ification.thread_id, - turn_id: ¬ification.turn_id, - item: ¬ification.item.payload, - model_context: model_context.as_ref(), - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary: self.item_review_summaries.get(&key), - elicitation_type, - }) { - if let TrackEventRequest::McpToolCall(mcp) = &mut event { - mcp.event_params.voice_session_id = self - .turns - .get(¬ification.turn_id) - .and_then(|turn| turn.voice_session_id.clone()); - } - let turn_metadata = self - .turns - .get(¬ification.turn_id) - .and_then(|turn| turn.resolved_config.as_ref()) - .map(|config| Arc::clone(&config.turn_metadata)); - // Fast collaborator tools can complete before their sampling response. - // Keep the event until that response can supply its originating ID. - let emission = if matches!( - ¬ification.item.payload, - ThreadItemPayload::CollabAgentToolCall { .. } - ) { - ToolEventEmission::AwaitResponse - } else { - ToolEventEmission::ImmediateUnlessCorrelated - }; - self.record_tool_event( - ¬ification.thread_id, - ¬ification.turn_id, - turn_metadata.as_deref(), - event, - emission, - out, - ); - if is_cua && let Some(turn) = self.turns.get_mut(¬ification.turn_id) { - turn.completed_cua_tool_item_ids.insert(item_id.to_string()); - } - } - self.item_review_summaries.remove(&key); - if self - .turns - .get(¬ification.turn_id) - .is_some_and(|turn_state| turn_state.turn_event_emitted) - && !self.has_pending_tool_items_for_turn(¬ification.turn_id) - { - self.turns.remove(¬ification.turn_id); - } - } - ServerNotification::ItemGuardianApprovalReviewStarted(notification) => { - let _ = notification; - } - ServerNotification::ItemGuardianApprovalReviewCompleted(notification) => { - self.ingest_guardian_review_completed(notification, out); - } - ServerNotification::ThreadClosed(notification) => { - self.tool_response_states.retain(|(thread_id, _), state| { - if thread_id == ¬ification.thread_id { - out.extend(state.pending_tool_events.drain(..)); - false - } else { - true - } - }); - let closed_turns: Vec<_> = self - .turns - .iter() - .filter(|(_, turn)| turn.thread_id.as_deref() == Some(¬ification.thread_id)) - .map(|(turn_id, _)| turn_id.clone()) - .collect(); - for turn_id in closed_turns { - self.discard_turn(&turn_id); - } - self.pending_reviews - .retain(|_, review| review.thread_id != notification.thread_id); - self.code_mode_cells.remove(¬ification.thread_id); - self.pending_mcp_tool_elicitations - .retain(|(key, _)| key.thread_id != notification.thread_id); - if let Some(thread) = self.threads.get_mut(¬ification.thread_id) { - thread.active_voice_session = None; - thread.recent_voice_sessions.clear(); - thread.active_turn_id = None; - thread.pending_voice_handoffs.clear(); - } - } - ServerNotification::ThreadRealtimeStarted(notification) => { - self.start_voice_session( - notification.thread_id, - notification.realtime_session_id, - now_unix_seconds(), - ); - } - ServerNotification::ThreadRealtimeClosed(notification) => { - self.close_voice_session(¬ification.thread_id, now_unix_seconds()); - } - ServerNotification::TurnStarted(notification) => { - let voice_session_id = { - let thread = self - .threads - .entry(notification.thread_id.clone()) - .or_default(); - thread.active_turn_id = Some(notification.turn.id.clone()); - thread - .pending_voice_handoffs - .pop_front() - .unwrap_or_else(|| thread.active_voice_session_id()) - }; - let turn_state = self.turn_state(notification.turn.id); - turn_state.thread_id = Some(notification.thread_id); - turn_state.voice_session_id = voice_session_id; - turn_state.started_at = notification - .turn - .started_at - .and_then(|started_at| u64::try_from(started_at).ok()); - } - ServerNotification::TurnDiffUpdated(notification) => { - let turn_state = self.turn_state(notification.turn_id.clone()); - turn_state.thread_id = Some(notification.thread_id); - turn_state.latest_diff = Some(notification.diff); - } - ServerNotification::TurnCompleted(notification) => { - if let Some(thread) = self.threads.get_mut(¬ification.thread_id) - && thread.active_turn_id.as_deref() == Some(notification.turn.id.as_str()) - { - thread.active_turn_id = None; - } - self.flush_pending_tool_events(¬ification.thread_id, ¬ification.turn.id, out); - let turn_state = self.turn_state(notification.turn.id.clone()); - turn_state.thread_id = Some(notification.thread_id); - turn_state.completed = Some(CompletedTurnState { - status: analytics_turn_status(notification.turn.status), - turn_error: notification - .turn - .error - .and_then(|error| error.codex_error_info), - completed_at: notification - .turn - .completed_at - .and_then(|completed_at| u64::try_from(completed_at).ok()) - .unwrap_or_default(), - duration_ms: notification - .turn - .duration_ms - .and_then(|duration_ms| u64::try_from(duration_ms).ok()), - }); - let turn_id = notification.turn.id; - self.maybe_emit_turn_event(&turn_id, out).await; - } - _ => {} - } - } - - fn ingest_plugin_measurements( - &mut self, - input: PluginMeasurementsInput, - out: &mut Vec, - ) { - if input.rows.is_empty() - || input.rows.len() > MAX_PLUGIN_MEASUREMENTS_PER_BATCH - || !valid_plugin_measurement_identifier(&input.operation) - { - return; - } - let PluginMeasurementsInput { - thread_id, - turn_id, - item_id, - originator, - model_slug, - reasoning_effort, - plugin_id, - execution_id, - operation, - rows, - } = input; - out.extend( - rows.into_iter() - .filter(valid_plugin_measurement_row) - .map(|row| { - TrackEventRequest::PluginMeasurement(CodexPluginMeasurementEventRequest { - event_type: "codex_plugin_measurement_event", - event_params: CodexPluginMeasurementEventParams { - thread_id: thread_id.clone(), - turn_id: turn_id.clone(), - item_id: item_id.clone(), - originator: originator.clone(), - model_slug: model_slug.clone(), - reasoning_effort: reasoning_effort.clone(), - plugin_id: plugin_id.clone(), - execution_id: execution_id.clone(), - operation: operation.clone(), - measurement_name: row.measurement_name, - number_value: row.number_value, - dimensions: (!row.dimensions.is_empty()).then_some(row.dimensions), - }, - }) - }), - ); - } - - fn emit_thread_initialized( - &mut self, - connection_id: u64, - thread: codex_app_server_protocol::Thread, - model: String, - initialization_mode: ThreadInitializationMode, - thread_originator: Option, - out: &mut Vec, - ) { - let session_source: SessionSource = thread.source.into(); - let is_worktree = - codex_git_utils::repository_identity(thread.cwd.as_path()).and_then(|_| { - codex_git_utils::get_git_repo_root(thread.cwd.canonicalize().ok()?.as_path()) - .map(|root| root.join(".git").is_file()) - }); - let session_id = thread.session_id; - let thread_id = thread.id; - let parent_thread_id = thread.parent_thread_id; - let forked_from_thread_id = thread.forked_from_id; - let Some(connection_state) = self.connections.get(&connection_id) else { - return; - }; - let thread_metadata = ThreadMetadataState::from_thread_metadata( - session_id.clone(), - &session_source, - thread.thread_source.map(Into::into), - parent_thread_id, - initialization_mode, - ); - let thread_state = self.threads.entry(thread_id.clone()).or_default(); - if let Some(originator) = thread_originator { - thread_state.originator = Some(originator); - } - thread_state.connection_id = Some(connection_id); - thread_state.metadata = Some(thread_metadata.clone()); - let app_server_client = thread_state.app_server_client(connection_state); - out.push(TrackEventRequest::ThreadInitialized( - ThreadInitializedEvent { - event_type: "codex_thread_initialized", - event_params: ThreadInitializedEventParams { - thread_id, - session_id, - app_server_client, - runtime: connection_state.runtime.clone(), - model, - ephemeral: thread.ephemeral, - is_worktree, - thread_source: thread_metadata.thread_source, - initialization_mode, - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id, - forked_from_thread_id, - created_at: u64::try_from(thread.created_at).unwrap_or_default(), - }, - }, - )); - } - - fn ingest_compaction(&mut self, input: CodexCompactionEvent, out: &mut Vec) { - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(AnalyticsDropSite::compaction(&input)) - else { - return; - }; - let voice_session_id = thread_state - .voice_session_id_at(input.started_at) - .or_else(|| { - self.turns - .get(&input.turn_id) - .and_then(|turn| turn.voice_session_id.clone()) - }); - let mut event_params = codex_compaction_event_params( - input, - thread_metadata.session_id.clone(), - thread_state.app_server_client(connection_state), - connection_state.runtime.clone(), - thread_metadata.thread_source.clone(), - thread_metadata.subagent_source.clone(), - thread_metadata.parent_thread_id.clone(), - ); - event_params.voice_session_id = voice_session_id; - out.push(TrackEventRequest::Compaction(Box::new( - CodexCompactionEventRequest { - event_type: "codex_compaction_event", - event_params, - }, - ))); - } - - fn set_active_voice_session_id( - &mut self, - thread_id: String, - realtime_session_id: Option, - ) { - let thread = self.threads.entry(thread_id).or_default(); - let realtime_session_id = realtime_session_id.filter(|id| !id.is_empty()); - let Some(session) = thread.active_voice_session.as_mut() else { - return; - }; - session.session_id.clone_from(&realtime_session_id); - if let Some(turn_id) = thread.active_turn_id.clone() { - self.turn_state(turn_id).voice_session_id = realtime_session_id; - } - } - - fn start_voice_session( - &mut self, - thread_id: String, - realtime_session_id: Option, - started_at: u64, - ) { - self.close_voice_session(&thread_id, started_at); - let realtime_session_id = realtime_session_id.filter(|id| !id.is_empty()); - let thread = self.threads.entry(thread_id).or_default(); - thread.active_voice_session = Some(VoiceSessionWindow { - session_id: realtime_session_id.clone(), - started_at, - closed_at: None, - }); - if let Some(turn_id) = thread.active_turn_id.clone() { - self.turn_state(turn_id).voice_session_id = realtime_session_id; - } - } - - fn close_voice_session(&mut self, thread_id: &str, closed_at: u64) { - let Some(thread) = self.threads.get_mut(thread_id) else { - return; - }; - if let Some(mut session) = thread.active_voice_session.take() { - session.closed_at = Some(closed_at); - if session.session_id.is_some() { - if thread.recent_voice_sessions.len() >= MAX_RECENT_VOICE_SESSION_WINDOWS { - thread.recent_voice_sessions.pop_front(); - } - thread.recent_voice_sessions.push_back(session); - } - } - } - - fn ingest_goal(&mut self, input: CodexGoalEvent, out: &mut Vec) { - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(AnalyticsDropSite::goal(&input)) - else { - return; - }; - out.push(TrackEventRequest::Goal(Box::new(CodexGoalEventRequest { - event_type: "codex_goal_event", - event_params: codex_goal_event_params( - input, - thread_metadata.session_id.clone(), - thread_state.app_server_client(connection_state), - connection_state.runtime.clone(), - thread_metadata.thread_source.clone(), - thread_metadata.subagent_source.clone(), - thread_metadata.parent_thread_id.clone(), - ), - }))); - } - - fn ingest_guardian_review_completed( - &mut self, - notification: codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification, - out: &mut Vec, - ) { - let Some((status, resolution)) = guardian_review_result(notification.review.status) else { - return; - }; - let (subject_kind, subject_name, trigger) = - guardian_review_subject_metadata(¬ification.action); - let Some(started_at_ms) = option_i64_to_u64(Some(notification.started_at_ms)) else { - return; - }; - let pending_review = PendingReviewState { - thread_id: notification.thread_id, - turn_id: notification.turn_id, - item_id: notification.target_item_id, - review_id: notification.review_id, - subject_kind, - subject_name, - trigger, - started_at_ms, - requested_additional_permissions: guardian_review_requested_additional_permissions( - ¬ification.action, - ), - requested_network_access: guardian_review_requested_network_access( - ¬ification.action, - ), - }; - let Some(completed_at_ms) = option_i64_to_u64(Some(notification.completed_at_ms)) else { - return; - }; - self.emit_review_event( - pending_review, - Reviewer::Guardian, - status, - resolution, - completed_at_ms, - out, - ); - } - - fn ingest_turn_steer_response( - &mut self, - connection_id: u64, - request_id: RequestId, - response: TurnSteerResponse, - out: &mut Vec, - ) { - let Some(RequestState::TurnSteer(pending_request)) = - self.requests.remove(&(connection_id, request_id)) - else { - return; - }; - if let Some(turn_state) = self.turns.get_mut(&response.turn_id) { - turn_state.steer_count += 1; - } - self.emit_turn_steer_event( - connection_id, - pending_request, - Some(response.turn_id), - TurnSteerResult::Accepted, - /*rejection_reason*/ None, - out, - ); - } - - fn emit_turn_steer_event( - &mut self, - connection_id: u64, - pending_request: PendingTurnSteerState, - accepted_turn_id: Option, - result: TurnSteerResult, - rejection_reason: Option, - out: &mut Vec, - ) { - let Some(connection_state) = self.connections.get(&connection_id) else { - return; - }; - let drop_site = AnalyticsDropSite::turn_steer(&pending_request.thread_id); - let Some(thread_state) = self.threads.get(drop_site.thread_id) else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return; - }; - let Some(thread_metadata) = thread_state.metadata.as_ref() else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return; - }; - out.push(TrackEventRequest::TurnSteer(CodexTurnSteerEventRequest { - event_type: "codex_turn_steer_event", - event_params: CodexTurnSteerEventParams { - thread_id: pending_request.thread_id, - session_id: thread_metadata.session_id.clone(), - expected_turn_id: Some(pending_request.expected_turn_id), - accepted_turn_id, - app_server_client: thread_state.app_server_client(connection_state), - runtime: connection_state.runtime.clone(), - thread_source: thread_metadata.thread_source.clone(), - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id.clone(), - num_input_images: pending_request.num_input_images, - result, - rejection_reason, - created_at: pending_request.created_at, - }, - })); - } - - fn emit_review_event( - &mut self, - pending_review: PendingReviewState, - reviewer: Reviewer, - status: ReviewStatus, - resolution: ReviewResolution, - completed_at_ms: u64, - out: &mut Vec, - ) { - if let Some(item_key) = item_review_summary_key(&pending_review) { - self.record_item_review_summary( - item_key, - reviewer, - status, - resolution, - &pending_review, - ); - } - let Some((connection_state, thread_state, thread_metadata)) = - self.thread_context_or_warn(AnalyticsDropSite::review(&pending_review)) - else { - return; - }; - out.push(TrackEventRequest::ReviewEvent(CodexReviewEventRequest { - event_type: "codex_review_event", - event_params: CodexReviewEventParams { - thread_id: pending_review.thread_id, - turn_id: pending_review.turn_id, - item_id: pending_review.item_id, - review_id: pending_review.review_id, - app_server_client: thread_state.app_server_client(connection_state), - runtime: connection_state.runtime.clone(), - thread_source: thread_metadata.thread_source.clone(), - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id.clone(), - subject_kind: pending_review.subject_kind, - subject_name: pending_review.subject_name, - reviewer, - trigger: pending_review.trigger, - status, - resolution, - started_at_ms: pending_review.started_at_ms, - completed_at_ms, - duration_ms: observed_duration_ms(pending_review.started_at_ms, completed_at_ms), - }, - })); - } - - fn record_item_review_summary( - &mut self, - item_key: ToolItemKey, - reviewer: Reviewer, - status: ReviewStatus, - resolution: ReviewResolution, - pending_review: &PendingReviewState, - ) { - let summary = self.item_review_summaries.entry(item_key).or_default(); - summary.review_count += 1; - match reviewer { - Reviewer::Guardian => summary.guardian_review_count += 1, - Reviewer::User => summary.user_review_count += 1, - } - summary.final_approval_outcome = Some(final_approval_outcome(reviewer, status, resolution)); - summary.requested_additional_permissions |= pending_review.requested_additional_permissions; - summary.requested_network_access |= pending_review.requested_network_access; - } - - async fn maybe_emit_turn_event(&mut self, turn_id: &str, out: &mut Vec) { - let Some(turn_state) = self.turns.get(turn_id) else { - return; - }; - if turn_state.turn_event_emitted { - return; - } - if turn_state.thread_id.is_none() - || turn_state.num_input_images.is_none() - || turn_state.resolved_config.is_none() - || turn_state.profile.is_none() - || turn_state.completed.is_none() - { - return; - } - let Some(thread_id) = turn_state.thread_id.as_ref() else { - return; - }; - let drop_site = AnalyticsDropSite::turn(thread_id, turn_id); - let connection_id = turn_state - .connection_id - .or_else(|| self.thread_connection_id(drop_site.thread_id)); - let Some(connection_id) = connection_id else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadConnection); - return; - }; - let Some(connection_state) = self.connections.get(&connection_id) else { - warn_missing_analytics_context( - &drop_site, - MissingAnalyticsContext::Connection { connection_id }, - ); - return; - }; - let Some(thread_state) = self.threads.get(drop_site.thread_id) else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return; - }; - let Some(thread_metadata) = thread_state.metadata.as_ref() else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return; - }; - let turn_event = TrackEventRequest::TurnEvent(Box::new(CodexTurnEventRequest { - event_type: "codex_turn_event", - event_params: codex_turn_event_params( - thread_state.app_server_client(connection_state), - connection_state.runtime.clone(), - turn_id.to_string(), - turn_state, - thread_metadata, - ), - })); - let accepted_line_event = accepted_line_event_input(turn_id, turn_state); - - out.push(turn_event); - if let Some((mut input, cwd)) = accepted_line_event { - input.repo_hash = accepted_line_repo_hash_for_cwd(cwd.as_path()).await; - out.extend(accepted_line_fingerprint_event_requests(input)); - } - if self.has_pending_tool_items_for_turn(turn_id) { - if let Some(turn_state) = self.turns.get_mut(turn_id) { - turn_state.turn_event_emitted = true; - } - } else { - self.turns.remove(turn_id); - } - } - - fn has_pending_tool_items_for_turn(&self, turn_id: &str) -> bool { - self.tool_items_started_at_ms - .keys() - .any(|key| key.turn_id == turn_id) - } - - /// Resolve the parent connection lazily when a subagent fact arrives first. - /// - /// Parents are spawned before their children, so ancestor links cannot cycle. - fn thread_connection_id(&self, thread_id: &str) -> Option { - let mut thread = self.threads.get(thread_id)?; - while thread.connection_id.is_none() { - let thread_metadata = thread.metadata.as_ref()?; - let parent_thread_id = thread_metadata.parent_thread_id.as_deref()?; - thread = self.threads.get(parent_thread_id)?; - } - thread.connection_id - } - - fn thread_connection_or_warn( - &self, - drop_site: AnalyticsDropSite<'_>, - ) -> Option<&ConnectionState> { - let Some(connection_id) = self.thread_connection_id(drop_site.thread_id) else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadConnection); - return None; - }; - let Some(connection_state) = self.connections.get(&connection_id) else { - warn_missing_analytics_context( - &drop_site, - MissingAnalyticsContext::Connection { connection_id }, - ); - return None; - }; - Some(connection_state) - } - - fn thread_context_or_warn( - &self, - drop_site: AnalyticsDropSite<'_>, - ) -> Option<( - &ConnectionState, - &ThreadAnalyticsState, - &ThreadMetadataState, - )> { - let connection_state = self.thread_connection_or_warn(drop_site)?; - let thread_state = self.threads.get(drop_site.thread_id)?; - let Some(thread_metadata) = thread_state.metadata.as_ref() else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return None; - }; - Some((connection_state, thread_state, thread_metadata)) - } -} - -fn warn_missing_analytics_context( - drop_site: &AnalyticsDropSite<'_>, - missing: MissingAnalyticsContext, -) { - let (missing_context, connection_id) = match missing { - MissingAnalyticsContext::ThreadConnection => ("thread_connection", None), - MissingAnalyticsContext::Connection { connection_id } => { - ("connection", Some(connection_id)) - } - MissingAnalyticsContext::ThreadMetadata => ("thread_metadata", None), - }; - tracing::warn!( - thread_id = %drop_site.thread_id, - turn_id = ?drop_site.turn_id, - review_id = ?drop_site.review_id, - item_id = ?drop_site.item_id, - missing_context, - connection_id, - "dropping {} analytics event: missing analytics context", - drop_site.event_name - ); -} - -pub(crate) fn tracked_tool_item_id(item: &ThreadItemPayload) -> Option<&str> { - match item { - ThreadItemPayload::CommandExecution { id, .. } - | ThreadItemPayload::FileChange { id, .. } - | ThreadItemPayload::McpToolCall { id, .. } - | ThreadItemPayload::DynamicToolCall { id, .. } - | ThreadItemPayload::CollabAgentToolCall { id, .. } => Some(id), - ThreadItemPayload::WebSearch(item) => Some(&item.id), - ThreadItemPayload::ImageGeneration(item) => Some(&item.id), - ThreadItemPayload::UserMessage { .. } - | ThreadItemPayload::HookPrompt { .. } - | ThreadItemPayload::AgentMessage { .. } - | ThreadItemPayload::FunctionCallOutput { .. } - | ThreadItemPayload::Plan { .. } - | ThreadItemPayload::Reasoning { .. } - | ThreadItemPayload::SubAgentActivity { .. } - | ThreadItemPayload::ImageView { .. } - | ThreadItemPayload::Sleep(_) - | ThreadItemPayload::EnteredReviewMode { .. } - | ThreadItemPayload::ExitedReviewMode { .. } - | ThreadItemPayload::ContextCompaction { .. } => None, - } -} - -fn cua_mcp_tool_identity( - item: &ThreadItemPayload, -) -> Option<(&str, &str, Option<&str>, Option<&str>)> { - let ThreadItemPayload::McpToolCall { - server, - tool, - plugin_id, - app_context, - .. - } = item - else { - return None; - }; - let connector_id = app_context - .as_ref() - .map(|app_context| app_context.connector_id.as_str()); - (tool == "js" && is_node_repl_backed_connector(server, connector_id)).then_some(( - server, - tool, - plugin_id.as_deref(), - connector_id, - )) -} - -fn tool_event_base_mut(event: &mut TrackEventRequest) -> Option<&mut CodexToolItemEventBase> { - match event { - TrackEventRequest::CommandExecution(event) => Some(&mut event.event_params.base), - TrackEventRequest::FileChange(event) => Some(&mut event.event_params.base), - TrackEventRequest::McpToolCall(event) => Some(&mut event.event_params.base), - TrackEventRequest::DynamicToolCall(event) => Some(&mut event.event_params.base), - TrackEventRequest::ControlToolCall(event) => Some(&mut event.event_params.base), - TrackEventRequest::CollabAgentToolCall(event) => Some(&mut event.event_params.base), - TrackEventRequest::WebSearch(event) => Some(&mut event.event_params.base), - TrackEventRequest::ImageGeneration(event) => Some(&mut event.event_params.base), - _ => None, - } -} - -fn enrich_tool_response_event( - event: &mut TrackEventRequest, - state: &ToolResponseState, - cells: Option<&HashMap>, -) { - let Some(base) = tool_event_base_mut(event) else { - return; - }; - let attribution = - tool_response_attribution(&base.item_id, base.cell_id.clone(), Some(state), cells); - base.tool_event_type = attribution.tool_event_type; - base.cell_id = attribution.cell_id; - base.parent_call_id = attribution.parent_call_id; - base.originating_response_id = attribution.originating_response_id; -} - -#[derive(Default)] -struct ToolResponseAttribution { - tool_event_type: Option, - cell_id: Option, - parent_call_id: Option, - originating_response_id: Option, -} - -fn tool_response_attribution( - item_id: &str, - cell_id: Option, - state: Option<&ToolResponseState>, - cells: Option<&HashMap>, -) -> ToolResponseAttribution { - // A cell association can also describe a separately sampled wait call. Classify - // only from evidence about this exact call ID, not its parent or response lineage. - let tool_event_type = match ( - state.is_some_and(|state| state.response_ids_by_call_id.contains_key(item_id)), - state.is_some_and(|state| state.cell_ids_by_child_call_id.contains_key(item_id)), - ) { - (true, false) => Some(ToolEventType::ModelToolCall), - (false, true) => Some(ToolEventType::InnerToolCall), - (false, false) | (true, true) => None, - }; - let cell_id = cell_id - .or_else(|| state.and_then(|state| state.cell_ids_by_child_call_id.get(item_id).cloned())); - let cell = cell_id.as_ref().and_then(|cell_id| cells?.get(cell_id)); - let parent_call_id = - cell.and_then(|cell| (cell.parent_call_id != item_id).then(|| cell.parent_call_id.clone())); - let originating_response_id = state - .and_then(|state| state.response_ids_by_call_id.get(item_id).cloned()) - .or_else(|| cell.and_then(|cell| cell.originating_response_id.clone())); - ToolResponseAttribution { - tool_event_type, - cell_id: cell.is_some().then_some(cell_id).flatten(), - parent_call_id, - originating_response_id, - } -} - -fn item_review_summary_key(pending_review: &PendingReviewState) -> Option { - match pending_review.subject_kind { - ReviewSubjectKind::CommandExecution - | ReviewSubjectKind::FileChange - | ReviewSubjectKind::McpToolCall => Some(ToolItemKey { - thread_id: pending_review.thread_id.clone(), - turn_id: pending_review.turn_id.clone(), - item_id: pending_review.item_id.clone()?, - }), - ReviewSubjectKind::WriteStdin - | ReviewSubjectKind::Permissions - | ReviewSubjectKind::NetworkAccess => None, - } -} - -struct ToolItemEventInput<'a> { - thread_id: &'a str, - turn_id: &'a str, - item: &'a ThreadItemPayload, - model_context: Option<&'a ModelInvocationContext>, - started_at_ms: u64, - completed_at_ms: u64, - connection_state: &'a ConnectionState, - thread_state: &'a ThreadAnalyticsState, - thread_metadata: &'a ThreadMetadataState, - review_summary: Option<&'a ItemReviewSummary>, - elicitation_type: Option, -} - -fn tool_item_event(input: ToolItemEventInput<'_>) -> Option { - let ToolItemEventInput { - thread_id, - turn_id, - item, - model_context, - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - elicitation_type, - } = input; - match item { - ThreadItemPayload::CommandExecution { - id, - sandbox_type, - plugin_id, - script_path, - source, - status, - command_actions, - exit_code, - duration_ms, - .. - } => { - let (terminal_status, failure_kind) = command_execution_outcome(status)?; - let action_counts = command_action_counts(command_actions); - let base = tool_item_base( - thread_id, - turn_id, - id.clone(), - command_execution_tool_name(*source).to_string(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: option_i64_to_u64(*duration_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::CommandExecution( - CodexCommandExecutionEventRequest { - event_type: "codex_command_execution_event", - event_params: CodexCommandExecutionEventParams { - sandbox_backend: sandbox_type - .map(|sandbox| sandbox.as_metric_tag().to_string()), - model_slug: model_context.map(|context| context.model_slug.clone()), - reasoning_effort: model_context - .and_then(|context| context.reasoning_effort.clone()), - base, - plugin_id: plugin_id.clone(), - script_path: safe_plugin_relative_script_path( - plugin_id.as_deref(), - script_path.as_deref(), - ), - command_execution_source: *source, - exit_code: *exit_code, - command_total_action_count: action_counts.total, - command_read_action_count: action_counts.read, - command_list_files_action_count: action_counts.list_files, - command_search_action_count: action_counts.search, - command_unknown_action_count: action_counts.unknown, - }, - }, - )) - } - ThreadItemPayload::FileChange { - id, - changes, - status, - } => { - let (terminal_status, failure_kind) = patch_apply_outcome(status)?; - let counts = file_change_counts(changes); - let base = tool_item_base( - thread_id, - turn_id, - id.clone(), - "apply_patch".to_string(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: None, - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::FileChange(CodexFileChangeEventRequest { - event_type: "codex_file_change_event", - event_params: CodexFileChangeEventParams { - base, - file_change_count: usize_to_u64(changes.len()), - file_add_count: counts.add, - file_update_count: counts.update, - file_delete_count: counts.delete, - file_move_count: counts.move_, - }, - })) - } - ThreadItemPayload::McpToolCall { - id, - server, - tool, - status, - error, - duration_ms, - plugin_id, - app_context, - .. - } => { - let (terminal_status, failure_kind) = mcp_tool_call_outcome(status)?; - let base = tool_item_base( - thread_id, - turn_id, - id.clone(), - tool.clone(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: option_i64_to_u64(*duration_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::McpToolCall( - CodexMcpToolCallEventRequest { - event_type: "codex_mcp_tool_call_event", - event_params: CodexMcpToolCallEventParams { - base, - mcp_server_name: server.clone(), - mcp_tool_name: tool.clone(), - mcp_error_present: error.is_some(), - plugin_id: plugin_id.clone(), - connector_id: app_context - .as_ref() - .map(|app_context| app_context.connector_id.clone()), - voice_session_id: None, - elicitation_type, - }, - }, - )) - } - ThreadItemPayload::DynamicToolCall { - id, - tool, - status, - content_items, - success, - duration_ms, - .. - } => { - let (terminal_status, failure_kind) = dynamic_tool_call_outcome(status)?; - let counts = content_items - .as_ref() - .map(|items| dynamic_content_counts(items)); - let base = tool_item_base( - thread_id, - turn_id, - id.clone(), - tool.clone(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: option_i64_to_u64(*duration_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::DynamicToolCall( - CodexDynamicToolCallEventRequest { - event_type: "codex_dynamic_tool_call_event", - event_params: CodexDynamicToolCallEventParams { - base, - dynamic_tool_name: tool.clone(), - success: *success, - output_content_item_count: counts.map(|counts| counts.total), - output_text_item_count: counts.map(|counts| counts.text), - output_image_item_count: counts.map(|counts| counts.image), - output_audio_item_count: counts.map(|counts| counts.audio), - }, - }, - )) - } - ThreadItemPayload::CollabAgentToolCall { - id, - tool, - status, - sender_thread_id, - receiver_thread_ids, - model, - reasoning_effort, - agents_states, - .. - } => { - let (terminal_status, failure_kind) = collab_tool_call_outcome(status)?; - let base = tool_item_base( - thread_id, - turn_id, - id.clone(), - collab_agent_tool_name(tool).to_string(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: observed_duration_ms(started_at_ms, completed_at_ms), - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::CollabAgentToolCall( - CodexCollabAgentToolCallEventRequest { - event_type: "codex_collab_agent_tool_call_event", - event_params: CodexCollabAgentToolCallEventParams { - base, - sender_thread_id: sender_thread_id.clone(), - receiver_thread_count: usize_to_u64(receiver_thread_ids.len()), - receiver_thread_ids: Some(receiver_thread_ids.clone()), - requested_model: model.clone(), - requested_reasoning_effort: reasoning_effort - .as_ref() - .and_then(serialize_enum_as_string), - agent_state_count: Some(usize_to_u64(agents_states.len())), - completed_agent_count: Some(usize_to_u64( - agents_states - .values() - .filter(|state| state.status == CollabAgentStatus::Completed) - .count(), - )), - failed_agent_count: Some(usize_to_u64( - agents_states - .values() - .filter(|state| { - matches!( - state.status, - CollabAgentStatus::Errored - | CollabAgentStatus::Shutdown - | CollabAgentStatus::NotFound - ) - }) - .count(), - )), - }, - }, - )) - } - ThreadItemPayload::WebSearch(item) => { - let base = tool_item_base( - thread_id, - turn_id, - item.id.clone(), - "web_search".to_string(), - ToolItemOutcome { - terminal_status: ToolItemTerminalStatus::Completed, - failure_kind: None, - execution_duration_ms: None, - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::WebSearch(CodexWebSearchEventRequest { - event_type: "codex_web_search_event", - event_params: CodexWebSearchEventParams { - base, - web_search_action: item.action.as_ref().map(web_search_action_kind), - query_present: !item.query.trim().is_empty(), - query_count: web_search_query_count(&item.query, item.action.as_ref()), - }, - })) - } - ThreadItemPayload::ImageGeneration(item) => { - let (terminal_status, failure_kind) = image_generation_outcome(item.status.as_str()); - let base = tool_item_base( - thread_id, - turn_id, - item.id.clone(), - "image_generation".to_string(), - ToolItemOutcome { - terminal_status, - failure_kind, - execution_duration_ms: None, - }, - ToolItemContext { - started_at_ms, - completed_at_ms, - connection_state, - thread_state, - thread_metadata, - review_summary, - }, - ); - Some(TrackEventRequest::ImageGeneration( - CodexImageGenerationEventRequest { - event_type: "codex_image_generation_event", - event_params: CodexImageGenerationEventParams { - base, - revised_prompt_present: item.revised_prompt.is_some(), - saved_path_present: item.saved_path.is_some(), - transparent_background: item.transparent_background, - imagegen_request_id: item.imagegen_request_id.clone(), - generation_id: item.generation_id.clone(), - }, - }, - )) - } - _ => None, - } -} - -fn safe_plugin_relative_script_path( - plugin_id: Option<&str>, - script_path: Option<&str>, -) -> Option { - let script_path = script_path.filter(|path| is_safe_plugin_relative_path(path))?; - plugin_id.map(|_| script_path.to_string()) -} - -struct ToolItemOutcome { - terminal_status: ToolItemTerminalStatus, - failure_kind: Option, - execution_duration_ms: Option, -} - -#[derive(Default)] -struct CommandActionCounts { - total: u64, - read: u64, - list_files: u64, - search: u64, - unknown: u64, -} - -fn command_action_counts(command_actions: &[CommandAction]) -> CommandActionCounts { - let mut counts = CommandActionCounts { - total: usize_to_u64(command_actions.len()), - ..Default::default() - }; - for action in command_actions { - match action { - CommandAction::Read { .. } => counts.read += 1, - CommandAction::ListFiles { .. } => counts.list_files += 1, - CommandAction::Search { .. } => counts.search += 1, - CommandAction::Unknown { .. } => counts.unknown += 1, - } - } - counts -} - -#[derive(Clone, Copy)] -struct ToolItemContext<'a> { - started_at_ms: u64, - completed_at_ms: u64, - connection_state: &'a ConnectionState, - thread_state: &'a ThreadAnalyticsState, - thread_metadata: &'a ThreadMetadataState, - review_summary: Option<&'a ItemReviewSummary>, -} - -fn tool_item_base( - thread_id: &str, - turn_id: &str, - item_id: String, - tool_name: String, - outcome: ToolItemOutcome, - context: ToolItemContext<'_>, -) -> CodexToolItemEventBase { - let thread_metadata = context.thread_metadata; - let review_summary = context.review_summary.cloned().unwrap_or_default(); - CodexToolItemEventBase { - thread_id: thread_id.to_string(), - session_id: thread_metadata.session_id.clone(), - turn_id: turn_id.to_string(), - turn_trigger: None, - root_turn_id: None, - item_id, - cell_id: None, - parent_call_id: None, - originating_response_id: None, - subsequent_response_id: None, - app_server_client: context - .thread_state - .app_server_client(context.connection_state), - runtime: context.connection_state.runtime.clone(), - thread_source: thread_metadata.thread_source.clone(), - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id.clone(), - tool_name, - tool_event_type: None, - started_at_ms: context.started_at_ms, - completed_at_ms: context.completed_at_ms, - // duration_ms reflects item lifecycle observed by app-server. For web - // search and image generation in particular, that can be narrower than - // full upstream execution time. - duration_ms: observed_duration_ms(context.started_at_ms, context.completed_at_ms), - execution_duration_ms: outcome.execution_duration_ms, - review_count: review_summary.review_count, - guardian_review_count: review_summary.guardian_review_count, - user_review_count: review_summary.user_review_count, - final_approval_outcome: review_summary - .final_approval_outcome - .unwrap_or(FinalApprovalOutcome::Unknown), - terminal_status: outcome.terminal_status, - failure_kind: outcome.failure_kind, - requested_additional_permissions: review_summary.requested_additional_permissions, - requested_network_access: review_summary.requested_network_access, - } -} - -fn observed_duration_ms(started_at_ms: u64, completed_at_ms: u64) -> Option { - completed_at_ms.checked_sub(started_at_ms) -} - -fn user_review_id(request_id: &RequestId) -> String { - format!("user:{request_id}") -} - -fn command_execution_review_result( - decision: CommandExecutionApprovalDecision, -) -> (ReviewStatus, ReviewResolution) { - match decision { - CommandExecutionApprovalDecision::Accept => { - (ReviewStatus::Approved, ReviewResolution::None) - } - CommandExecutionApprovalDecision::AcceptForSession => { - (ReviewStatus::Approved, ReviewResolution::SessionApproval) - } - CommandExecutionApprovalDecision::AcceptWithExecpolicyAmendment { .. } => ( - ReviewStatus::Approved, - ReviewResolution::ExecPolicyAmendment, - ), - CommandExecutionApprovalDecision::ApplyNetworkPolicyAmendment { - network_policy_amendment, - } => match network_policy_amendment.action { - NetworkPolicyRuleAction::Allow => ( - ReviewStatus::Approved, - ReviewResolution::NetworkPolicyAmendment, - ), - NetworkPolicyRuleAction::Deny => ( - ReviewStatus::Denied, - ReviewResolution::NetworkPolicyAmendment, - ), - }, - CommandExecutionApprovalDecision::Decline => (ReviewStatus::Denied, ReviewResolution::None), - CommandExecutionApprovalDecision::Cancel => (ReviewStatus::Aborted, ReviewResolution::None), - } -} - -fn file_change_review_result( - decision: FileChangeApprovalDecision, -) -> (ReviewStatus, ReviewResolution) { - match decision { - FileChangeApprovalDecision::Accept => (ReviewStatus::Approved, ReviewResolution::None), - FileChangeApprovalDecision::AcceptForSession => { - (ReviewStatus::Approved, ReviewResolution::SessionApproval) - } - FileChangeApprovalDecision::Decline => (ReviewStatus::Denied, ReviewResolution::None), - FileChangeApprovalDecision::Cancel => (ReviewStatus::Aborted, ReviewResolution::None), - } -} - -fn effective_permissions_review_result( - response: &CoreRequestPermissionsResponse, -) -> (ReviewStatus, ReviewResolution) { - if response.permissions.is_empty() { - return (ReviewStatus::Denied, ReviewResolution::None); - } - - match response.scope { - CorePermissionGrantScope::Turn => (ReviewStatus::Approved, ReviewResolution::None), - CorePermissionGrantScope::Session => { - (ReviewStatus::Approved, ReviewResolution::SessionApproval) - } - } -} - -fn guardian_review_result( - status: GuardianApprovalReviewStatus, -) -> Option<(ReviewStatus, ReviewResolution)> { - match status { - GuardianApprovalReviewStatus::InProgress => None, - GuardianApprovalReviewStatus::Approved => { - Some((ReviewStatus::Approved, ReviewResolution::None)) - } - GuardianApprovalReviewStatus::Denied => { - Some((ReviewStatus::Denied, ReviewResolution::None)) - } - GuardianApprovalReviewStatus::TimedOut => { - Some((ReviewStatus::TimedOut, ReviewResolution::None)) - } - GuardianApprovalReviewStatus::Aborted => { - Some((ReviewStatus::Aborted, ReviewResolution::None)) - } - } -} - -fn guardian_review_subject_metadata( - action: &GuardianApprovalReviewAction, -) -> (ReviewSubjectKind, String, ReviewTrigger) { - match action { - GuardianApprovalReviewAction::Command { .. } => ( - ReviewSubjectKind::CommandExecution, - "command_execution".to_string(), - ReviewTrigger::Initial, - ), - GuardianApprovalReviewAction::WriteStdin { .. } => ( - ReviewSubjectKind::WriteStdin, - "write_stdin".to_string(), - ReviewTrigger::Initial, - ), - GuardianApprovalReviewAction::Execve { .. } => ( - ReviewSubjectKind::CommandExecution, - "command_execution".to_string(), - ReviewTrigger::ExecveIntercept, - ), - GuardianApprovalReviewAction::ApplyPatch { .. } => ( - ReviewSubjectKind::FileChange, - "apply_patch".to_string(), - ReviewTrigger::SandboxDenial, - ), - GuardianApprovalReviewAction::NetworkAccess { .. } => ( - ReviewSubjectKind::NetworkAccess, - "network_access".to_string(), - ReviewTrigger::NetworkPolicyDenial, - ), - GuardianApprovalReviewAction::RequestPermissions { permissions, .. } => { - let requested_network_access = permissions - .network - .as_ref() - .and_then(|network| network.enabled) - .unwrap_or(false); - let trigger = if requested_network_access { - ReviewTrigger::NetworkPolicyDenial - } else if permissions.file_system.is_some() { - ReviewTrigger::SandboxDenial - } else { - ReviewTrigger::Initial - }; - ( - ReviewSubjectKind::Permissions, - "permissions".to_string(), - trigger, - ) - } - GuardianApprovalReviewAction::McpToolCall { tool_name, .. } => ( - ReviewSubjectKind::McpToolCall, - tool_name.clone(), - ReviewTrigger::Initial, - ), - } -} - -fn guardian_review_requested_additional_permissions(action: &GuardianApprovalReviewAction) -> bool { - match action { - GuardianApprovalReviewAction::ApplyPatch { .. } - | GuardianApprovalReviewAction::NetworkAccess { .. } => true, - GuardianApprovalReviewAction::RequestPermissions { permissions, .. } => { - guardian_review_request_permissions_network_enabled(permissions) - || permissions.file_system.is_some() - } - GuardianApprovalReviewAction::Command { .. } - | GuardianApprovalReviewAction::WriteStdin { .. } - | GuardianApprovalReviewAction::Execve { .. } - | GuardianApprovalReviewAction::McpToolCall { .. } => false, - } -} - -fn guardian_review_requested_network_access(action: &GuardianApprovalReviewAction) -> bool { - match action { - GuardianApprovalReviewAction::NetworkAccess { .. } => true, - GuardianApprovalReviewAction::RequestPermissions { permissions, .. } => { - guardian_review_request_permissions_network_enabled(permissions) - } - GuardianApprovalReviewAction::ApplyPatch { .. } - | GuardianApprovalReviewAction::Command { .. } - | GuardianApprovalReviewAction::WriteStdin { .. } - | GuardianApprovalReviewAction::Execve { .. } - | GuardianApprovalReviewAction::McpToolCall { .. } => false, - } -} - -fn guardian_review_request_permissions_network_enabled( - permissions: &RequestPermissionProfile, -) -> bool { - permissions - .network - .as_ref() - .and_then(|network| network.enabled) - .unwrap_or(false) -} - -fn final_approval_outcome( - reviewer: Reviewer, - status: ReviewStatus, - resolution: ReviewResolution, -) -> FinalApprovalOutcome { - match (reviewer, status, resolution) { - (Reviewer::Guardian, ReviewStatus::Approved, _) => FinalApprovalOutcome::GuardianApproved, - (Reviewer::Guardian, ReviewStatus::Denied, _) => FinalApprovalOutcome::GuardianDenied, - (Reviewer::Guardian, _, _) => FinalApprovalOutcome::GuardianAborted, - (Reviewer::User, ReviewStatus::Approved, ReviewResolution::SessionApproval) => { - FinalApprovalOutcome::UserApprovedForSession - } - (Reviewer::User, ReviewStatus::Approved, _) => FinalApprovalOutcome::UserApproved, - (Reviewer::User, ReviewStatus::Denied, _) => FinalApprovalOutcome::UserDenied, - (Reviewer::User, _, _) => FinalApprovalOutcome::UserAborted, - } -} - -fn command_execution_tool_name(source: CommandExecutionSource) -> &'static str { - match source { - CommandExecutionSource::UnifiedExecStartup - | CommandExecutionSource::UnifiedExecInteraction => "unified_exec", - CommandExecutionSource::UserShell => "user_shell", - CommandExecutionSource::Agent => "shell", - } -} - -fn command_execution_outcome( - status: &CommandExecutionStatus, -) -> Option<(ToolItemTerminalStatus, Option)> { - match status { - CommandExecutionStatus::InProgress => None, - CommandExecutionStatus::Completed => Some((ToolItemTerminalStatus::Completed, None)), - CommandExecutionStatus::Failed => Some(( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - )), - CommandExecutionStatus::Declined => Some(( - ToolItemTerminalStatus::Rejected, - Some(ToolItemFailureKind::ApprovalDenied), - )), - } -} - -fn patch_apply_outcome( - status: &PatchApplyStatus, -) -> Option<(ToolItemTerminalStatus, Option)> { - match status { - PatchApplyStatus::InProgress => None, - PatchApplyStatus::Completed => Some((ToolItemTerminalStatus::Completed, None)), - PatchApplyStatus::Failed => Some(( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - )), - PatchApplyStatus::Declined => Some(( - ToolItemTerminalStatus::Rejected, - Some(ToolItemFailureKind::ApprovalDenied), - )), - } -} - -fn mcp_tool_call_outcome( - status: &McpToolCallStatus, -) -> Option<(ToolItemTerminalStatus, Option)> { - match status { - McpToolCallStatus::InProgress => None, - McpToolCallStatus::Completed => Some((ToolItemTerminalStatus::Completed, None)), - McpToolCallStatus::Failed => Some(( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - )), - } -} - -fn dynamic_tool_call_outcome( - status: &DynamicToolCallStatus, -) -> Option<(ToolItemTerminalStatus, Option)> { - match status { - DynamicToolCallStatus::InProgress => None, - DynamicToolCallStatus::Completed => Some((ToolItemTerminalStatus::Completed, None)), - DynamicToolCallStatus::Failed => Some(( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - )), - } -} - -fn collab_tool_call_outcome( - status: &CollabAgentToolCallStatus, -) -> Option<(ToolItemTerminalStatus, Option)> { - match status { - CollabAgentToolCallStatus::InProgress => None, - CollabAgentToolCallStatus::Completed => Some((ToolItemTerminalStatus::Completed, None)), - CollabAgentToolCallStatus::Interrupted => Some((ToolItemTerminalStatus::Interrupted, None)), - CollabAgentToolCallStatus::Failed => Some(( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - )), - } -} - -fn image_generation_outcome(status: &str) -> (ToolItemTerminalStatus, Option) { - match status { - "failed" | "error" => ( - ToolItemTerminalStatus::Failed, - Some(ToolItemFailureKind::ToolError), - ), - _ => (ToolItemTerminalStatus::Completed, None), - } -} - -fn collab_agent_tool_name(tool: &CollabAgentTool) -> &'static str { - match tool { - CollabAgentTool::SpawnAgent => "spawn_agent", - CollabAgentTool::SendInput => "send_input", - CollabAgentTool::ResumeAgent => "resume_agent", - CollabAgentTool::Wait => "wait_agent", - CollabAgentTool::CloseAgent => "close_agent", - CollabAgentTool::SendMessage => "send_message", - CollabAgentTool::FollowupTask => "followup_task", - CollabAgentTool::InterruptAgent => "interrupt_agent", - CollabAgentTool::ListAgents => "list_agents", - } -} - -#[derive(Default)] -struct FileChangeCounts { - add: u64, - update: u64, - delete: u64, - move_: u64, -} - -fn file_change_counts(changes: &[codex_app_server_protocol::FileUpdateChange]) -> FileChangeCounts { - let mut counts = FileChangeCounts::default(); - for change in changes { - match &change.kind { - PatchChangeKind::Add => counts.add += 1, - PatchChangeKind::Delete => counts.delete += 1, - PatchChangeKind::Update { move_path: Some(_) } => counts.move_ += 1, - PatchChangeKind::Update { move_path: None } => counts.update += 1, - } - } - counts -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct DynamicContentCounts { - total: u64, - text: u64, - image: u64, - audio: u64, -} - -fn dynamic_content_counts(items: &[DynamicToolCallOutputContentItem]) -> DynamicContentCounts { - let mut text = 0; - let mut image = 0; - let mut audio = 0; - for item in items { - match item { - DynamicToolCallOutputContentItem::InputText { .. } => text += 1, - DynamicToolCallOutputContentItem::InputImage { .. } => image += 1, - DynamicToolCallOutputContentItem::InputAudio { .. } => audio += 1, - } - } - DynamicContentCounts { - total: usize_to_u64(items.len()), - text, - image, - audio, - } -} - -fn web_search_action_kind(action: &WebSearchAction) -> WebSearchActionKind { - match action { - WebSearchAction::Search { .. } => WebSearchActionKind::Search, - WebSearchAction::OpenPage { .. } => WebSearchActionKind::OpenPage, - WebSearchAction::FindInPage { .. } => WebSearchActionKind::FindInPage, - WebSearchAction::Other => WebSearchActionKind::Other, - } -} - -fn web_search_query_count(query: &str, action: Option<&WebSearchAction>) -> Option { - match action { - Some(WebSearchAction::Search { query, queries }) => queries - .as_ref() - .map(|queries| usize_to_u64(queries.len())) - .or_else(|| query.as_ref().map(|_| 1)), - Some(WebSearchAction::OpenPage { .. }) - | Some(WebSearchAction::FindInPage { .. }) - | Some(WebSearchAction::Other) => None, - None => (!query.trim().is_empty()).then_some(1), - } -} - -fn accepted_line_event_input( - turn_id: &str, - turn_state: &TurnState, -) -> Option<(AcceptedLineFingerprintEventInput, PathBuf)> { - let latest_diff = turn_state.latest_diff.as_deref()?; - let summary = accepted_line_counts_from_unified_diff(latest_diff); - if summary.accepted_added_lines == 0 && summary.accepted_deleted_lines == 0 { - return None; - } - - let thread_id = turn_state.thread_id.clone()?; - let resolved_config = turn_state.resolved_config.clone()?; - - Some(( - AcceptedLineFingerprintEventInput { - event_type: "codex.accepted_line_fingerprints", - turn_id: turn_id.to_string(), - thread_id, - product_surface: Some("codex".to_string()), - model_slug: Some(resolved_config.model.clone()), - completed_at: now_unix_seconds(), - repo_hash: None, - accepted_added_lines: summary.accepted_added_lines, - accepted_deleted_lines: summary.accepted_deleted_lines, - }, - resolved_config.permission_profile_cwd, - )) -} - -fn codex_turn_event_params( - app_server_client: CodexAppServerClientMetadata, - runtime: CodexRuntimeMetadata, - turn_id: String, - turn_state: &TurnState, - thread_metadata: &ThreadMetadataState, -) -> CodexTurnEventParams { - let ( - Some(thread_id), - Some(num_input_images), - Some(resolved_config), - Some(profile), - Some(completed), - ) = ( - turn_state.thread_id.clone(), - turn_state.num_input_images, - turn_state.resolved_config.clone(), - turn_state.profile.clone(), - turn_state.completed.clone(), - ) - else { - unreachable!("turn event params require a fully populated turn state"); - }; - let started_at = turn_state.started_at; - let TurnResolvedConfigFact { - turn_id: _resolved_turn_id, - thread_id: _resolved_thread_id, - turn_metadata, - active_plugin_ids_at_turn_start, - num_input_images: _resolved_num_input_images, - submission_type, - ephemeral, - session_source: _session_source, - model, - model_provider, - permission_profile, - permission_profile_cwd, - reasoning_effort, - reasoning_summary, - service_tier, - approval_policy, - approvals_reviewer, - guardian_v2_enabled, - multi_agent_version, - sandbox_network_access, - collaboration_mode, - personality, - workspace_kind, - is_first_turn, - } = resolved_config; - let TurnProfile { - critical_path, - before_first_sampling_ms, - sampling_ms, - compaction_ms, - between_sampling_overhead_ms, - tool_blocking_ms, - after_last_sampling_ms, - sampling_request_count, - sampling_retry_count, - tools_change_count, - } = profile; - let token_usage = turn_state.token_usage.clone(); - let codex_error = turn_state.codex_error.as_ref(); - CodexTurnEventParams { - critical_path: critical_path.into(), - thread_id, - session_id: thread_metadata.session_id.clone(), - turn_id, - active_plugin_ids_at_turn_start, - voice_session_id: turn_state.voice_session_id.clone(), - root_turn_id: turn_metadata.root_turn_id(), - turn_trigger: turn_metadata.turn_trigger(), - codex_turn_source: turn_metadata.codex_turn_source(), - app_server_client, - runtime, - submission_type, - ephemeral, - thread_source: thread_metadata.thread_source.clone(), - initialization_mode: thread_metadata.initialization_mode, - subagent_source: thread_metadata.subagent_source.clone(), - parent_thread_id: thread_metadata.parent_thread_id.clone(), - model: Some(model), - model_provider, - sandbox_policy: Some(sandbox_policy_mode( - &permission_profile, - permission_profile_cwd.as_path(), - )), - reasoning_effort: reasoning_effort.map(|value| value.to_string()), - reasoning_summary: reasoning_summary_mode(reasoning_summary), - service_tier: service_tier - .map(|value| value.to_string()) - .unwrap_or_else(|| "default".to_string()), - approval_policy: approval_policy.to_string(), - approvals_reviewer: approvals_reviewer.to_string(), - guardian_v2_enabled, - multi_agent_version, - sandbox_network_access, - collaboration_mode: Some(collaboration_mode_mode(collaboration_mode)), - personality: personality_mode(personality), - workspace_kind, - num_input_images, - image_preparations: turn_state.image_preparations.clone(), - is_first_turn, - status: completed.status, - explicit_client_interrupt_requested_at_ms: turn_state - .explicit_client_interrupt_requested_at_ms, - turn_error: completed.turn_error, - codex_error_kind: codex_error.map(|error| error.kind), - codex_error_http_status_code: codex_error.and_then(|error| error.http_status_code), - usage_limit_window_minutes: codex_error.and_then(|error| error.usage_limit_window_minutes), - steer_count: Some(turn_state.steer_count), - total_tool_call_count: Some(turn_state.tool_counts.total), - shell_command_count: Some(turn_state.tool_counts.shell_command), - file_change_count: Some(turn_state.tool_counts.file_change), - mcp_tool_call_count: Some(turn_state.tool_counts.mcp_tool_call), - dynamic_tool_call_count: Some(turn_state.tool_counts.dynamic_tool_call), - subagent_tool_call_count: Some(turn_state.tool_counts.subagent_tool_call), - web_search_count: Some(turn_state.tool_counts.web_search), - image_generation_count: Some(turn_state.tool_counts.image_generation), - input_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.input_tokens), - cached_input_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.cached_input_tokens), - cache_write_input_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.cache_write_input_tokens), - output_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.output_tokens), - reasoning_output_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.reasoning_output_tokens), - total_tokens: token_usage - .as_ref() - .map(|token_usage| token_usage.total_tokens), - before_first_sampling_ms, - sampling_ms, - compaction_ms, - between_sampling_overhead_ms, - tool_blocking_ms, - after_last_sampling_ms, - sampling_request_count, - sampling_retry_count, - tools_change_count, - duration_ms: completed.duration_ms, - started_at, - completed_at: Some(completed.completed_at), - } -} - -fn sandbox_policy_mode(permission_profile: &PermissionProfile, cwd: &Path) -> &'static str { - match permission_profile { - PermissionProfile::Disabled => "full_access", - PermissionProfile::External { .. } => "external_sandbox", - PermissionProfile::Managed { .. } => { - let file_system_policy = permission_profile.file_system_sandbox_policy(); - if file_system_policy.has_full_disk_write_access() { - if permission_profile.network_sandbox_policy().is_enabled() { - "full_access" - } else { - "external_sandbox" - } - } else if file_system_policy - .get_writable_roots_with_cwd(cwd) - .is_empty() - { - "read_only" - } else { - "workspace_write" - } - } - } -} - -fn collaboration_mode_mode(mode: ModeKind) -> &'static str { - match mode { - ModeKind::Plan => "plan", - ModeKind::Default => "default", - } -} - -fn reasoning_summary_mode(summary: Option) -> Option { - match summary { - Some(ReasoningSummary::None) | None => None, - Some(summary) => Some(summary.to_string()), - } -} - -fn personality_mode(personality: Option) -> Option { - match personality { - Some(Personality::None) | None => None, - Some(personality) => Some(personality.to_string()), - } -} - -fn analytics_turn_status(status: codex_app_server_protocol::TurnStatus) -> Option { - match status { - codex_app_server_protocol::TurnStatus::Completed => Some(TurnStatus::Completed), - codex_app_server_protocol::TurnStatus::Failed => Some(TurnStatus::Failed), - codex_app_server_protocol::TurnStatus::Interrupted => Some(TurnStatus::Interrupted), - codex_app_server_protocol::TurnStatus::InProgress => None, - } -} - -fn num_input_images(input: &[UserInput]) -> usize { - input - .iter() - .filter(|item| matches!(item, UserInput::Image { .. } | UserInput::LocalImage { .. })) - .count() -} - -fn rejection_reason_from_error_type( - error_type: Option, -) -> Option { - match error_type? { - AnalyticsJsonRpcError::TurnSteer(error) => Some(error.into()), - AnalyticsJsonRpcError::Input(error) => Some(error.into()), - } -} - -pub(crate) fn skill_id_for_local_skill( - repo_url: Option<&str>, - repo_root: Option<&Path>, - skill_path: &PathUri, - skill_name: &str, -) -> String { - let path = normalize_path_for_skill_id(repo_url, repo_root, skill_path); - let prefix = if let Some(url) = repo_url { - format!("repo_{url}") - } else { - "personal".to_string() - }; - let raw_id = format!("{prefix}_{path}_{skill_name}"); - let mut hasher = sha1::Sha1::new(); - sha1::Digest::update(&mut hasher, raw_id.as_bytes()); - format!("{:x}", sha1::Digest::finalize(hasher)) -} - -/// Returns a normalized path for skill ID construction. -/// -/// - Repo-scoped skills use a path relative to the repo root. -/// - User/admin/system skills use an absolute path. -pub(crate) fn normalize_path_for_skill_id( - repo_url: Option<&str>, - repo_root: Option<&Path>, - skill_path: &PathUri, -) -> String { - // Foreign paths have no host repository to inspect; retain their native spelling for telemetry. - let Ok(skill_path) = skill_path.to_abs_path() else { - return skill_path.inferred_native_path_string().replace('\\', "/"); - }; - let resolved_path = - std::fs::canonicalize(skill_path.as_path()).unwrap_or_else(|_| skill_path.to_path_buf()); - match (repo_url, repo_root) { - (Some(_), Some(root)) => { - let resolved_root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); - resolved_path - .strip_prefix(&resolved_root) - .unwrap_or(resolved_path.as_path()) - .to_string_lossy() - .replace('\\', "/") - } - _ => resolved_path.to_string_lossy().replace('\\', "/"), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use codex_app_server_protocol::ItemCompletedNotification; - use codex_app_server_protocol::JSONRPCErrorError; - use codex_app_server_protocol::ThreadClosedNotification; - use codex_protocol::models::SandboxEnforcement; - use codex_protocol::permissions::FileSystemSandboxPolicy; - use codex_protocol::permissions::NetworkSandboxPolicy; - use pretty_assertions::assert_eq; - - #[tokio::test] - async fn pending_classifications_evict_oldest_and_clean_up() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let keys = (0..=MAX_TOOL_RESPONSE_ENTRIES) - .map(|index| ToolItemKey { - thread_id: if index == MAX_TOOL_RESPONSE_ENTRIES { - "other-thread" - } else { - "thread" - } - .to_string(), - turn_id: "turn".to_string(), - item_id: index.to_string(), - }) - .collect::>(); - let assert_pending = |reducer: &AnalyticsReducer, keys: &[ToolItemKey]| { - let expected = keys - .iter() - .cloned() - .map(|key| (key, ElicitationType::AuthOrLink)) - .collect::>(); - assert!(reducer.pending_mcp_tool_elicitations == expected); - }; - for key in &keys { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::McpToolCallElicitation( - McpToolCallElicitation { - thread_id: key.thread_id.clone(), - turn_id: key.turn_id.clone(), - item_id: key.item_id.clone(), - elicitation_type: ElicitationType::AuthOrLink, - }, - )), - &mut events, - ) - .await; - } - assert_pending(&reducer, &keys[1..]); - - // A duplicate at capacity keeps the first value and original arrival order. - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::McpToolCallElicitation( - McpToolCallElicitation { - thread_id: keys[1].thread_id.clone(), - turn_id: keys[1].turn_id.clone(), - item_id: keys[1].item_id.clone(), - elicitation_type: ElicitationType::Approval, - }, - )), - &mut events, - ) - .await; - assert_pending(&reducer, &keys[1..]); - - // Out-of-order completion consumes its marker even without turn context. - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - keys[2].thread_id.clone(), - keys[2].turn_id.clone(), - ThreadItemPayload::McpToolCall { - id: keys[2].item_id.clone(), - server: "server".to_string(), - tool: "tool".to_string(), - status: McpToolCallStatus::Failed, - arguments: serde_json::json!({}), - app_context: None, - mcp_app_resource_uri: None, - mcp_app_ui: None, - plugin_id: None, - read_only_hint: None, - result: None, - error: None, - duration_ms: None, - }, - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut events, - ) - .await; - let mut remaining = keys[1..].to_vec(); - remaining.remove(1); - assert_pending(&reducer, &remaining); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadClosed( - ThreadClosedNotification { - thread_id: "thread".to_string(), - }, - ))), - &mut events, - ) - .await; - assert_pending(&reducer, &keys[MAX_TOOL_RESPONSE_ENTRIES..]); - assert!(events.is_empty()); - } - - #[tokio::test] - async fn rejected_turn_interrupt_removes_pending_analytics_request() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - let connection_id = 7; - let request_id = RequestId::Integer(4); - let request_key = (connection_id, request_id.clone()); - - reducer - .ingest( - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id, - request_id: request_id.clone(), - turn_id: "turn-2".to_string(), - requested_at_ms: 1716000000123, - }, - &mut out, - ) - .await; - - assert!(reducer.requests.contains_key(&request_key)); - - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id, - request_id, - error: JSONRPCErrorError { - code: -32600, - message: "no active turn to interrupt".to_string(), - data: None, - }, - error_type: None, - }, - &mut out, - ) - .await; - - assert!(!reducer.requests.contains_key(&request_key)); - assert!(out.is_empty()); - } - - #[test] - fn managed_full_disk_with_restricted_network_reports_external_sandbox() { - let permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - SandboxEnforcement::Managed, - &FileSystemSandboxPolicy::unrestricted(), - NetworkSandboxPolicy::Restricted, - ); - - assert_eq!( - sandbox_policy_mode(&permission_profile, Path::new("/")), - "external_sandbox" - ); - } - - #[test] - fn guardian_review_result_maps_terminal_statuses() { - assert!(guardian_review_result(GuardianApprovalReviewStatus::InProgress).is_none()); - assert!(matches!( - guardian_review_result(GuardianApprovalReviewStatus::TimedOut), - Some((ReviewStatus::TimedOut, ReviewResolution::None)) - )); - } - - #[test] - fn dynamic_content_counts_include_audio() { - let items = vec![ - DynamicToolCallOutputContentItem::InputText { - text: "ok".to_string(), - }, - DynamicToolCallOutputContentItem::InputImage { - image_url: "data:image/png;base64,AAA".to_string(), - }, - DynamicToolCallOutputContentItem::InputAudio { - audio_url: "data:audio/wav;base64,YXVkaW8=".to_string(), - }, - ]; - - assert_eq!( - dynamic_content_counts(&items), - DynamicContentCounts { - total: 3, - text: 1, - image: 1, - audio: 1, - } - ); - } - - #[test] - fn command_execution_script_paths_reject_unsafe_values() { - assert_eq!( - safe_plugin_relative_script_path( - Some("sample@openai-curated"), - Some("/home/user/.codex/plugins/cache/openai-curated/sample/scripts/run.py"), - ), - None - ); - assert_eq!( - safe_plugin_relative_script_path(Some("sample@openai-curated"), Some("scripts/run.py"),), - Some("scripts/run.py".to_string()) - ); - assert_eq!( - safe_plugin_relative_script_path(/*plugin_id*/ None, Some("scripts/run.py"),), - None - ); - } -} diff --git a/codex-rs/analytics/src/tests/mod.rs b/codex-rs/analytics/src/tests/mod.rs deleted file mode 100644 index 4477e258..00000000 --- a/codex-rs/analytics/src/tests/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod suite; -mod support; diff --git a/codex-rs/analytics/src/tests/suite/approvals_tests.rs b/codex-rs/analytics/src/tests/suite/approvals_tests.rs deleted file mode 100644 index c49a7570..00000000 --- a/codex-rs/analytics/src/tests/suite/approvals_tests.rs +++ /dev/null @@ -1,1097 +0,0 @@ -//! User and Guardian approval events, item summaries, and permission privacy tests. - -use crate::GuardianAdditionalPermissions; -use crate::GuardianApprovalRequestSource; -use crate::GuardianReviewDecision; -use crate::GuardianReviewEventParams; -use crate::GuardianReviewFailureReason; -use crate::GuardianReviewTerminalStatus; -use crate::GuardianReviewedAction; -use crate::events::AppServerRpcTransport; -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexReviewEventParams; -use crate::events::CodexReviewEventRequest; -use crate::events::CodexRuntimeMetadata; -use crate::events::ReviewResolution; -use crate::events::ReviewStatus; -use crate::events::ReviewSubjectKind; -use crate::events::ReviewTrigger; -use crate::events::Reviewer; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::CodexCompactionEvent; -use crate::facts::CompactionImplementation; -use crate::facts::CompactionPhase; -use crate::facts::CompactionReason; -use crate::facts::CompactionStatus; -use crate::facts::CompactionStrategy; -use crate::facts::CompactionTrigger; -use crate::facts::CustomAnalyticsFact; -use crate::facts::SubAgentThreadStartedInput; -use crate::facts::ThreadInitializationMode; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::ingest_complete_child_turn; -use crate::tests::support::ingest_completed_command_execution_item; -use crate::tests::support::ingest_review_prerequisites; -use crate::tests::support::sample_initialize_fact; -use crate::tests::support::sample_runtime_metadata; -use crate::tests::support::sample_thread_start_response; -use crate::tests::support::sample_turn_start_request; -use crate::tests::support::sample_turn_start_response; -use crate::tests::support::sample_turn_token_usage_fact; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::CommandExecutionApprovalDecision; -use codex_app_server_protocol::CommandExecutionRequestApprovalParams; -use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; -use codex_app_server_protocol::GuardianApprovalReview; -use codex_app_server_protocol::GuardianApprovalReviewAction; -use codex_app_server_protocol::GuardianApprovalReviewStatus; -use codex_app_server_protocol::GuardianCommandSource as AppServerGuardianCommandSource; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification; -use codex_app_server_protocol::PermissionsRequestApprovalParams; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::RequestPermissionProfile; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ServerResponse; -use codex_app_server_protocol::ThreadClosedNotification; -use codex_login::default_client::DEFAULT_ORIGINATOR; -use codex_protocol::approvals::NetworkApprovalProtocol; -use codex_protocol::models::AdditionalPermissionProfile; -use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions; -use codex_protocol::models::SandboxPermissions; -use codex_protocol::protocol::GuardianCommandSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadSource; -use codex_protocol::request_permissions::PermissionGrantScope as CorePermissionGrantScope; -use codex_protocol::request_permissions::RequestPermissionProfile as CoreRequestPermissionProfile; -use codex_protocol::request_permissions::RequestPermissionsResponse as CoreRequestPermissionsResponse; -use codex_utils_absolute_path::test_support::PathBufExt; -use codex_utils_absolute_path::test_support::test_path_buf; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn sample_command_approval_request(request_id: i64, approval_id: Option<&str>) -> ServerRequest { - ServerRequest::CommandExecutionRequestApproval { - request_id: RequestId::Integer(request_id), - params: CommandExecutionRequestApprovalParams { - kind: Default::default(), - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "item-1".to_string(), - started_at_ms: 1_000, - approval_id: approval_id.map(str::to_string), - environment_id: None, - reason: None, - network_approval_context: None, - command: Some("echo hi".to_string()), - cwd: None, - command_actions: None, - additional_permissions: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, - available_decisions: None, - }, - } -} - -fn sample_command_approval_response( - request_id: i64, - decision: CommandExecutionApprovalDecision, -) -> ServerResponse { - ServerResponse::CommandExecutionRequestApproval { - request_id: RequestId::Integer(request_id), - response: CommandExecutionRequestApprovalResponse { decision }, - } -} - -fn sample_permissions_approval_request(request_id: i64) -> ServerRequest { - ServerRequest::PermissionsRequestApproval { - request_id: RequestId::Integer(request_id), - params: PermissionsRequestApprovalParams { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "permissions-1".to_string(), - environment_id: None, - started_at_ms: 1_000, - cwd: test_path_buf("/tmp").abs().into(), - reason: Some("need network".to_string()), - permissions: RequestPermissionProfile { - network: Some(codex_app_server_protocol::AdditionalNetworkPermissions { - enabled: Some(true), - }), - file_system: None, - }, - }, - } -} - -fn sample_effective_permissions_approval_response( - permissions: CoreRequestPermissionProfile, - scope: CorePermissionGrantScope, -) -> CoreRequestPermissionsResponse { - CoreRequestPermissionsResponse { - permissions, - scope, - strict_auto_review: false, - } -} - -fn sample_guardian_review_completed( - review_id: &str, - target_item_id: Option<&str>, - status: GuardianApprovalReviewStatus, - action: GuardianApprovalReviewAction, -) -> ServerNotification { - ServerNotification::ItemGuardianApprovalReviewCompleted( - ItemGuardianApprovalReviewCompletedNotification { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - started_at_ms: 1_000, - completed_at_ms: 1_042, - review_id: review_id.to_string(), - target_item_id: target_item_id.map(str::to_string), - decision_source: codex_app_server_protocol::AutoReviewDecisionSource::Agent, - review: GuardianApprovalReview { - status, - risk_level: None, - user_authorization: None, - rationale: None, - }, - action, - }, - ) -} - -#[test] -fn review_event_serializes_expected_shape() { - let event = TrackEventRequest::ReviewEvent(CodexReviewEventRequest { - event_type: "codex_review_event", - event_params: CodexReviewEventParams { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: None, - review_id: "review-1".to_string(), - app_server_client: CodexAppServerClientMetadata { - product_client_id: "codex_tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.2.3".to_string()), - rpc_transport: AppServerRpcTransport::Websocket, - experimental_api_enabled: Some(true), - }, - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.99.0".to_string(), - runtime_os: "macos".to_string(), - runtime_os_version: "15.3.1".to_string(), - runtime_arch: "aarch64".to_string(), - }, - thread_source: Some(ThreadSource::Subagent), - subagent_source: Some("thread_spawn".to_string()), - parent_thread_id: Some("parent-thread-1".to_string()), - subject_kind: ReviewSubjectKind::NetworkAccess, - subject_name: "network_access".to_string(), - reviewer: Reviewer::User, - trigger: ReviewTrigger::NetworkPolicyDenial, - status: ReviewStatus::Approved, - resolution: ReviewResolution::NetworkPolicyAmendment, - started_at_ms: 123, - completed_at_ms: 125, - duration_ms: Some(2), - }, - }); - - let payload = serde_json::to_value(&event).expect("serialize review event"); - assert_eq!( - payload, - json!({ - "event_type": "codex_review_event", - "event_params": { - "thread_id": "thread-1", - "turn_id": "turn-1", - "item_id": null, - "review_id": "review-1", - "app_server_client": { - "product_client_id": "codex_tui", - "client_name": "codex-tui", - "client_version": "1.2.3", - "rpc_transport": "websocket", - "experimental_api_enabled": true - }, - "runtime": { - "codex_rs_version": "0.99.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64" - }, - "thread_source": "subagent", - "subagent_source": "thread_spawn", - "parent_thread_id": "parent-thread-1", - "subject_kind": "network_access", - "subject_name": "network_access", - "reviewer": "user", - "trigger": "network_policy_denial", - "status": "approved", - "resolution": "network_policy_amendment", - "started_at_ms": 123, - "completed_at_ms": 125, - "duration_ms": 2 - } - }) - ); -} - -#[tokio::test] -async fn guardian_review_event_ingests_custom_fact_with_optional_target_item() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 7, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-tui".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: Some(InitializeCapabilities { - required_human_approval: false, - explicit_gateway_oauth: false, - experimental_api: false, - request_attestation: false, - opt_out_notification_methods: None, - mcp_server_openai_form_elicitation: false, - extensions: None, - }), - }, - product_client_id: DEFAULT_ORIGINATOR.to_string(), - runtime: sample_runtime_metadata(), - rpc_transport: AppServerRpcTransport::Websocket, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - "thread-guardian", - /*ephemeral*/ false, - "gpt-5", - )), - thread_originator: None, - }, - &mut events, - ) - .await; - events.clear(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::GuardianReview(Box::new( - GuardianReviewEventParams { - guardian_context_mode: None, - thread_id: "thread-guardian".to_string(), - turn_id: "turn-guardian".to_string(), - review_id: "review-guardian".to_string(), - target_item_id: None, - approval_request_source: GuardianApprovalRequestSource::DelegatedSubagent, - reviewed_action: GuardianReviewedAction::NetworkAccess { - protocol: NetworkApprovalProtocol::Https, - port: 443, - }, - reviewed_action_truncated: false, - decision: GuardianReviewDecision::Denied, - terminal_status: GuardianReviewTerminalStatus::TimedOut, - failure_reason: Some(GuardianReviewFailureReason::Timeout), - attempt_count: 1, - risk_level: None, - user_authorization: None, - outcome: None, - guardian_thread_id: None, - guardian_session_kind: None, - guardian_model: None, - guardian_reasoning_effort: None, - guardian_default_review_model_id: Some("codex-auto-review".to_string()), - guardian_catalog_contains_auto_review: Some(false), - guardian_review_model_overridden: Some(false), - guardian_review_model_override: None, - guardian_model_provider_id: Some("openai".to_string()), - had_prior_review_context: None, - review_timeout_ms: 90_000, - tool_call_count: None, - time_to_first_token_ms: None, - completion_latency_ms: Some(90_000), - started_at: 100, - completed_at: Some(190), - input_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - output_tokens: None, - reasoning_output_tokens: None, - total_tokens: None, - }, - ))), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_guardian_review"); - assert_eq!( - payload[0]["event_params"]["session_id"], - "session-thread-guardian" - ); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-guardian"); - assert_eq!(payload[0]["event_params"]["turn_id"], "turn-guardian"); - assert_eq!(payload[0]["event_params"]["review_id"], "review-guardian"); - assert_eq!(payload[0]["event_params"]["target_item_id"], json!(null)); - assert_eq!( - payload[0]["event_params"]["approval_request_source"], - "delegated_subagent" - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["product_client_id"], - DEFAULT_ORIGINATOR - ); - assert_eq!( - payload[0]["event_params"]["runtime"]["codex_rs_version"], - "0.1.0" - ); - assert_eq!( - payload[0]["event_params"]["reviewed_action"]["type"], - "network_access" - ); - assert_eq!( - payload[0]["event_params"]["reviewed_action"]["protocol"], - "https" - ); - assert_eq!(payload[0]["event_params"]["reviewed_action"]["port"], 443); - assert!(payload[0]["event_params"].get("retry_reason").is_none()); - assert!(payload[0]["event_params"].get("rationale").is_none()); - assert!( - payload[0]["event_params"]["reviewed_action"] - .get("target") - .is_none() - ); - assert!( - payload[0]["event_params"]["reviewed_action"] - .get("host") - .is_none() - ); - assert_eq!(payload[0]["event_params"]["terminal_status"], "timed_out"); - assert_eq!(payload[0]["event_params"]["failure_reason"], "timeout"); - assert_eq!(payload[0]["event_params"]["attempt_count"], 1); - assert_eq!(payload[0]["event_params"]["review_timeout_ms"], 90_000); - assert_eq!( - payload[0]["event_params"]["guardian_default_review_model_id"], - "codex-auto-review" - ); - assert_eq!( - payload[0]["event_params"]["guardian_catalog_contains_auto_review"], - false - ); - assert_eq!( - payload[0]["event_params"]["guardian_review_model_overridden"], - false - ); - assert_eq!( - payload[0]["event_params"]["guardian_review_model_override"], - json!(null) - ); - assert_eq!( - payload[0]["event_params"]["guardian_model_provider_id"], - "openai" - ); -} - -#[tokio::test] -async fn command_execution_approval_response_publishes_user_review_event() { - for (kind, approval_id, subject, trigger) in [ - (None, None, "command_execution", "initial"), - ( - None, - Some("execve-approval"), - "command_execution", - "execve_intercept", - ), - ( - Some("writeStdin"), - Some("stdin-approval"), - "write_stdin", - "initial", - ), - ] { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - let mut request = serde_json::to_value(sample_command_approval_request( - /*request_id*/ 41, - approval_id, - )) - .expect("serialize approval request"); - // Missing kind models requests from older app-servers. - if let Some(kind) = kind { - request["params"]["kind"] = json!(kind); - } else { - request["params"].as_object_mut().unwrap().remove("kind"); - } - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new( - serde_json::from_value(request).expect("deserialize approval request"), - ), - }, - &mut events, - ) - .await; - assert!(events.is_empty()); - - reducer - .ingest( - AnalyticsFact::ServerResponse { - completed_at_ms: 1_042, - response: Box::new(sample_command_approval_response( - /*request_id*/ 41, - CommandExecutionApprovalDecision::Accept, - )), - }, - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_review_event"); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-1"); - assert_eq!(payload[0]["event_params"]["turn_id"], "turn-1"); - assert_eq!(payload[0]["event_params"]["item_id"], "item-1"); - assert_eq!(payload[0]["event_params"]["review_id"], "user:41"); - assert_eq!(payload[0]["event_params"]["thread_source"], "user"); - assert_eq!(payload[0]["event_params"]["subject_kind"], subject); - assert_eq!(payload[0]["event_params"]["subject_name"], subject); - assert_eq!(payload[0]["event_params"]["reviewer"], "user"); - assert_eq!(payload[0]["event_params"]["trigger"], trigger); - assert_eq!(payload[0]["event_params"]["status"], "approved"); - assert_eq!(payload[0]["event_params"]["started_at_ms"], 1_000); - assert_eq!(payload[0]["event_params"]["completed_at_ms"], 1_042); - assert_eq!(payload[0]["event_params"]["duration_ms"], 42); - - // Stdin reviews must not count toward the parent command's approval summary. - events.clear(); - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "item-1") - .await; - let item = serde_json::to_value(&events[0]).expect("serialize tool item event"); - assert_eq!( - item["event_params"]["review_count"], - u64::from(kind.is_none()) - ); - } -} - -#[tokio::test] -async fn permissions_reviews_emit_events_without_denormalizing_onto_tool_items() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new(sample_permissions_approval_request(/*request_id*/ 51)), - }, - &mut events, - ) - .await; - assert!(events.is_empty()); - - reducer - .ingest( - AnalyticsFact::EffectivePermissionsApprovalResponse { - completed_at_ms: 1_042, - request_id: RequestId::Integer(51), - response: Box::new(sample_effective_permissions_approval_response( - CoreRequestPermissionProfile::default(), - CorePermissionGrantScope::Turn, - )), - }, - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_review_event"); - assert_eq!(payload[0]["event_params"]["review_id"], "user:51"); - assert_eq!(payload[0]["event_params"]["subject_kind"], "permissions"); - assert_eq!(payload[0]["event_params"]["reviewer"], "user"); - assert_eq!(payload[0]["event_params"]["status"], "denied"); - assert_eq!(payload[0]["event_params"]["resolution"], "none"); - - events.clear(); - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "permissions-1") - .await; - - let payload = serde_json::to_value(&events[0]).expect("serialize tool item event"); - assert_eq!(payload["event_params"]["item_id"], "permissions-1"); - assert_eq!(payload["event_params"]["review_count"], 0); - assert_eq!(payload["event_params"]["user_review_count"], 0); - assert_eq!(payload["event_params"]["guardian_review_count"], 0); -} - -#[tokio::test] -async fn effective_session_permissions_response_publishes_session_user_review_event() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new(sample_permissions_approval_request(/*request_id*/ 52)), - }, - &mut events, - ) - .await; - - reducer - .ingest( - AnalyticsFact::EffectivePermissionsApprovalResponse { - completed_at_ms: 1_042, - request_id: RequestId::Integer(52), - response: Box::new(sample_effective_permissions_approval_response( - CoreRequestPermissionProfile { - network: Some(CoreNetworkPermissions { - enabled: Some(true), - }), - file_system: None, - }, - CorePermissionGrantScope::Session, - )), - }, - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_review_event"); - assert_eq!(payload[0]["event_params"]["review_id"], "user:52"); - assert_eq!(payload[0]["event_params"]["subject_kind"], "permissions"); - assert_eq!(payload[0]["event_params"]["reviewer"], "user"); - assert_eq!(payload[0]["event_params"]["status"], "approved"); - assert_eq!(payload[0]["event_params"]["resolution"], "session_approval"); -} - -#[tokio::test] -async fn aborted_server_request_publishes_aborted_user_review_event_once() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new(sample_command_approval_request( - /*request_id*/ 61, /*approval_id*/ None, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ServerRequestAborted { - completed_at_ms: 1_042, - request_id: RequestId::Integer(61), - }, - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_params"]["review_id"], "user:61"); - assert_eq!(payload[0]["event_params"]["status"], "aborted"); - assert_eq!(payload[0]["event_params"]["resolution"], "none"); - - events.clear(); - reducer - .ingest( - AnalyticsFact::ServerResponse { - completed_at_ms: 1_043, - response: Box::new(sample_command_approval_response( - /*request_id*/ 61, - CommandExecutionApprovalDecision::Accept, - )), - }, - &mut events, - ) - .await; - assert!(events.is_empty()); -} - -#[tokio::test] -async fn guardian_completed_notification_publishes_review_event_with_thread_metadata() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_guardian_review_completed( - "guardian-review-1", - Some("item-1"), - GuardianApprovalReviewStatus::Denied, - GuardianApprovalReviewAction::Command { - source: AppServerGuardianCommandSource::Shell, - command: "echo hi".to_string(), - cwd: test_path_buf("/tmp").abs().into(), - }, - ))), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events[0]).expect("serialize review event"); - assert_eq!(payload["event_type"], "codex_review_event"); - assert_eq!(payload["event_params"]["review_id"], "guardian-review-1"); - assert_eq!(payload["event_params"]["item_id"], "item-1"); - assert_eq!(payload["event_params"]["thread_source"], "user"); - assert_eq!(payload["event_params"]["subject_kind"], "command_execution"); - assert_eq!(payload["event_params"]["reviewer"], "guardian"); - assert_eq!(payload["event_params"]["status"], "denied"); - assert_eq!(payload["event_params"]["started_at_ms"], 1_000); - assert_eq!(payload["event_params"]["completed_at_ms"], 1_042); - assert_eq!(payload["event_params"]["duration_ms"], 42); -} - -#[tokio::test] -async fn terminal_reviews_denormalize_counts_onto_tool_item_events() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new(sample_command_approval_request( - /*request_id*/ 71, /*approval_id*/ None, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ServerResponse { - completed_at_ms: 1_042, - response: Box::new(sample_command_approval_response( - /*request_id*/ 71, - CommandExecutionApprovalDecision::AcceptForSession, - )), - }, - &mut events, - ) - .await; - events.clear(); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_guardian_review_completed( - "guardian-stdin-review-1", - Some("item-1"), - GuardianApprovalReviewStatus::Denied, - GuardianApprovalReviewAction::WriteStdin { - approval_id: "stdin-approval-1".to_string(), - process_id: "42".to_string(), - stdin: "confirm\n".to_string(), - cwd: test_path_buf("/tmp").abs().into(), - }, - ))), - &mut events, - ) - .await; - let review_payload = serde_json::to_value(&events[0]).expect("serialize review event"); - assert_eq!( - review_payload["event_params"]["subject_kind"], - "write_stdin" - ); - events.clear(); - - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "item-1").await; - - let payload = serde_json::to_value(&events[0]).expect("serialize tool item event"); - assert_eq!(payload["event_params"]["review_count"], 1); - assert_eq!(payload["event_params"]["user_review_count"], 1); - assert_eq!(payload["event_params"]["guardian_review_count"], 0); - assert_eq!( - payload["event_params"]["final_approval_outcome"], - "user_approved_for_session" - ); -} - -#[tokio::test] -async fn item_review_summaries_do_not_cross_threads_with_reused_item_ids() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(2), - response: Box::new(sample_thread_start_response( - "thread-2", /*ephemeral*/ false, "gpt-5", - )), - thread_originator: None, - }, - &mut events, - ) - .await; - events.clear(); - - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 7, - request: Box::new(sample_command_approval_request( - /*request_id*/ 72, /*approval_id*/ None, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ServerResponse { - completed_at_ms: 1_042, - response: Box::new(sample_command_approval_response( - /*request_id*/ 72, - CommandExecutionApprovalDecision::Accept, - )), - }, - &mut events, - ) - .await; - events.clear(); - - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-2", "item-1").await; - - let payload = serde_json::to_value(&events[0]).expect("serialize tool item event"); - assert_eq!(payload["event_params"]["thread_id"], "thread-2"); - assert_eq!(payload["event_params"]["item_id"], "item-1"); - assert_eq!(payload["event_params"]["review_count"], 0); - assert_eq!(payload["event_params"]["user_review_count"], 0); - assert_eq!(payload["event_params"]["guardian_review_count"], 0); - assert_eq!(payload["event_params"]["final_approval_outcome"], "unknown"); -} - -#[tokio::test] -async fn guardian_events_keep_thread_source_and_originator_with_explicit_turn_connection() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let parent_thread_id = - codex_protocol::ThreadId::from_string("44444444-4444-4444-4444-444444444444") - .expect("valid parent thread id"); - let parent_thread_id_string = parent_thread_id.to_string(); - - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 7, - params: InitializeParams { - client_info: ClientInfo { - name: "parent-client".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: None, - }, - product_client_id: "parent-client".to_string(), - runtime: sample_runtime_metadata(), - rpc_transport: AppServerRpcTransport::Stdio, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - &parent_thread_id_string, - /*ephemeral*/ false, - "gpt-5", - )), - thread_originator: None, - }, - &mut events, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SubAgentThreadStarted( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-review".to_string(), - parent_thread_id: Some(parent_thread_id.to_string()), - forked_from_thread_id: None, - product_client_id: "parent-client".to_string(), - client_name: Some("parent-client".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::GuardianReview), - subagent_source: SubAgentSource::Other("guardian".to_string()), - initialization_mode: ThreadInitializationMode::New, - created_at: 130, - }, - )), - &mut events, - ) - .await; - - events.clear(); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::Compaction(Box::new( - CodexCompactionEvent { - thread_id: "thread-review".to_string(), - turn_id: "turn-compact".to_string(), - trigger: CompactionTrigger::Manual, - reason: CompactionReason::UserRequested, - implementation: CompactionImplementation::Responses, - phase: CompactionPhase::StandaloneTurn, - strategy: CompactionStrategy::Memento, - status: CompactionStatus::Completed, - codex_error_kind: None, - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - active_context_tokens_before: 131_000, - active_context_tokens_after: 64_000, - retained_image_count: None, - compaction_summary_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - started_at: 100, - completed_at: 101, - duration_ms: Some(1200), - }, - ))), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload[0]["event_params"]["session_id"], "session-root"); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-review"); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["product_client_id"], - "parent-client" - ); - assert_eq!( - payload[0]["event_params"]["parent_thread_id"], - "44444444-4444-4444-4444-444444444444" - ); - - events.clear(); - ingest_complete_child_turn(&mut reducer, &mut events, "thread-review", "turn-inherited").await; - let [TrackEventRequest::TurnEvent(event)] = events.as_slice() else { - panic!("expected one turn event"); - }; - let params = &event.event_params; - assert_eq!(params.session_id, "session-root"); - assert_eq!(params.thread_source, Some(ThreadSource::GuardianReview)); - assert_eq!(params.subagent_source.as_deref(), Some("guardian")); - assert_eq!( - params.parent_thread_id.as_deref(), - Some("44444444-4444-4444-4444-444444444444") - ); - assert_eq!(params.app_server_client.product_client_id, "parent-client"); - assert_eq!(params.runtime.codex_rs_version, "0.1.0"); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnTokenUsage(Box::new( - sample_turn_token_usage_fact("thread-review", "turn-inherited"), - ))), - &mut events, - ) - .await; - assert_eq!(events.len(), 1); - - events.clear(); - reducer - .ingest(sample_initialize_fact(/*connection_id*/ 8), &mut events) - .await; - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 8, - request_id: RequestId::Integer(3), - request: Box::new(sample_turn_start_request( - "thread-review", - /*request_id*/ 3, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 8, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-explicit")), - thread_originator: None, - }, - &mut events, - ) - .await; - ingest_complete_child_turn(&mut reducer, &mut events, "thread-review", "turn-explicit").await; - let [TrackEventRequest::TurnEvent(event)] = events.as_slice() else { - panic!("expected one turn event"); - }; - assert_eq!( - event.event_params.app_server_client.product_client_id, - "parent-client" - ); - assert_eq!( - event.event_params.app_server_client.client_name.as_deref(), - Some("codex-tui") - ); -} - -#[test] -fn execve_serializes_enabled_network_permissions() { - let permissions: AdditionalPermissionProfile = serde_json::from_value(json!({ - "network": { "enabled": true }, - })) - .expect("network permissions"); - - let action = GuardianReviewedAction::Execve { - source: GuardianCommandSource::UnifiedExec, - additional_permissions: Some(GuardianAdditionalPermissions::from(&permissions)), - }; - - assert_eq!( - serde_json::to_value(action).expect("serialize action"), - json!({ - "type": "execve", - "source": "unified_exec", - "additional_permissions": { - "network": { "enabled": true }, - }, - }), - ); -} - -#[test] -fn unified_exec_serializes_disabled_network_permissions() { - let permissions: AdditionalPermissionProfile = serde_json::from_value(json!({ - "network": { "enabled": false }, - })) - .expect("network permissions"); - - let action = GuardianReviewedAction::UnifiedExec { - sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, - additional_permissions: Some(GuardianAdditionalPermissions::from(&permissions)), - tty: false, - }; - - assert_eq!( - serde_json::to_value(action).expect("serialize action"), - json!({ - "type": "unified_exec", - "sandbox_permissions": "with_additional_permissions", - "additional_permissions": { - "network": { "enabled": false }, - }, - "tty": false, - }), - ); -} - -#[test] -fn permission_metadata_preserves_absent_and_empty_requests() { - for (input, expected) in [ - (json!(null), json!(null)), - (json!({}), json!({ "network": null })), - ( - json!({ "network": { "enabled": null } }), - json!({ - "network": { "enabled": null }, - }), - ), - ] { - let permissions: Option = - serde_json::from_value(input).expect("optional permissions"); - let metadata = permissions - .as_ref() - .map(GuardianAdditionalPermissions::from); - - assert_eq!( - serde_json::to_value(metadata).expect("serialize permissions"), - expected, - ); - } -} - -#[tokio::test] -async fn closing_thread_discards_review_without_turn_lifecycle_facts() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ServerRequest { - connection_id: 1, - request: Box::new(sample_command_approval_request( - /*request_id*/ 1, /*approval_id*/ None, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadClosed( - ThreadClosedNotification { - thread_id: "thread-1".to_string(), - }, - ))), - &mut events, - ) - .await; - events.clear(); - reducer - .ingest( - AnalyticsFact::ServerResponse { - completed_at_ms: 2_000, - response: Box::new(sample_command_approval_response( - /*request_id*/ 1, - CommandExecutionApprovalDecision::Accept, - )), - }, - &mut events, - ) - .await; - assert!(events.is_empty()); -} diff --git a/codex-rs/analytics/src/tests/suite/apps_tests.rs b/codex-rs/analytics/src/tests/suite/apps_tests.rs deleted file mode 100644 index 1060e12a..00000000 --- a/codex-rs/analytics/src/tests/suite/apps_tests.rs +++ /dev/null @@ -1,181 +0,0 @@ -//! App mention and usage events. - -use crate::events::CodexAppMentionedEventRequest; -use crate::events::CodexAppUsedEventRequest; -use crate::events::CodexAppUsedMetadata; -use crate::events::TrackEventRequest; -use crate::events::codex_app_metadata; -use crate::facts::AnalyticsFact; -use crate::facts::AppInvocation; -use crate::facts::AppMentionedInput; -use crate::facts::AppUsedInput; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::InvocationType; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::test_tracking_context; -use crate::tests::support::test_turn_metadata; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn app_mentioned_event_serializes_expected_shape() { - let tracking = test_tracking_context("thread-1", "turn-1"); - let event = TrackEventRequest::AppMentioned(CodexAppMentionedEventRequest { - event_type: "codex_app_mentioned", - event_params: codex_app_metadata( - &tracking, - AppInvocation { - connector_id: Some("calendar".to_string()), - app_name: Some("Calendar".to_string()), - invocation_type: Some(InvocationType::Explicit), - }, - ), - }); - - let payload = serde_json::to_value(&event).expect("serialize app mentioned event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_app_mentioned", - "event_params": { - "connector_id": "calendar", - "thread_id": "thread-1", - "turn_id": "turn-1", - "app_name": "Calendar", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "invoke_type": "explicit", - "model_slug": "gpt-5" - } - }) - ); -} - -#[test] -fn app_used_event_serializes_expected_shape() { - let mut tracking = test_tracking_context("thread-2", "turn-2"); - let mut metadata = test_turn_metadata(/*root_turn_id*/ None); - std::sync::Arc::get_mut(&mut metadata) - .expect("unique metadata") - .turn_trigger = Some("appServer-goal".to_string()); - tracking.turn_metadata = Some(metadata); - let event = TrackEventRequest::AppUsed(CodexAppUsedEventRequest { - event_type: "codex_app_used", - event_params: CodexAppUsedMetadata { - app: codex_app_metadata( - &tracking, - AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Google Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - ), - voice_session_id: None, - elicitation_type: None, - }, - }); - - let payload = serde_json::to_value(&event).expect("serialize app used event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_app_used", - "event_params": { - "turn_trigger": "appServer-goal", - "connector_id": "drive", - "thread_id": "thread-2", - "turn_id": "turn-2", - "app_name": "Google Drive", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "invoke_type": "implicit", - "model_slug": "gpt-5", - "voice_session_id": null, - "elicitation_type": null - } - }) - ); -} - -#[tokio::test] -async fn reducer_ingests_app_facts() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - let mut metadata = test_turn_metadata(/*root_turn_id*/ None); - std::sync::Arc::get_mut(&mut metadata) - .expect("unique metadata") - .turn_trigger = Some("automation_cron_run_now".to_string()); - let tracking = crate::facts::TrackEventsContext { - turn_metadata: Some(metadata), - ..tracking - }; - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppMentioned(AppMentionedInput { - tracking: tracking.clone(), - mentions: vec![AppInvocation { - connector_id: Some("calendar".to_string()), - app_name: Some("Calendar".to_string()), - invocation_type: Some(InvocationType::Explicit), - }], - })), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking, - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: Some(ElicitationType::AuthOrLink), - })), - &mut events, - ) - .await; - - let [ - TrackEventRequest::AppMentioned(mention), - TrackEventRequest::AppUsed(usage), - ] = events.as_slice() - else { - panic!("expected app mention and usage events"); - }; - assert_eq!( - [ - ( - mention.event_type, - mention.event_params.product_client_id.as_deref() - ), - ( - usage.event_type, - usage.event_params.app.product_client_id.as_deref() - ), - ], - [ - ("codex_app_mentioned", Some(TEST_PRODUCT_CLIENT_ID)), - ("codex_app_used", Some(TEST_PRODUCT_CLIENT_ID)), - ] - ); - assert_eq!( - ( - mention.event_params.turn_trigger.as_deref(), - usage.event_params.app.turn_trigger.as_deref() - ), - ( - Some("automation_cron_run_now"), - Some("automation_cron_run_now") - ) - ); - assert_eq!( - usage.event_params.elicitation_type, - Some(ElicitationType::AuthOrLink) - ); -} diff --git a/codex-rs/analytics/src/tests/suite/hooks_tests.rs b/codex-rs/analytics/src/tests/suite/hooks_tests.rs deleted file mode 100644 index b7e202dd..00000000 --- a/codex-rs/analytics/src/tests/suite/hooks_tests.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! Hook execution event, source, and status tests. - -use crate::events::CodexHookRunEventRequest; -use crate::events::TrackEventRequest; -use crate::events::codex_hook_run_metadata; -use crate::facts::AnalyticsFact; -use crate::facts::CustomAnalyticsFact; -use crate::facts::HookRunFact; -use crate::facts::HookRunInput; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::test_tracking_context; -use codex_protocol::protocol::HookEventName; -use codex_protocol::protocol::HookExecutionMode; -use codex_protocol::protocol::HookHandlerType; -use codex_protocol::protocol::HookRunStatus; -use codex_protocol::protocol::HookSource; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn hook_run_event_serializes_expected_shape() { - let tracking = test_tracking_context("thread-3", "turn-3"); - let event = TrackEventRequest::HookRun(CodexHookRunEventRequest { - event_type: "codex_hook_run", - event_params: codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::PreToolUse, - hook_source: HookSource::User, - handler_type: HookHandlerType::McpTool, - execution_mode: HookExecutionMode::Sync, - status: HookRunStatus::Completed, - }, - ), - }); - - let payload = serde_json::to_value(&event).expect("serialize hook run event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_hook_run", - "event_params": { - "thread_id": "thread-3", - "turn_id": "turn-3", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "model_slug": "gpt-5", - "hook_name": "PreToolUse", - "hook_source": "user", - "handler_type": "mcp_tool", - "execution_mode": "sync", - "status": "completed" - } - }) - ); -} - -#[test] -fn hook_run_metadata_maps_sources_and_statuses() { - let tracking = test_tracking_context("thread-1", "turn-1"); - - let system = serde_json::to_value(codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::SessionStart, - hook_source: HookSource::System, - handler_type: HookHandlerType::Command, - execution_mode: HookExecutionMode::Sync, - status: HookRunStatus::Completed, - }, - )) - .expect("serialize system hook"); - let project = serde_json::to_value(codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::Stop, - hook_source: HookSource::Project, - handler_type: HookHandlerType::Prompt, - execution_mode: HookExecutionMode::Async, - status: HookRunStatus::Blocked, - }, - )) - .expect("serialize project hook"); - let cloud_requirements = serde_json::to_value(codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::Stop, - hook_source: HookSource::CloudRequirements, - handler_type: HookHandlerType::Agent, - execution_mode: HookExecutionMode::Sync, - status: HookRunStatus::Blocked, - }, - )) - .expect("serialize cloud requirements hook"); - let unknown = serde_json::to_value(codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::UserPromptSubmit, - hook_source: HookSource::Unknown, - handler_type: HookHandlerType::Command, - execution_mode: HookExecutionMode::Async, - status: HookRunStatus::Failed, - }, - )) - .expect("serialize unknown hook"); - - assert_eq!(system["hook_source"], "system"); - assert_eq!(system["status"], "completed"); - assert_eq!(project["hook_source"], "project"); - assert_eq!(project["status"], "blocked"); - assert_eq!(cloud_requirements["hook_source"], "cloud_requirements"); - assert_eq!(cloud_requirements["status"], "blocked"); - assert_eq!(unknown["hook_source"], "unknown"); - assert_eq!(unknown["status"], "failed"); -} - -#[test] -fn hook_run_metadata_maps_stopped_status() { - let tracking = test_tracking_context("thread-1", "turn-1"); - - let stopped = serde_json::to_value(codex_hook_run_metadata( - &tracking, - HookRunFact { - event_name: HookEventName::Stop, - hook_source: HookSource::User, - handler_type: HookHandlerType::Command, - execution_mode: HookExecutionMode::Sync, - status: HookRunStatus::Stopped, - }, - )) - .expect("serialize stopped hook"); - - assert_eq!(stopped["hook_source"], "user"); - assert_eq!(stopped["status"], "stopped"); -} - -#[tokio::test] -async fn reducer_ingests_hook_run_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::HookRun(HookRunInput { - tracking: test_tracking_context("thread-1", "turn-1"), - hook: HookRunFact { - event_name: HookEventName::PostToolUse, - hook_source: HookSource::Unknown, - handler_type: HookHandlerType::Agent, - execution_mode: HookExecutionMode::Async, - status: HookRunStatus::Failed, - }, - })), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_hook_run"); - assert_eq!(payload[0]["event_params"]["hook_name"], "PostToolUse"); - assert_eq!(payload[0]["event_params"]["hook_source"], "unknown"); - assert_eq!(payload[0]["event_params"]["handler_type"], "agent"); - assert_eq!(payload[0]["event_params"]["execution_mode"], "async"); - assert_eq!(payload[0]["event_params"]["status"], "failed"); -} diff --git a/codex-rs/analytics/src/tests/suite/mod.rs b/codex-rs/analytics/src/tests/suite/mod.rs deleted file mode 100644 index efd9d3d3..00000000 --- a/codex-rs/analytics/src/tests/suite/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Choose tests by the contract that changes: the owning event suite covers fact-to-JSON -//! behavior, privacy, and prerequisites; client protocol covers admission; client delivery covers -//! authentication, batching, and destinations; reducer ordering covers relative arrivals across -//! owners. Use owner-local tests for private invariants when needed, and Core or app-server -//! integration tests when changing the actual producer or emission. Client tests live in this -//! directory but are mounted by `client.rs` for private access without widening internals. - -#[path = "approvals_tests.rs"] -mod approvals; -#[path = "apps_tests.rs"] -mod apps; -#[path = "hooks_tests.rs"] -mod hooks; -#[path = "onboarding_tests.rs"] -mod onboarding; -#[path = "plugins_tests.rs"] -mod plugins; -#[path = "reducer_ordering_tests.rs"] -mod reducer_ordering; -#[path = "skills_tests.rs"] -mod skills; -#[path = "threads_tests.rs"] -mod threads; -#[path = "tools_tests.rs"] -mod tools; -#[path = "turns_tests.rs"] -mod turns; diff --git a/codex-rs/analytics/src/tests/suite/onboarding_tests.rs b/codex-rs/analytics/src/tests/suite/onboarding_tests.rs deleted file mode 100644 index 3eadd54a..00000000 --- a/codex-rs/analytics/src/tests/suite/onboarding_tests.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! External-agent configuration import event tests. - -use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest; -use crate::events::CodexOnboardingExternalAgentImportFailureMetadata; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ExternalAgentConfigImportCompletedInput; -use crate::facts::ExternalAgentConfigImportFailureInput; -use crate::reducer::AnalyticsReducer; -use codex_login::default_client::originator; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[tokio::test] -async fn reducer_ingests_external_agent_config_import_completed_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportCompleted( - ExternalAgentConfigImportCompletedInput { - import_id: "import-1".to_string(), - source: "app_server".to_string(), - provider_id: "test-provider-42".to_string(), - item_type: "PLUGINS".to_string(), - success_count: 2, - failed_count: 1, - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "codex_onboarding_external_agent_import_complete", - "event_params": { - "import_id": "import-1", - "source": "app_server", - "provider_id": "test-provider-42", - "type": "PLUGINS", - "success_count": 2, - "failed_count": 1, - "product_client_id": originator().value, - } - }]) - ); -} - -#[test] -fn external_agent_config_import_failure_event_serializes_expected_shape() { - let event = TrackEventRequest::ExternalAgentConfigImportFailure( - CodexOnboardingExternalAgentImportFailureEventRequest { - event_type: "codex_onboarding_external_agent_import_failure", - event_params: CodexOnboardingExternalAgentImportFailureMetadata { - import_id: "import-1".to_string(), - source: "app_server".to_string(), - provider_id: "test-provider-42".to_string(), - item_type: "PLUGINS".to_string(), - failure_stage: "plugin_import".to_string(), - error_type: "plugin_import".to_string(), - sub_error_type: Some("failed_to_copy_plugin_file".to_string()), - product_client_id: Some(originator().value), - }, - }, - ); - - let payload = serde_json::to_value(&event).expect("serialize import failure event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_onboarding_external_agent_import_failure", - "event_params": { - "import_id": "import-1", - "source": "app_server", - "provider_id": "test-provider-42", - "type": "PLUGINS", - "failure_stage": "plugin_import", - "error_type": "plugin_import", - "sub_error_type": "failed_to_copy_plugin_file", - "product_client_id": originator().value, - } - }) - ); -} - -#[tokio::test] -async fn reducer_ingests_external_agent_config_import_failure_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportFailure( - ExternalAgentConfigImportFailureInput { - import_id: "import-1".to_string(), - source: "app_server".to_string(), - provider_id: "test-provider-42".to_string(), - item_type: "PLUGINS".to_string(), - failure_stage: "plugin_import".to_string(), - error_type: "plugin_import".to_string(), - sub_error_type: Some("failed_to_copy_plugin_file".to_string()), - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "codex_onboarding_external_agent_import_failure", - "event_params": { - "import_id": "import-1", - "source": "app_server", - "provider_id": "test-provider-42", - "type": "PLUGINS", - "failure_stage": "plugin_import", - "error_type": "plugin_import", - "sub_error_type": "failed_to_copy_plugin_file", - "product_client_id": originator().value, - } - }]) - ); -} diff --git a/codex-rs/analytics/src/tests/suite/plugins_tests.rs b/codex-rs/analytics/src/tests/suite/plugins_tests.rs deleted file mode 100644 index 584f5d0c..00000000 --- a/codex-rs/analytics/src/tests/suite/plugins_tests.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! Plugin lifecycle, usage, measurements, and event deduplication tests. - -use crate::client::AnalyticsEventsQueue; -use crate::events::CodexPluginEventRequest; -use crate::events::CodexPluginInstallFailedEventRequest; -use crate::events::CodexPluginInstallFailedMetadata; -use crate::events::CodexPluginUsedEventRequest; -use crate::events::TrackEventRequest; -use crate::events::codex_plugin_metadata; -use crate::events::codex_plugin_used_metadata; -use crate::facts::AnalyticsFact; -use crate::facts::CustomAnalyticsFact; -use crate::facts::PluginInstallFailedInput; -use crate::facts::PluginInstallRequestSource; -use crate::facts::PluginInstallRequested; -use crate::facts::PluginInstallRequestedInput; -use crate::facts::PluginInstallRequestedPlugin; -use crate::facts::PluginInstallSource; -use crate::facts::PluginMeasurementRow; -use crate::facts::PluginMeasurementsInput; -use crate::facts::PluginState; -use crate::facts::PluginStateChangedInput; -use crate::facts::PluginUsedInput; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::sample_plugin_metadata; -use crate::tests::support::test_tracking_context; -use codex_login::default_client::originator; -use codex_plugin::PluginTelemetryMetadata; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::BTreeMap; -use std::collections::HashSet; -use std::sync::Arc; -use std::sync::Mutex; -use tokio::sync::mpsc; - -fn plugin_measurements(rows: Vec) -> PluginMeasurementsInput { - PluginMeasurementsInput { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "item-1".to_string(), - originator: "codex_cli_rs".to_string(), - model_slug: None, - reasoning_effort: None, - plugin_id: "sample@openai-curated".to_string(), - execution_id: "execution-1".to_string(), - operation: "security_scan".to_string(), - rows, - } -} - -#[tokio::test] -async fn plugin_measurement_batch_emits_directly_and_filters_invalid_rows() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let mut too_many_dimensions = BTreeMap::new(); - for index in 0..9 { - too_many_dimensions.insert(format!("dimension_{index}"), "allowed".to_string()); - } - let mut measurements = plugin_measurements(vec![ - PluginMeasurementRow { - measurement_name: "finding_count".to_string(), - number_value: 3.0, - dimensions: BTreeMap::from([("severity".to_string(), "high".to_string())]), - }, - PluginMeasurementRow { - measurement_name: "non_finite".to_string(), - number_value: f64::NAN, - dimensions: BTreeMap::new(), - }, - PluginMeasurementRow { - measurement_name: "too_many_dimensions".to_string(), - number_value: 1.0, - dimensions: too_many_dimensions, - }, - PluginMeasurementRow { - measurement_name: "files_scanned".to_string(), - number_value: 17.0, - dimensions: BTreeMap::new(), - }, - ]); - measurements.model_slug = Some("invoking-model".to_string()); - measurements.reasoning_effort = Some("max".to_string()); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginMeasurements(measurements)), - &mut events, - ) - .await; - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([ - { - "event_type": "codex_plugin_measurement_event", - "event_params": { - "thread_id": "thread-1", - "turn_id": "turn-1", - "item_id": "item-1", - "plugin_id": "sample@openai-curated", - "execution_id": "execution-1", - "operation": "security_scan", - "measurement_name": "finding_count", - "originator": "codex_cli_rs", - "model_slug": "invoking-model", - "reasoning_effort": "max", - "number_value": 3.0, - "dimensions": {"severity": "high"}, - }, - }, - { - "event_type": "codex_plugin_measurement_event", - "event_params": { - "thread_id": "thread-1", - "turn_id": "turn-1", - "item_id": "item-1", - "plugin_id": "sample@openai-curated", - "execution_id": "execution-1", - "operation": "security_scan", - "measurement_name": "files_scanned", - "originator": "codex_cli_rs", - "model_slug": "invoking-model", - "reasoning_effort": "max", - "number_value": 17.0, - "dimensions": null, - }, - }, - ]) - ); -} - -#[test] -fn plugin_used_event_serializes_expected_shape() { - let tracking = test_tracking_context("thread-3", "turn-3"); - let event = TrackEventRequest::PluginUsed(CodexPluginUsedEventRequest { - event_type: "codex_plugin_used", - event_params: codex_plugin_used_metadata(&tracking, sample_plugin_metadata()), - }); - - let payload = serde_json::to_value(&event).expect("serialize plugin used event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_plugin_used", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": null, - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "mcp_server_names": ["mcp-1", "mcp-2"], - "thread_id": "thread-3", - "turn_id": "turn-3", - "model_slug": "gpt-5" - } - }) - ); -} - -#[tokio::test] -async fn reducer_ingests_plugin_used_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginUsed(PluginUsedInput { - tracking, - plugin: sample_plugin_metadata(), - })), - &mut events, - ) - .await; - - let [TrackEventRequest::PluginUsed(event)] = events.as_slice() else { - panic!("expected a plugin usage event"); - }; - assert_eq!( - ( - event.event_type, - event.event_params.plugin.product_client_id.as_deref() - ), - ("codex_plugin_used", Some(TEST_PRODUCT_CLIENT_ID)) - ); -} - -#[test] -fn plugin_management_event_serializes_expected_shape() { - let event = TrackEventRequest::PluginInstalled(CodexPluginEventRequest { - event_type: "codex_plugin_installed", - event_params: codex_plugin_metadata(sample_plugin_metadata()), - }); - - let payload = serde_json::to_value(&event).expect("serialize plugin installed event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": null, - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": originator().value - } - }) - ); -} - -#[test] -fn plugin_install_failed_event_serializes_expected_shape() { - let event = TrackEventRequest::PluginInstallFailed(CodexPluginInstallFailedEventRequest { - event_type: "codex_plugin_install_failed", - event_params: CodexPluginInstallFailedMetadata { - plugin: codex_plugin_metadata(sample_plugin_metadata()), - source: PluginInstallSource::Manual, - error_type: "store_io".to_string(), - sub_error_type: Some("failed_to_copy_plugin_file".to_string()), - }, - }); - - let payload = serde_json::to_value(&event).expect("serialize plugin install failed event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_plugin_install_failed", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": null, - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": originator().value, - "source": "manual", - "error_type": "store_io", - "sub_error_type": "failed_to_copy_plugin_file" - } - }) - ); -} - -#[test] -fn plugin_management_event_keeps_plugin_id_local_when_remote_id_exists() { - let mut plugin = sample_plugin_metadata(); - plugin.remote_plugin_id = Some("plugins~Plugin_remote".to_string()); - let event = TrackEventRequest::PluginInstalled(CodexPluginEventRequest { - event_type: "codex_plugin_installed", - event_params: codex_plugin_metadata(plugin), - }); - - let payload = serde_json::to_value(&event).expect("serialize plugin installed event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": "plugins~Plugin_remote", - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": originator().value - } - }) - ); -} - -#[test] -fn plugin_used_dedupe_is_keyed_by_turn_and_plugin() { - let (sender, _receiver) = mpsc::channel(1); - let queue = AnalyticsEventsQueue { - sender, - product_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)), - app_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - plugin_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())), - }; - let plugin = sample_plugin_metadata(); - - let turn_1 = test_tracking_context("thread-1", "turn-1"); - let turn_2 = test_tracking_context("thread-1", "turn-2"); - - assert_eq!(queue.should_enqueue_plugin_used(&turn_1, &plugin), true); - assert_eq!(queue.should_enqueue_plugin_used(&turn_1, &plugin), false); - assert_eq!(queue.should_enqueue_plugin_used(&turn_2, &plugin), true); -} - -#[tokio::test] -async fn reducer_ingests_plugin_state_changed_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginStateChanged( - PluginStateChangedInput { - plugin: sample_plugin_metadata(), - state: PluginState::Disabled, - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "codex_plugin_disabled", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": null, - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": originator().value - } - }]) - ); -} - -#[tokio::test] -async fn reducer_ingests_plugin_install_requested_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - let request = PluginInstallRequested { - suggestion_id: "request_plugin_install_call-1".to_string(), - plugins: vec![ - PluginInstallRequestedPlugin { - plugin_id: "calendar@openai-curated-remote".to_string(), - remote_plugin_id: Some("plugin_calendar".to_string()), - plugin_name: "Calendar".to_string(), - connector_ids: vec!["connector_calendar".to_string()], - }, - PluginInstallRequestedPlugin { - plugin_id: "github@openai-curated-remote".to_string(), - remote_plugin_id: None, - plugin_name: "GitHub".to_string(), - connector_ids: vec!["connector_github".to_string()], - }, - ], - source: PluginInstallRequestSource::EndpointRecommendation, - }; - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallRequested( - PluginInstallRequestedInput { tracking, request }, - )), - &mut events, - ) - .await; - - assert_eq!( - serde_json::to_value(&events).expect("serialize events"), - json!([{ - "event_type": "codex_plugin_install_requested", - "event_params": { - "suggestion_id": "request_plugin_install_call-1", - "plugins": [{ - "plugin_id": "calendar@openai-curated-remote", - "remote_plugin_id": "plugin_calendar", - "plugin_name": "Calendar", - "connector_ids": ["connector_calendar"], - }, { - "plugin_id": "github@openai-curated-remote", - "remote_plugin_id": null, - "plugin_name": "GitHub", - "connector_ids": ["connector_github"], - }], - "source": "endpoint_recommendation", - "thread_id": "thread-1", - "turn_id": "turn-1", - "model_slug": "gpt-5", - "product_client_id": originator().value, - } - }]) - ); -} - -#[tokio::test] -async fn reducer_ingests_plugin_install_failed_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed( - PluginInstallFailedInput { - plugin: sample_plugin_metadata(), - source: PluginInstallSource::ExternalAgentMigration, - error_type: "invalid_plugin".to_string(), - sub_error_type: Some("failed_to_copy_plugin_file".to_string()), - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "codex_plugin_install_failed", - "event_params": { - "plugin_id": "sample@test", - "remote_plugin_id": null, - "plugin_name": "sample", - "marketplace_name": "test", - "has_skills": true, - "mcp_server_count": 2, - "connector_ids": ["calendar", "drive"], - "product_client_id": originator().value, - "source": "external_agent_migration", - "error_type": "invalid_plugin", - "sub_error_type": "failed_to_copy_plugin_file" - } - }]) - ); -} - -#[tokio::test] -async fn reducer_ingests_plugin_install_failed_fact_without_detail() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let plugin = PluginTelemetryMetadata { - plugin_id: None, - remote_plugin_id: Some("plugins~Plugin_00000000000000000000000000000000".to_string()), - capability_summary: None, - }; - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed( - PluginInstallFailedInput { - plugin, - source: PluginInstallSource::Manual, - error_type: "remote_catalog_unexpected_status".to_string(), - sub_error_type: None, - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "codex_plugin_install_failed", - "event_params": { - "plugin_id": null, - "remote_plugin_id": "plugins~Plugin_00000000000000000000000000000000", - "plugin_name": null, - "marketplace_name": null, - "has_skills": null, - "mcp_server_count": null, - "connector_ids": null, - "product_client_id": originator().value, - "source": "manual", - "error_type": "remote_catalog_unexpected_status", - "sub_error_type": null - } - }]) - ); -} diff --git a/codex-rs/analytics/src/tests/suite/reducer_ordering_tests.rs b/codex-rs/analytics/src/tests/suite/reducer_ordering_tests.rs deleted file mode 100644 index d6e8c65f..00000000 --- a/codex-rs/analytics/src/tests/suite/reducer_ordering_tests.rs +++ /dev/null @@ -1,806 +0,0 @@ -//! Coordinator routing and ordering guarantees across analytics event families. - -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::AppInvocation; -use crate::facts::AppMentionedInput; -use crate::facts::AppUsedInput; -use crate::facts::CodeModeToolCallFact; -use crate::facts::CodeModeToolCallStatus; -use crate::facts::ControlToolCallFact; -use crate::facts::ControlToolCallStatus; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::InvocationType; -use crate::facts::PluginUsedInput; -use crate::facts::SkillInvocation; -use crate::facts::SkillInvocationLocation; -use crate::facts::SkillInvokedInput; -use crate::facts::TurnProfileFact; -use crate::facts::TurnResolvedConfigFact; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::ingest_code_mode_facts; -use crate::tests::support::ingest_completed_command_execution_item; -use crate::tests::support::ingest_initialize; -use crate::tests::support::ingest_review_prerequisites; -use crate::tests::support::ingest_turn_prerequisites; -use crate::tests::support::sample_command_execution_item; -use crate::tests::support::sample_plugin_metadata; -use crate::tests::support::sample_turn_completed_notification; -use crate::tests::support::sample_turn_profile; -use crate::tests::support::sample_turn_resolved_config; -use crate::tests::support::sample_turn_start_response; -use crate::tests::support::sample_turn_started_notification; -use crate::tests::support::test_tracking_context; -use crate::tests::support::test_turn_metadata; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadArchiveParams; -use codex_app_server_protocol::ThreadArchiveResponse; -use codex_app_server_protocol::ThreadClosedNotification; -use codex_app_server_protocol::ThreadRealtimeClosedNotification; -use codex_app_server_protocol::ThreadRealtimeStartedNotification; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_protocol::protocol::RealtimeConversationVersion; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[tokio::test] -async fn stateless_app_and_plugin_facts_preserve_arrival_order() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - - for fact in [ - CustomAnalyticsFact::AppMentioned(AppMentionedInput { - tracking: tracking.clone(), - mentions: vec![AppInvocation { - connector_id: Some("calendar".to_string()), - app_name: Some("Calendar".to_string()), - invocation_type: Some(InvocationType::Explicit), - }], - }), - CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking: tracking.clone(), - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: Some(ElicitationType::AuthOrLink), - }), - CustomAnalyticsFact::PluginUsed(PluginUsedInput { - tracking, - plugin: sample_plugin_metadata(), - }), - ] { - reducer - .ingest(AnalyticsFact::Custom(fact), &mut events) - .await; - } - - let [ - TrackEventRequest::AppMentioned(mention), - TrackEventRequest::AppUsed(usage), - TrackEventRequest::PluginUsed(plugin), - ] = events.as_slice() - else { - panic!("expected app mention, app usage, and plugin usage in arrival order"); - }; - assert_eq!( - [ - ( - mention.event_type, - mention.event_params.product_client_id.as_deref() - ), - ( - usage.event_type, - usage.event_params.app.product_client_id.as_deref() - ), - ( - plugin.event_type, - plugin.event_params.plugin.product_client_id.as_deref() - ), - ], - [ - ("codex_app_mentioned", Some(TEST_PRODUCT_CLIENT_ID)), - ("codex_app_used", Some(TEST_PRODUCT_CLIENT_ID)), - ("codex_plugin_used", Some(TEST_PRODUCT_CLIENT_ID)), - ] - ); - assert_eq!( - usage.event_params.elicitation_type, - Some(ElicitationType::AuthOrLink) - ); -} - -#[tokio::test] -async fn unrelated_client_requests_are_ignored_by_reducer() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(3), - request: Box::new(ClientRequest::ThreadArchive { - request_id: RequestId::Integer(3), - params: ThreadArchiveParams { - thread_id: "thread-2".to_string(), - }, - }), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-2")), - thread_originator: None, - }, - &mut events, - ) - .await; - - assert!( - events.is_empty(), - "unrelated requests must not create pending turn state" - ); -} - -#[tokio::test] -async fn unrelated_client_responses_are_ignored_by_reducer() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_initialize(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(9), - response: Box::new(ClientResponsePayload::ThreadArchive( - ThreadArchiveResponse {}, - )), - thread_originator: None, - }, - &mut events, - ) - .await; - - assert!(events.is_empty()); -} - -#[tokio::test] -async fn turn_and_tool_events_read_current_trusted_root() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - let turn_metadata = test_turn_metadata(Some("root-ancestor")); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata: turn_metadata.clone(), - ..sample_turn_resolved_config("thread-1", "turn-1") - }, - ))), - &mut events, - ) - .await; - - ingest_completed_command_execution_item( - &mut reducer, - &mut events, - "thread-1", - "before-conflict", - ) - .await; - let queued_control_call = ControlToolCallFact { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - turn_metadata: turn_metadata.clone(), - call_id: "queued-control".to_string(), - cell_id: None, - tool_name: "view_image".to_string(), - started_at_ms: 998, - completed_at_ms: 1_000, - status: ControlToolCallStatus::Completed, - }; - let queued_code_mode_call = CodeModeToolCallFact::Completed { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - turn_metadata: turn_metadata.clone(), - call_id: "queued-code-mode".to_string(), - cell_id: None, - tool_name: "exec".to_string(), - started_at_ms: 998, - completed_at_ms: 1_000, - status: CodeModeToolCallStatus::Completed, - }; - *turn_metadata.root_turn_id.lock().expect("root turn ID") = None; - ingest_completed_command_execution_item( - &mut reducer, - &mut events, - "thread-1", - "after-conflict", - ) - .await; - for fact in [ - AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall(queued_control_call)), - AnalyticsFact::Custom(CustomAnalyticsFact::CodeModeToolCall(queued_code_mode_call)), - AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new( - TurnProfileFact { - turn_id: "turn-1".to_string(), - profile: sample_turn_profile(), - }, - ))), - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-1", - "turn-1", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - ] { - reducer.ingest(fact, &mut events).await; - } - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload - .as_array() - .expect("events array") - .iter() - .map(|event| json!({ - "event_type": event["event_type"], - "turn_id": event["event_params"]["turn_id"], - "item_id": event["event_params"].get("item_id"), - "root_turn_id": event["event_params"].get("root_turn_id").expect("root field"), - })) - .collect::>(), - vec![ - json!({"event_type": "codex_command_execution_event", "turn_id": "turn-1", "item_id": "before-conflict", "root_turn_id": "root-ancestor"}), - json!({"event_type": "codex_command_execution_event", "turn_id": "turn-1", "item_id": "after-conflict", "root_turn_id": null}), - json!({"event_type": "codex_control_tool_call_event", "turn_id": "turn-1", "item_id": "queued-control", "root_turn_id": null}), - json!({"event_type": "codex_dynamic_tool_call_event", "turn_id": "turn-1", "item_id": "queued-code-mode", "root_turn_id": null}), - json!({"event_type": "codex_turn_event", "turn_id": "turn-1", "item_id": null, "root_turn_id": null}), - ] - ); -} - -#[tokio::test] -async fn completed_background_tool_item_emits_after_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - let turn_metadata = test_turn_metadata(Some("root-background")); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata: turn_metadata.clone(), - ..sample_turn_resolved_config("thread-2", "turn-2") - }, - ))), - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - sample_command_execution_item( - CommandExecutionStatus::InProgress, - /*exit_code*/ None, - /*duration_ms*/ None, - ), - /*started_at_ms*/ 998, - ), - ))), - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert_eq!( - out.iter() - .filter(|event| matches!(event, TrackEventRequest::TurnEvent(_))) - .count(), - 1 - ); - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - sample_command_execution_item( - CommandExecutionStatus::Completed, - Some(0), - Some(1), - ), - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut out, - ) - .await; - - assert_eq!( - out.iter() - .filter(|event| matches!(event, TrackEventRequest::TurnEvent(_))) - .count(), - 1 - ); - assert!( - out.iter() - .any(|event| matches!(event, TrackEventRequest::CommandExecution(_))) - ); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall(ControlToolCallFact { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - turn_metadata: turn_metadata.clone(), - call_id: "late-view-image".to_string(), - cell_id: None, - tool_name: "view_image".to_string(), - started_at_ms: 998, - completed_at_ms: 1_001, - status: ControlToolCallStatus::Completed, - })), - &mut out, - ) - .await; - ingest_code_mode_facts( - &mut reducer, - &mut out, - [CodeModeToolCallFact::Completed { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - turn_metadata, - call_id: "late-code-mode".to_string(), - cell_id: None, - tool_name: "exec".to_string(), - started_at_ms: 998, - completed_at_ms: 1_001, - status: CodeModeToolCallStatus::Interrupted, - }], - ) - .await; - reducer.flush(&mut out); - - assert_eq!( - out.iter() - .map(|event| { - let event = serde_json::to_value(event).expect("serialize event"); - json!({ - "event_type": event["event_type"], - "turn_id": event["event_params"]["turn_id"], - "root_turn_id": event["event_params"]["root_turn_id"], - }) - }) - .collect::>(), - vec![ - json!({"event_type": "codex_turn_event", "turn_id": "turn-2", "root_turn_id": "root-background"}), - json!({"event_type": "codex_command_execution_event", "turn_id": "turn-2", "root_turn_id": "root-background"}), - json!({"event_type": "codex_control_tool_call_event", "turn_id": "turn-2", "root_turn_id": "root-background"}), - json!({"event_type": "codex_dynamic_tool_call_event", "turn_id": "turn-2", "root_turn_id": "root-background"}), - ] - ); -} - -#[tokio::test] -async fn item_completed_without_turn_state_does_not_create_turn_state() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - sample_command_execution_item( - CommandExecutionStatus::Completed, - Some(0), - Some(1), - ), - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert!(out.is_empty()); -} - -#[tokio::test] -async fn voice_handoff_attributes_plugin_events_after_realtime_closes() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ false, - /*include_token_usage*/ true, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadRealtimeStarted( - ThreadRealtimeStartedNotification { - thread_id: "thread-2".to_string(), - realtime_session_id: Some("work-voice-123".to_string()), - version: RealtimeConversationVersion::V2, - }, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::RealtimeHandoffRequested { - thread_id: "thread-2".to_string(), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadRealtimeClosed( - ThreadRealtimeClosedNotification { - thread_id: "thread-2".to_string(), - reason: None, - }, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-2", - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking: test_tracking_context("thread-2", "turn-2"), - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: None, - })), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SkillInvoked(SkillInvokedInput { - tracking: test_tracking_context("thread-2", "turn-2"), - invocations: vec![SkillInvocation { - skill_name: "sample:doc".to_string(), - location: SkillInvocationLocation::Resource { - id: "resource-1".to_string(), - skill_id: Some("sample:doc".to_string()), - scope: None, - }, - plugin_id: Some("sample@test".to_string()), - remote_plugin_id: None, - invocation_type: InvocationType::Explicit, - }], - })), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - - for event_type in ["codex_app_used", "skill_invocation", "codex_turn_event"] { - let event = events - .iter() - .map(|event| serde_json::to_value(event).expect("serialize analytics event")) - .find(|event| event["event_type"] == event_type) - .unwrap_or_else(|| panic!("missing {event_type}")); - assert_eq!(event["event_params"]["voice_session_id"], "work-voice-123"); - } - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-3", - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking: test_tracking_context("thread-2", "turn-3"), - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: None, - })), - &mut events, - ) - .await; - let text_app = serde_json::to_value(events.last().expect("text app event")) - .expect("serialize text app event"); - assert_eq!(text_app["event_params"]["voice_session_id"], json!(null)); -} - -#[tokio::test] -async fn voice_handoff_steering_active_turn_does_not_tag_next_text_turn() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-2", - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadRealtimeStarted( - ThreadRealtimeStartedNotification { - thread_id: "thread-2".to_string(), - realtime_session_id: Some("work-voice-123".to_string()), - version: RealtimeConversationVersion::V2, - }, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::RealtimeHandoffRequested { - thread_id: "thread-2".to_string(), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadRealtimeClosed( - ThreadRealtimeClosedNotification { - thread_id: "thread-2".to_string(), - reason: None, - }, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking: test_tracking_context("thread-2", "turn-2"), - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: None, - })), - &mut events, - ) - .await; - let voice_app = serde_json::to_value(events.last().expect("voice app event")) - .expect("serialize voice app event"); - assert_eq!( - voice_app["event_params"]["voice_session_id"], - "work-voice-123" - ); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-3", - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::AppUsed(AppUsedInput { - tracking: test_tracking_context("thread-2", "turn-3"), - app: AppInvocation { - connector_id: Some("drive".to_string()), - app_name: Some("Drive".to_string()), - invocation_type: Some(InvocationType::Implicit), - }, - elicitation_type: None, - })), - &mut events, - ) - .await; - let text_app = serde_json::to_value(events.last().expect("text app event")) - .expect("serialize text app event"); - assert_eq!(text_app["event_params"]["voice_session_id"], json!(null)); -} - -#[tokio::test] -async fn incomplete_turns_release_metadata_when_capacity_is_exceeded() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let mut retained = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - events.clear(); - - // Simulate a full queue dropping completion/profile facts for many turns. - for index in 0..1_024 { - let config = sample_turn_resolved_config("thread-1", &format!("lost-{index}")); - retained.push(std::sync::Arc::downgrade(&config.turn_metadata)); - if index % 2 == 0 { - // Tool completions can arrive before the surviving config fact. - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall( - ControlToolCallFact { - thread_id: config.thread_id.clone(), - turn_id: config.turn_id.clone(), - turn_metadata: config.turn_metadata.clone(), - call_id: format!("tool-{index}"), - cell_id: None, - tool_name: "view_image".to_string(), - started_at_ms: 100, - completed_at_ms: 200, - status: ControlToolCallStatus::Completed, - }, - )), - &mut events, - ) - .await; - } - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new(config))), - &mut events, - ) - .await; - } - assert!(retained.first().unwrap().upgrade().is_none()); - assert!(retained.last().unwrap().upgrade().is_some()); - assert!(events.is_empty()); - - // Dropped history must not prevent a new, complete turn from being reported. - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ true, - ) - .await; - events.clear(); - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - assert_eq!( - events - .iter() - .filter_map(|event| match event { - TrackEventRequest::TurnEvent(event) => Some(event.event_params.turn_id.as_str()), - _ => None, - }) - .collect::>(), - vec!["turn-2"] - ); -} - -#[tokio::test] -async fn closing_thread_releases_incomplete_turns_without_affecting_other_threads() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let closed = sample_turn_resolved_config("closed-thread", "closed-turn"); - let live = sample_turn_resolved_config("live-thread", "live-turn"); - let closed_metadata = std::sync::Arc::downgrade(&closed.turn_metadata); - let live_metadata = std::sync::Arc::downgrade(&live.turn_metadata); - for config in [closed, live] { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new(config))), - &mut events, - ) - .await; - } - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadClosed( - ThreadClosedNotification { - thread_id: "closed-thread".to_string(), - }, - ))), - &mut events, - ) - .await; - assert!(closed_metadata.upgrade().is_none()); - assert!(live_metadata.upgrade().is_some()); - assert!(events.is_empty()); -} diff --git a/codex-rs/analytics/src/tests/suite/skills_tests.rs b/codex-rs/analytics/src/tests/suite/skills_tests.rs deleted file mode 100644 index 08b50d23..00000000 --- a/codex-rs/analytics/src/tests/suite/skills_tests.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! Skill invocation events and privacy rules for local skill identifiers. - -use crate::facts::AnalyticsFact; -use crate::facts::CustomAnalyticsFact; -use crate::facts::InvocationType; -use crate::facts::SkillInvocation; -use crate::facts::SkillInvocationLocation; -use crate::facts::SkillInvokedInput; -use crate::reducer::AnalyticsReducer; -use crate::reducer::normalize_path_for_skill_id; -use crate::reducer::skill_id_for_local_skill; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::test_tracking_context; -use codex_utils_path_uri::PathUri; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::path::PathBuf; - -fn expected_absolute_path(path: &PathBuf) -> String { - std::fs::canonicalize(path) - .unwrap_or_else(|_| path.to_path_buf()) - .to_string_lossy() - .replace('\\', "/") -} - -#[test] -fn normalize_path_for_skill_id_repo_scoped_uses_relative_path() { - let repo_root = std::env::temp_dir().join("repo/root"); - let skill_path = repo_root.join(".codex/skills/doc/SKILL.md"); - - let path = normalize_path_for_skill_id( - Some("https://example.com/repo.git"), - Some(repo_root.as_path()), - &PathUri::from_host_native_path(&skill_path).expect("native skill path"), - ); - - assert_eq!(path, ".codex/skills/doc/SKILL.md"); -} - -#[test] -fn normalize_path_for_skill_id_user_scoped_uses_absolute_path() { - let skill_path = std::env::temp_dir().join("Users/abc/.codex/skills/doc/SKILL.md"); - - let path = normalize_path_for_skill_id( - /*repo_url*/ None, - /*repo_root*/ None, - &PathUri::from_host_native_path(&skill_path).expect("native skill path"), - ); - let expected = expected_absolute_path(&skill_path); - - assert_eq!(path, expected); -} - -#[test] -fn normalize_path_for_skill_id_admin_scoped_uses_absolute_path() { - let skill_path = std::env::temp_dir().join("etc/codex/skills/doc/SKILL.md"); - - let path = normalize_path_for_skill_id( - /*repo_url*/ None, - /*repo_root*/ None, - &PathUri::from_host_native_path(&skill_path).expect("native skill path"), - ); - let expected = expected_absolute_path(&skill_path); - - assert_eq!(path, expected); -} - -#[test] -fn normalize_path_for_skill_id_repo_root_not_in_skill_path_uses_absolute_path() { - let repo_root = std::env::temp_dir().join("repo/root"); - let skill_path = std::env::temp_dir().join("other/path/.codex/skills/doc/SKILL.md"); - - let path = normalize_path_for_skill_id( - Some("https://example.com/repo.git"), - Some(repo_root.as_path()), - &PathUri::from_host_native_path(&skill_path).expect("native skill path"), - ); - let expected = expected_absolute_path(&skill_path); - - assert_eq!(path, expected); -} - -/// Foreign paths keep native telemetry spelling without depending on host filesystem lookup. -#[test] -fn normalize_path_for_skill_id_foreign_path_uses_native_spelling() { - let (uri, expected) = if cfg!(windows) { - ( - "file:///Users/abc/.codex/skills/doc%20%23/SKILL.md", - "/Users/abc/.codex/skills/doc #/SKILL.md", - ) - } else { - ( - "file:///C:/Users/abc/.codex/skills/doc%20%23/SKILL.md", - "C:/Users/abc/.codex/skills/doc #/SKILL.md", - ) - }; - let path = normalize_path_for_skill_id( - /*repo_url*/ None, - /*repo_root*/ None, - &PathUri::parse(uri).expect("foreign skill URI"), - ); - - assert_eq!(path, expected); -} - -#[tokio::test] -async fn reducer_ingests_skill_invoked_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - let skill_path = std::env::temp_dir() - .ancestors() - .last() - .expect("temporary directory root") - .join("Users/abc/.codex/skills/doc/SKILL.md"); - let expected_skill_id = skill_id_for_local_skill( - /*repo_url*/ None, - /*repo_root*/ None, - &PathUri::from_host_native_path(&skill_path).expect("native skill path"), - "doc", - ); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SkillInvoked(SkillInvokedInput { - tracking, - invocations: vec![SkillInvocation { - skill_name: "doc".to_string(), - location: SkillInvocationLocation::Host { - path: PathUri::from_host_native_path(&skill_path) - .expect("native skill path"), - scope: codex_protocol::protocol::SkillScope::User, - }, - plugin_id: None, - remote_plugin_id: None, - invocation_type: InvocationType::Explicit, - }], - })), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - payload, - json!([{ - "event_type": "skill_invocation", - "skill_id": expected_skill_id, - "skill_name": "doc", - "event_params": { - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "skill_scope": "user", - "plugin_id": null, - "remote_plugin_id": null, - "thread_id": "thread-1", - "turn_id": "turn-1", - "voice_session_id": null, - "invoke_type": "explicit", - "model_slug": "gpt-5" - } - }]) - ); -} - -#[tokio::test] -async fn reducer_includes_plugin_ids_for_plugin_skill_invocations() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let tracking = test_tracking_context("thread-1", "turn-1"); - let skill_path = std::env::temp_dir() - .ancestors() - .last() - .expect("temporary directory root") - .join("Users/abc/.codex/plugins/cache/test/sample/skills/doc/SKILL.md"); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SkillInvoked(SkillInvokedInput { - tracking, - invocations: vec![SkillInvocation { - skill_name: "sample:doc".to_string(), - location: SkillInvocationLocation::Host { - path: PathUri::from_host_native_path(&skill_path) - .expect("native skill path"), - scope: codex_protocol::protocol::SkillScope::User, - }, - plugin_id: Some("sample@test".to_string()), - remote_plugin_id: Some("plugins~Plugin_sample".to_string()), - invocation_type: InvocationType::Explicit, - }], - })), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!( - ( - &payload[0]["event_params"]["plugin_id"], - &payload[0]["event_params"]["remote_plugin_id"], - ), - (&json!("sample@test"), &json!("plugins~Plugin_sample")) - ); -} diff --git a/codex-rs/analytics/src/tests/suite/threads_tests.rs b/codex-rs/analytics/src/tests/suite/threads_tests.rs deleted file mode 100644 index 9c0dd2dd..00000000 --- a/codex-rs/analytics/src/tests/suite/threads_tests.rs +++ /dev/null @@ -1,915 +0,0 @@ -//! Thread lifecycle, lineage, originator, and metadata event tests. - -use crate::events::AppServerRpcTransport; -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexRuntimeMetadata; -use crate::events::ThreadInitializedEvent; -use crate::events::ThreadInitializedEventParams; -use crate::events::TrackEventRequest; -use crate::events::subagent_thread_started_event_request; -use crate::facts::AnalyticsFact; -use crate::facts::CodeModeToolCallFact; -use crate::facts::CodeModeToolCallStatus; -use crate::facts::CodexCompactionEvent; -use crate::facts::CompactionImplementation; -use crate::facts::CompactionPhase; -use crate::facts::CompactionReason; -use crate::facts::CompactionStatus; -use crate::facts::CompactionStrategy; -use crate::facts::CompactionTrigger; -use crate::facts::CustomAnalyticsFact; -use crate::facts::SubAgentThreadStartedInput; -use crate::facts::ThreadInitializationMode; -use crate::facts::TurnResolvedConfigFact; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::ingest_code_mode_facts; -use crate::tests::support::ingest_complete_child_turn; -use crate::tests::support::ingest_completed_command_execution_item; -use crate::tests::support::ingest_initialize; -use crate::tests::support::ingest_review_prerequisites; -use crate::tests::support::sample_command_execution_item; -use crate::tests::support::sample_initialize_fact; -use crate::tests::support::sample_thread_resume_response; -use crate::tests::support::sample_thread_resume_response_with_source; -use crate::tests::support::sample_thread_start_response; -use crate::tests::support::sample_turn_resolved_config; -use crate::tests::support::sample_turn_start_request; -use crate::tests::support::sample_turn_start_response; -use crate::tests::support::sample_turn_started_notification; -use crate::tests::support::test_turn_metadata; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionSource as AppServerSessionSource; -use codex_app_server_protocol::ThreadArchivedNotification; -use codex_app_server_protocol::ThreadSource as AppServerThreadSource; -use codex_app_server_protocol::ThreadUnarchivedNotification; -use codex_login::default_client::DEFAULT_ORIGINATOR; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadSource; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn thread_initialized_event_serializes_expected_shape() { - let event = TrackEventRequest::ThreadInitialized(ThreadInitializedEvent { - event_type: "codex_thread_initialized", - event_params: ThreadInitializedEventParams { - thread_id: "thread-0".to_string(), - session_id: "session-thread-0".to_string(), - app_server_client: CodexAppServerClientMetadata { - product_client_id: DEFAULT_ORIGINATOR.to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - rpc_transport: AppServerRpcTransport::Stdio, - experimental_api_enabled: Some(true), - }, - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.1.0".to_string(), - runtime_os: "macos".to_string(), - runtime_os_version: "15.3.1".to_string(), - runtime_arch: "aarch64".to_string(), - }, - model: "gpt-5".to_string(), - ephemeral: true, - is_worktree: Some(true), - thread_source: Some(ThreadSource::Feature("automation".to_string())), - initialization_mode: ThreadInitializationMode::New, - subagent_source: None, - parent_thread_id: None, - forked_from_thread_id: None, - created_at: 1, - }, - }); - - let payload = serde_json::to_value(&event).expect("serialize thread initialized event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_thread_initialized", - "event_params": { - "thread_id": "thread-0", - "session_id": "session-thread-0", - "app_server_client": { - "product_client_id": DEFAULT_ORIGINATOR, - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "stdio", - "experimental_api_enabled": true - }, - "runtime": { - "codex_rs_version": "0.1.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64" - }, - "model": "gpt-5", - "ephemeral": true, - "is_worktree": true, - "thread_source": "automation", - "initialization_mode": "new", - "subagent_source": null, - "parent_thread_id": null, - "forked_from_thread_id": null, - "created_at": 1 - } - }) - ); -} - -#[tokio::test] -async fn thread_initialized_classifies_validated_linked_worktrees() { - let root = std::env::temp_dir().join(format!( - "codex-analytics-worktree-{}", - codex_protocol::ThreadId::new() - )); - let primary = root.join("primary"); - let linked = root.join("linked"); - let admin = primary.join(".git/worktrees/linked"); - std::fs::create_dir_all(&admin).expect("worktree administrative directory"); - std::fs::create_dir_all(&linked).expect("linked checkout"); - std::fs::write(primary.join(".git/HEAD"), "ref: refs/heads/main\n") - .expect("primary repository HEAD"); - std::fs::write(admin.join("commondir"), "../..\n").expect("common directory"); - std::fs::write( - admin.join("gitdir"), - format!("{}\n", linked.join(".git").display()), - ) - .expect("linked checkout backlink"); - std::fs::write( - linked.join(".git"), - format!("gitdir: {}\n", admin.display()), - ) - .expect("linked checkout git file"); - - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_initialize(&mut reducer, &mut events).await; - for (cwd, expected) in [ - (primary.as_path(), json!(false)), - (linked.as_path(), json!(true)), - (root.as_path(), serde_json::Value::Null), - ] { - events.clear(); - let mut response = - sample_thread_start_response("thread-1", /*ephemeral*/ false, "gpt-5"); - let ClientResponsePayload::ThreadStart(start) = &mut response else { - panic!("expected thread/start response"); - }; - start.thread.cwd = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(cwd) - .expect("absolute checkout path"); - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(response), - thread_originator: None, - }, - &mut events, - ) - .await; - let payload = serde_json::to_value(&events).expect("serialize thread event"); - assert_eq!(payload[0]["event_params"]["is_worktree"], expected); - } - - std::fs::remove_dir_all(root).expect("remove test checkout"); -} - -#[tokio::test] -async fn initialize_caches_client_and_thread_lifecycle_publishes_once_initialized() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - "thread-no-client", - /*ephemeral*/ false, - "gpt-5", - )), - thread_originator: None, - }, - &mut events, - ) - .await; - assert!(events.is_empty(), "thread events should require initialize"); - - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 7, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-tui".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: Some(InitializeCapabilities { - required_human_approval: false, - explicit_gateway_oauth: false, - experimental_api: false, - request_attestation: false, - opt_out_notification_methods: None, - mcp_server_openai_form_elicitation: false, - extensions: None, - }), - }, - product_client_id: DEFAULT_ORIGINATOR.to_string(), - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.99.0".to_string(), - runtime_os: "linux".to_string(), - runtime_os_version: "24.04".to_string(), - runtime_arch: "x86_64".to_string(), - }, - rpc_transport: AppServerRpcTransport::Websocket, - }, - &mut events, - ) - .await; - assert!(events.is_empty(), "initialize should not publish by itself"); - - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(2), - response: Box::new(sample_thread_resume_response( - "thread-1", /*ephemeral*/ true, "gpt-5", - )), - thread_originator: None, - }, - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_thread_initialized"); - assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1"); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["product_client_id"], - DEFAULT_ORIGINATOR - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["client_name"], - "codex-tui" - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["client_version"], - "1.0.0" - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["rpc_transport"], - "websocket" - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["experimental_api_enabled"], - false - ); - assert_eq!( - payload[0]["event_params"]["runtime"]["codex_rs_version"], - "0.99.0" - ); - assert_eq!(payload[0]["event_params"]["runtime"]["runtime_os"], "linux"); - assert_eq!( - payload[0]["event_params"]["runtime"]["runtime_os_version"], - "24.04" - ); - assert_eq!( - payload[0]["event_params"]["runtime"]["runtime_arch"], - "x86_64" - ); -} - -#[tokio::test] -async fn thread_originator_overrides_shared_connection_across_thread_events() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest(sample_initialize_fact(/*connection_id*/ 7), &mut events) - .await; - for (request_id, thread_id, thread_originator) in [ - (1, "thread-work", Some(TEST_PRODUCT_CLIENT_ID.to_string())), - (2, "thread-default", None), - ] { - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(request_id), - response: Box::new(sample_thread_start_response( - thread_id, /*ephemeral*/ false, "gpt-5", - )), - thread_originator, - }, - &mut events, - ) - .await; - } - - let initialized = serde_json::to_value(&events).expect("serialize thread events"); - assert_eq!( - initialized - .as_array() - .expect("thread events") - .iter() - .map(|event| { - json!({ - "thread_id": event["event_params"]["thread_id"], - "app_server_client": event["event_params"]["app_server_client"], - }) - }) - .collect::>(), - vec![ - json!({ - "thread_id": "thread-work", - "app_server_client": { - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "websocket", - "experimental_api_enabled": false, - }, - }), - json!({ - "thread_id": "thread-default", - "app_server_client": { - "product_client_id": DEFAULT_ORIGINATOR, - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "websocket", - "experimental_api_enabled": false, - }, - }), - ] - ); - - events.clear(); - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(3), - request: Box::new(sample_turn_start_request( - "thread-work", - /*request_id*/ 3, - )), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-1")), - thread_originator: None, - }, - &mut events, - ) - .await; - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-work", "item-work") - .await; - ingest_complete_child_turn(&mut reducer, &mut events, "thread-work", "turn-1").await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::Compaction(Box::new( - CodexCompactionEvent { - thread_id: "thread-work".to_string(), - turn_id: "turn-compact".to_string(), - trigger: CompactionTrigger::Manual, - reason: CompactionReason::UserRequested, - implementation: CompactionImplementation::Responses, - phase: CompactionPhase::StandaloneTurn, - strategy: CompactionStrategy::Memento, - status: CompactionStatus::Completed, - codex_error_kind: None, - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - active_context_tokens_before: 131_000, - active_context_tokens_after: 64_000, - retained_image_count: None, - compaction_summary_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - started_at: 100, - completed_at: 101, - duration_ms: Some(1200), - }, - ))), - &mut events, - ) - .await; - - let lifecycle = serde_json::to_value(&events).expect("serialize lifecycle events"); - assert_eq!( - lifecycle - .as_array() - .expect("lifecycle events") - .iter() - .map(|event| { - json!({ - "event_type": event["event_type"], - "product_client_id": - event["event_params"]["app_server_client"]["product_client_id"], - }) - }) - .collect::>(), - vec![ - json!({ - "event_type": "codex_command_execution_event", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - }), - json!({ - "event_type": "codex_turn_event", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - }), - json!({ - "event_type": "codex_compaction_event", - "product_client_id": TEST_PRODUCT_CLIENT_ID, - }), - ] - ); - - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - response: Box::new(sample_thread_resume_response_with_source( - "thread-private-source", - /*ephemeral*/ false, - "gpt-5", - AppServerSessionSource::Exec, - Some(AppServerThreadSource::Feature( - "private customer feature label".to_string(), - )), - Some("019ee5cf-4d15-77a2-8023-01a9f79b6e7d".to_string()), - )), - thread_originator: Some(TEST_PRODUCT_CLIENT_ID.to_string()), - }, - &mut events, - ) - .await; - events.clear(); - - for notification in [ - ServerNotification::ThreadArchived(ThreadArchivedNotification { - thread_id: "thread-work".to_string(), - }), - ServerNotification::ThreadUnarchived(ThreadUnarchivedNotification { - thread_id: "thread-default".to_string(), - }), - ServerNotification::ThreadArchived(ThreadArchivedNotification { - thread_id: "thread-private-source".to_string(), - }), - ServerNotification::ThreadUnarchived(ThreadUnarchivedNotification { - thread_id: "thread-without-context".to_string(), - }), - ] { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(notification)), - &mut events, - ) - .await; - } - - let mut archives = serde_json::to_value(&events).expect("serialize archive events"); - for event in archives.as_array_mut().expect("archive events") { - assert!(event["event_params"]["occurred_at_ms"].is_u64()); - event["event_params"] - .as_object_mut() - .expect("archive event params") - .remove("occurred_at_ms"); - } - assert_eq!( - archives, - json!([ - { - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": "thread-work", - "action": "archived", - "app_server_client": initialized[0]["event_params"]["app_server_client"], - "runtime": initialized[0]["event_params"]["runtime"], - "thread_source": "user", - }, - }, - { - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": "thread-default", - "action": "unarchived", - "app_server_client": initialized[1]["event_params"]["app_server_client"], - "runtime": initialized[1]["event_params"]["runtime"], - "thread_source": "user", - }, - }, - { - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": "thread-private-source", - "action": "archived", - "app_server_client": initialized[0]["event_params"]["app_server_client"], - "runtime": initialized[0]["event_params"]["runtime"], - "parent_thread_id": "019ee5cf-4d15-77a2-8023-01a9f79b6e7d", - }, - }, - { - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": "thread-without-context", - "action": "unarchived", - }, - } - ]) - ); -} - -#[test] -fn subagent_thread_started_review_serializes_expected_shape() { - let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-review".to_string(), - parent_thread_id: None, - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::Subagent), - subagent_source: SubAgentSource::Review, - initialization_mode: ThreadInitializationMode::New, - created_at: 123, - }, - )); - - let payload = serde_json::to_value(&event).expect("serialize review subagent event"); - assert_eq!(payload["event_params"]["thread_source"], "subagent"); - assert_eq!( - payload["event_params"]["app_server_client"]["product_client_id"], - "codex-tui" - ); - assert_eq!( - payload["event_params"]["app_server_client"]["client_name"], - "codex-tui" - ); - assert_eq!( - payload["event_params"]["app_server_client"]["client_version"], - "1.0.0" - ); - assert_eq!( - payload["event_params"]["app_server_client"]["rpc_transport"], - "in_process" - ); - assert_eq!(payload["event_params"]["created_at"], 123); - assert_eq!(payload["event_params"]["initialization_mode"], "new"); - assert_eq!(payload["event_params"]["subagent_source"], "review"); - assert_eq!(payload["event_params"]["parent_thread_id"], json!(null)); - assert_eq!( - payload["event_params"]["forked_from_thread_id"], - json!(null) - ); -} - -#[test] -fn subagent_thread_started_thread_spawn_serializes_thread_lineage() { - let parent_thread_id = - codex_protocol::ThreadId::from_string("11111111-1111-1111-1111-111111111111") - .expect("valid thread id"); - let forked_from_thread_id = - codex_protocol::ThreadId::from_string("22222222-2222-4222-8222-222222222222") - .expect("valid thread id"); - let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-spawn".to_string(), - parent_thread_id: Some(parent_thread_id.to_string()), - forked_from_thread_id: Some(forked_from_thread_id.to_string()), - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: true, - thread_source: Some(ThreadSource::Subagent), - subagent_source: SubAgentSource::ThreadSpawn { - parent_thread_id, - depth: 1, - agent_path: None, - agent_nickname: None, - agent_role: None, - }, - initialization_mode: ThreadInitializationMode::Resumed, - created_at: 124, - }, - )); - - let payload = serde_json::to_value(&event).expect("serialize thread spawn subagent event"); - assert_eq!(payload["event_params"]["thread_id"], "thread-spawn"); - assert_eq!(payload["event_params"]["thread_source"], "subagent"); - assert_eq!(payload["event_params"]["initialization_mode"], "resumed"); - assert_eq!(payload["event_params"]["created_at"], 124); - assert_eq!(payload["event_params"]["subagent_source"], "thread_spawn"); - assert_eq!( - payload["event_params"]["parent_thread_id"], - "11111111-1111-1111-1111-111111111111" - ); - assert_eq!( - payload["event_params"]["forked_from_thread_id"], - "22222222-2222-4222-8222-222222222222" - ); - assert_eq!(payload["event_params"]["session_id"], "session-root"); -} - -#[test] -fn subagent_thread_started_memory_consolidation_serializes_expected_shape() { - let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-memory".to_string(), - parent_thread_id: None, - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::Subagent), - subagent_source: SubAgentSource::MemoryConsolidation, - initialization_mode: ThreadInitializationMode::New, - created_at: 125, - }, - )); - - let payload = - serde_json::to_value(&event).expect("serialize memory consolidation subagent event"); - assert_eq!( - payload["event_params"]["subagent_source"], - "memory_consolidation" - ); - assert_eq!(payload["event_params"]["parent_thread_id"], json!(null)); -} - -#[test] -fn subagent_thread_started_other_serializes_expected_shape() { - let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-guardian".to_string(), - parent_thread_id: None, - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::GuardianReview), - subagent_source: SubAgentSource::Other("guardian".to_string()), - initialization_mode: ThreadInitializationMode::New, - created_at: 126, - }, - )); - - let payload = serde_json::to_value(&event).expect("serialize other subagent event"); - assert_eq!(payload["event_params"]["thread_source"], "guardian_review"); - assert_eq!(payload["event_params"]["subagent_source"], "guardian"); - assert_eq!(payload["event_params"]["parent_thread_id"], json!(null)); -} - -#[test] -fn subagent_thread_started_other_serializes_explicit_parent_thread_id() { - let parent_thread_id = - codex_protocol::ThreadId::from_string("33333333-3333-4333-8333-333333333333") - .expect("valid thread id"); - let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-guardian".to_string(), - parent_thread_id: Some(parent_thread_id.to_string()), - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::GuardianReview), - subagent_source: SubAgentSource::Other("guardian".to_string()), - initialization_mode: ThreadInitializationMode::New, - created_at: 126, - }, - )); - - let payload = serde_json::to_value(&event).expect("serialize auto-review subagent event"); - assert_eq!(payload["event_params"]["subagent_source"], "guardian"); - assert_eq!( - payload["event_params"]["parent_thread_id"], - "33333333-3333-4333-8333-333333333333" - ); -} - -#[tokio::test] -async fn subagent_thread_started_publishes_without_initialize() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SubAgentThreadStarted( - SubAgentThreadStartedInput { - session_id: "session-root".to_string(), - thread_id: "thread-review".to_string(), - parent_thread_id: None, - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::Subagent), - subagent_source: SubAgentSource::Review, - initialization_mode: ThreadInitializationMode::New, - created_at: 127, - }, - )), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_type"], "codex_thread_initialized"); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["product_client_id"], - "codex-tui" - ); - assert_eq!(payload[0]["event_params"]["thread_source"], "subagent"); - assert_eq!(payload[0]["event_params"]["subagent_source"], "review"); -} - -#[tokio::test] -async fn subagent_tool_items_inherit_parent_connection_metadata() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::SubAgentThreadStarted( - SubAgentThreadStartedInput { - session_id: "session-thread-1".to_string(), - thread_id: "thread-subagent".to_string(), - parent_thread_id: Some("thread-1".to_string()), - forked_from_thread_id: None, - product_client_id: "codex-tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - model: "gpt-5".to_string(), - ephemeral: false, - thread_source: Some(ThreadSource::Subagent), - subagent_source: SubAgentSource::Review, - initialization_mode: ThreadInitializationMode::New, - created_at: 128, - }, - )), - &mut events, - ) - .await; - ingest_review_prerequisites(&mut reducer, &mut events).await; - for (thread_id, turn_id, root_turn_id) in [ - ("thread-1", "turn-parent", "parent-current-root"), - ("thread-subagent", "turn-subagent", "child-causal-root"), - ] { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata: test_turn_metadata(Some(root_turn_id)), - ..sample_turn_resolved_config(thread_id, turn_id) - }, - ))), - &mut events, - ) - .await; - } - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-subagent", - "turn-subagent", - ))), - &mut events, - ) - .await; - - ingest_code_mode_facts( - &mut reducer, - &mut events, - [CodeModeToolCallFact::SamplingResponseCompleted { - thread_id: "thread-subagent".into(), - turn_id: "turn-subagent".into(), - response_id: "response-subagent".into(), - tool_call_ids: vec!["item-1".into(), "exec-1".into()], - }], - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-subagent".to_string(), - "turn-subagent".to_string(), - sample_command_execution_item( - CommandExecutionStatus::InProgress, - /*exit_code*/ None, - /*duration_ms*/ None, - ), - /*started_at_ms*/ 1_000, - ), - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-subagent".to_string(), - "turn-subagent".to_string(), - sample_command_execution_item( - CommandExecutionStatus::Completed, - Some(0), - Some(42), - ), - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_042, - ), - ))), - &mut events, - ) - .await; - - ingest_code_mode_facts( - &mut reducer, - &mut events, - [CodeModeToolCallFact::Completed { - thread_id: "thread-subagent".into(), - turn_id: "turn-subagent".into(), - turn_metadata: test_turn_metadata(Some("child-causal-root")), - call_id: "exec-1".into(), - cell_id: None, - tool_name: "exec".into(), - started_at_ms: 1_000, - completed_at_ms: 1_042, - status: CodeModeToolCallStatus::Completed, - }], - ) - .await; - reducer.flush(&mut events); - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 2); - assert_eq!( - payload - .as_array() - .expect("events array") - .iter() - .map(|event| json!({ - "turn_id": event["event_params"]["turn_id"], - "root_turn_id": event["event_params"]["root_turn_id"], - "tool_event_type": event["event_params"]["tool_event_type"], - })) - .collect::>(), - vec![ - json!({"turn_id": "turn-subagent", "root_turn_id": "child-causal-root", "tool_event_type": "model_tool_call"}), - json!({"turn_id": "turn-subagent", "root_turn_id": "child-causal-root", "tool_event_type": "model_tool_call"}), - ] - ); - assert_eq!(payload[0]["event_type"], "codex_command_execution_event"); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-subagent"); - assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1"); - assert_eq!(payload[0]["event_params"]["thread_source"], "subagent"); - assert_eq!(payload[0]["event_params"]["subagent_source"], "review"); - assert_eq!(payload[0]["event_params"]["parent_thread_id"], "thread-1"); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["client_name"], - "codex-tui" - ); - assert_eq!(payload[1]["event_type"], "codex_dynamic_tool_call_event"); - assert_eq!(payload[1]["event_params"]["parent_thread_id"], "thread-1"); -} diff --git a/codex-rs/analytics/src/tests/suite/tools_tests.rs b/codex-rs/analytics/src/tests/suite/tools_tests.rs deleted file mode 100644 index d84996e7..00000000 --- a/codex-rs/analytics/src/tests/suite/tools_tests.rs +++ /dev/null @@ -1,1040 +0,0 @@ -//! Tool item, Code Mode correlation, and artifact event tests. - -use crate::events::AppServerRpcTransport; -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexCommandExecutionEventParams; -use crate::events::CodexCommandExecutionEventRequest; -use crate::events::CodexRuntimeMetadata; -use crate::events::CodexToolItemEventBase; -use crate::events::FinalApprovalOutcome; -use crate::events::ToolEventType; -use crate::events::ToolItemTerminalStatus; -use crate::events::TrackEventRequest; -use crate::events::current_runtime_metadata; -use crate::facts::AnalyticsFact; -use crate::facts::ArtifactOperation; -use crate::facts::ArtifactOperationInput; -use crate::facts::ArtifactOperationLifecycle; -use crate::facts::CodeModeToolCallFact; -use crate::facts::CodeModeToolCallStatus; -use crate::facts::ControlToolCallFact; -use crate::facts::ControlToolCallStatus; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ElicitationType; -use crate::facts::McpToolCallElicitation; -use crate::facts::TurnResolvedConfigFact; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::TEST_PRODUCT_CLIENT_ID; -use crate::tests::support::ingest_code_mode_facts; -use crate::tests::support::ingest_completed_command_execution_item; -use crate::tests::support::ingest_review_prerequisites; -use crate::tests::support::ingest_turn_prerequisites; -use crate::tests::support::sample_command_execution_item; -use crate::tests::support::sample_turn_completed_notification; -use crate::tests::support::sample_turn_resolved_config; -use crate::tests::support::sample_turn_started_notification; -use crate::tests::support::test_tracking_context; -use crate::tests::support::test_turn_metadata; -use codex_app_server_protocol::CollabAgentTool; -use codex_app_server_protocol::CollabAgentToolCallStatus; -use codex_app_server_protocol::CommandAction; -use codex_app_server_protocol::CommandExecutionSource; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::GeneratedImageRef; -use codex_app_server_protocol::ImageGenerationItem; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::McpToolCallAppContext; -use codex_app_server_protocol::McpToolCallStatus; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_protocol::protocol::ThreadSource; -use codex_protocol::sandbox::SandboxType; -use codex_utils_absolute_path::test_support::PathBufExt; -use codex_utils_absolute_path::test_support::test_path_buf; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn sample_command_execution_item_with_actions( - status: CommandExecutionStatus, - exit_code: Option, - duration_ms: Option, - command_actions: Vec, - plugin_id: Option<&str>, - script_path: Option<&str>, - sandbox_type: Option, -) -> ThreadItemPayload { - let mut item = sample_command_execution_item(status, exit_code, duration_ms); - let ThreadItemPayload::CommandExecution { - command_actions: item_command_actions, - plugin_id: item_plugin_id, - script_path: item_script_path, - sandbox_type: item_sandbox_type, - .. - } = &mut item - else { - unreachable!("sample command execution item should be CommandExecution"); - }; - *item_command_actions = command_actions; - *item_plugin_id = plugin_id.map(str::to_string); - *item_script_path = script_path.map(str::to_string); - *item_sandbox_type = sandbox_type; - item -} - -fn sampling_response( - turn_id: &str, - response_id: &str, - tool_call_ids: &[&str], -) -> CodeModeToolCallFact { - CodeModeToolCallFact::SamplingResponseCompleted { - thread_id: "thread-1".into(), - turn_id: turn_id.into(), - response_id: response_id.into(), - tool_call_ids: tool_call_ids.iter().map(|id| (*id).into()).collect(), - } -} - -#[test] -fn command_execution_event_serializes_expected_shape() { - let event = TrackEventRequest::CommandExecution(CodexCommandExecutionEventRequest { - event_type: "codex_command_execution_event", - event_params: CodexCommandExecutionEventParams { - sandbox_backend: None, - model_slug: None, - reasoning_effort: None, - base: CodexToolItemEventBase { - turn_trigger: None, - thread_id: "thread-1".to_string(), - session_id: "session-thread-1".to_string(), - turn_id: "turn-1".to_string(), - root_turn_id: Some("root-turn".to_string()), - item_id: "item-1".to_string(), - cell_id: None, - parent_call_id: None, - originating_response_id: None, - subsequent_response_id: None, - app_server_client: CodexAppServerClientMetadata { - product_client_id: "codex_tui".to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.2.3".to_string()), - rpc_transport: AppServerRpcTransport::Websocket, - experimental_api_enabled: Some(true), - }, - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.99.0".to_string(), - runtime_os: "macos".to_string(), - runtime_os_version: "15.3.1".to_string(), - runtime_arch: "aarch64".to_string(), - }, - thread_source: Some(ThreadSource::User), - subagent_source: None, - parent_thread_id: None, - tool_name: "shell".to_string(), - tool_event_type: Some(ToolEventType::ModelToolCall), - started_at_ms: 123_000, - completed_at_ms: 125_000, - duration_ms: Some(2000), - execution_duration_ms: Some(1900), - review_count: 0, - guardian_review_count: 0, - user_review_count: 0, - final_approval_outcome: FinalApprovalOutcome::NotNeeded, - terminal_status: ToolItemTerminalStatus::Completed, - failure_kind: None, - requested_additional_permissions: false, - requested_network_access: false, - }, - plugin_id: Some("sample@openai-curated".to_string()), - script_path: Some("scripts/run.py".to_string()), - command_execution_source: CommandExecutionSource::Agent, - exit_code: Some(0), - command_total_action_count: 4, - command_read_action_count: 1, - command_list_files_action_count: 1, - command_search_action_count: 1, - command_unknown_action_count: 1, - }, - }); - - let payload = serde_json::to_value(&event).expect("serialize command execution event"); - let mut expected = json!({ - "event_type": "codex_command_execution_event", - "event_params": { - "sandbox_backend": null, - "model_slug": null, - "reasoning_effort": null, - "thread_id": "thread-1", - "session_id": "session-thread-1", - "turn_id": "turn-1", - "root_turn_id": "root-turn", - "item_id": "item-1", - "cell_id": null, - "parent_call_id": null, - "originating_response_id": null, - "subsequent_response_id": null, - "app_server_client": { - "product_client_id": "codex_tui", - "client_name": "codex-tui", - "client_version": "1.2.3", - "rpc_transport": "websocket", - "experimental_api_enabled": true - }, - "runtime": { - "codex_rs_version": "0.99.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64" - }, - "thread_source": "user", - "subagent_source": null, - "parent_thread_id": null, - "tool_name": "shell", - "started_at_ms": 123000, - "completed_at_ms": 125000, - "duration_ms": 2000, - "execution_duration_ms": 1900, - "review_count": 0, - "guardian_review_count": 0, - "user_review_count": 0, - "final_approval_outcome": "not_needed", - "terminal_status": "completed", - "failure_kind": null, - "requested_additional_permissions": false, - "requested_network_access": false, - "plugin_id": "sample@openai-curated", - "script_path": "scripts/run.py", - "command_execution_source": "agent", - "exit_code": 0, - "command_total_action_count": 4, - "command_read_action_count": 1, - "command_list_files_action_count": 1, - "command_search_action_count": 1, - "command_unknown_action_count": 1 - } - }); - // Keep this field separate to stay within json!'s macro recursion limit. - expected["event_params"]["tool_event_type"] = json!("model_tool_call"); - assert_eq!(payload, expected); -} - -#[tokio::test] -async fn cua_tool_call_lifecycle_requires_a_start_and_deduplicates_replay() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - events.clear(); - - let item = |status| ThreadItemPayload::McpToolCall { - id: "cua-call".into(), - server: "codex_apps".into(), - tool: "js".into(), - status, - arguments: json!({"script": "synthetic-private-input"}), - app_context: Some(McpToolCallAppContext { - connector_id: "connector_openai_browser".into(), - link_id: None, - resource_uri: None, - app_name: None, - action_name: None, - }), - mcp_app_resource_uri: None, - mcp_app_ui: None, - plugin_id: Some("browser@openai-curated".into()), - read_only_hint: None, - result: None, - error: None, - duration_ms: None, - }; - let started = ServerNotification::ItemStarted(ItemStartedNotification::new( - "thread-2".into(), - "turn-2".into(), - item(McpToolCallStatus::InProgress), - /*started_at_ms*/ 1_000, - )); - let completed = ServerNotification::ItemCompleted(ItemCompletedNotification::new( - "thread-2".into(), - "turn-2".into(), - item(McpToolCallStatus::Completed), - Some(1_000), - /*completed_at_ms*/ 1_100, - )); - for notification in [ - completed.clone(), // Missing start must not poison later deduplication. - started.clone(), - started.clone(), - completed.clone(), - started, // Replay after a valid terminal. - completed, - ] { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(notification)), - &mut events, - ) - .await; - } - - let [ - TrackEventRequest::CuaToolCallStarted(start), - TrackEventRequest::McpToolCall(terminal), - ] = events.as_slice() - else { - panic!("expected exactly one CUA start and one terminal"); - }; - assert_eq!( - ( - start.event_type, - start.event_params.connector_id.as_deref(), - start.event_params.plugin_id.as_deref(), - start.event_params.started_at_ms, - terminal.event_params.base.started_at_ms, - ), - ( - "codex_cua_tool_call_started", - Some("connector_openai_browser"), - Some("browser@openai-curated"), - 1_000, - 1_000, - ) - ); - assert!( - !serde_json::to_string(&events) - .expect("serialize CUA lifecycle events") - .contains("synthetic-private-input") - ); -} - -#[tokio::test] -async fn item_lifecycle_notifications_publish_command_execution_event() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-1", "turn-1", - ))), - &mut events, - ) - .await; - for model in ["invoking-model", "later-model"] { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-1".to_string(), - "turn-1".to_string(), - { - let mut item = sample_command_execution_item( - CommandExecutionStatus::InProgress, - /*exit_code*/ None, - /*duration_ms*/ None, - ); - if let ThreadItemPayload::CommandExecution { model_context, .. } = - &mut item - { - *model_context = - Some(codex_protocol::items::ModelInvocationContext { - model_slug: model.to_string(), - reasoning_effort: Some("max".to_string()), - }); - } - item - }, - /*started_at_ms*/ 1_000, - ), - ))), - &mut events, - ) - .await; - } - assert!( - events.is_empty(), - "tool item event should emit on completion" - ); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-1".to_string(), - "turn-1".to_string(), - sample_command_execution_item_with_actions( - CommandExecutionStatus::Completed, - Some(0), - Some(42), - vec![ - CommandAction::Read { - command: "cat README.md".to_string(), - name: "README.md".to_string(), - path: test_path_buf("/tmp/README.md").abs().into(), - }, - CommandAction::ListFiles { - command: "ls".to_string(), - path: None, - }, - CommandAction::Search { - command: "rg TODO".to_string(), - query: Some("TODO".to_string()), - path: None, - }, - CommandAction::Unknown { - command: "cargo test".to_string(), - }, - ], - Some("sample@openai-curated"), - Some("scripts/run.py"), - Some(SandboxType::WindowsMxc), - ), - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_045, - ), - ))), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - assert_eq!(payload[0]["event_params"]["model_slug"], "invoking-model"); - assert_eq!(payload[0]["event_params"]["sandbox_backend"], "windows_mxc"); - assert_eq!(payload[0]["event_params"]["reasoning_effort"], "max"); - assert_eq!(payload[0]["event_type"], "codex_command_execution_event"); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-1"); - assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1"); - assert_eq!(payload[0]["event_params"]["turn_id"], "turn-1"); - assert_eq!(payload[0]["event_params"]["item_id"], "item-1"); - assert_eq!(payload[0]["event_params"]["tool_name"], "shell"); - assert_eq!( - payload[0]["event_params"]["plugin_id"], - "sample@openai-curated" - ); - assert_eq!(payload[0]["event_params"]["script_path"], "scripts/run.py"); - assert_eq!( - payload[0]["event_params"]["command_execution_source"], - "agent" - ); - assert_eq!(payload[0]["event_params"]["terminal_status"], "completed"); - assert_eq!( - payload[0]["event_params"]["final_approval_outcome"], - "unknown" - ); - assert_eq!( - payload[0]["event_params"]["failure_kind"], - serde_json::Value::Null - ); - assert_eq!(payload[0]["event_params"]["exit_code"], 0); - assert_eq!(payload[0]["event_params"]["command_total_action_count"], 4); - assert_eq!(payload[0]["event_params"]["command_read_action_count"], 1); - assert_eq!( - payload[0]["event_params"]["command_list_files_action_count"], - 1 - ); - assert_eq!(payload[0]["event_params"]["command_search_action_count"], 1); - assert_eq!( - payload[0]["event_params"]["command_unknown_action_count"], - 1 - ); - assert_eq!(payload[0]["event_params"]["started_at_ms"], 1_000); - assert_eq!(payload[0]["event_params"]["completed_at_ms"], 1_045); - assert_eq!(payload[0]["event_params"]["duration_ms"], 45); - assert_eq!(payload[0]["event_params"]["execution_duration_ms"], 42); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["client_name"], - "codex-tui" - ); - assert_eq!(payload[0]["event_params"]["thread_source"], "user"); -} - -#[tokio::test] -async fn collaborator_tool_events_keep_response_ids_when_completion_races_sampling() { - for response_first in [false, true] { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-1", "turn-1", - ))), - &mut events, - ) - .await; - let item = ThreadItemPayload::CollabAgentToolCall { - id: "call-1".into(), - tool: CollabAgentTool::SendMessage, - status: CollabAgentToolCallStatus::Failed, - sender_thread_id: "thread-1".into(), - receiver_thread_ids: Vec::new(), - prompt: None, - model: None, - reasoning_effort: None, - agents_states: Default::default(), - }; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-1".into(), - "turn-1".into(), - item.clone(), - /*started_at_ms*/ 1_000, - ), - ))), - &mut events, - ) - .await; - let response = AnalyticsFact::Custom(CustomAnalyticsFact::CodeModeToolCall( - sampling_response("turn-1", "response-1", &["call-1"]), - )); - let completion = AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-1".into(), - "turn-1".into(), - item, - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_010, - ), - ))); - let facts = if response_first { - [response, completion] - } else { - [completion, response] - }; - for fact in facts { - reducer.ingest(fact, &mut events).await; - assert!(events.is_empty(), "emitted before response correlation"); - } - ingest_code_mode_facts( - &mut reducer, - &mut events, - [sampling_response("turn-1", "response-2", &[])], - ) - .await; - let payload = serde_json::to_value(&events).expect("serialize collaborator event"); - assert_eq!(payload.as_array().expect("events array").len(), 1); - let params = &payload[0]["event_params"]; - assert_eq!( - json!({ - "type": payload[0]["event_type"], - "item": params["item_id"], - "origin": params["originating_response_id"], - "subsequent": params["subsequent_response_id"], - "status": params["terminal_status"], - "tool_event_type": params["tool_event_type"], - }), - json!({ - "type": "codex_collab_agent_tool_call_event", - "item": "call-1", - "origin": "response-1", - "subsequent": "response-2", - "status": "failed", - "tool_event_type": "model_tool_call", - }), - ); - } -} - -#[tokio::test] -async fn code_mode_exec_wait_and_child_events_share_cell_and_response_ids() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata: test_turn_metadata(Some("root-a")), - ..sample_turn_resolved_config("thread-1", "turn-1") - }, - ))), - &mut events, - ) - .await; - - let completed = |turn_id: &str, root_turn_id: &str, call_id: &str, tool_name: &str| { - CodeModeToolCallFact::Completed { - thread_id: "thread-1".into(), - turn_id: turn_id.into(), - turn_metadata: test_turn_metadata(Some(root_turn_id)), - call_id: call_id.into(), - cell_id: Some("cell-1".into()), - tool_name: tool_name.into(), - started_at_ms: 1_000, - completed_at_ms: 1_010, - status: CodeModeToolCallStatus::Completed, - } - }; - ingest_code_mode_facts( - &mut reducer, - &mut events, - [ - sampling_response("turn-1", "resp-a", &["exec-1"]), - CodeModeToolCallFact::CellStarted { - thread_id: "thread-1".into(), - turn_id: "turn-1".into(), - call_id: "exec-1".into(), - cell_id: "cell-1".into(), - }, - CodeModeToolCallFact::ChildStarted { - thread_id: "thread-1".into(), - turn_id: "turn-1".into(), - call_id: "child-1".into(), - cell_id: "cell-1".into(), - }, - completed("turn-1", "root-a", "exec-1", "exec"), - ], - ) - .await; - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "child-1").await; - assert!(events.is_empty()); - - ingest_code_mode_facts( - &mut reducer, - &mut events, - [ - sampling_response("turn-1", "resp-b", &[]), - sampling_response("turn-2", "resp-c", &["wait-1"]), - completed("turn-2", "root-b", "wait-1", "wait"), - sampling_response("turn-2", "resp-d", &[]), - ], - ) - .await; - - let actual = events - .iter() - .map(|event| { - let event = serde_json::to_value(event).expect("serialize tool event"); - serde_json::json!({ - "item": event["event_params"]["item_id"], - "tool_event_type": event["event_params"]["tool_event_type"], - "root": event["event_params"]["root_turn_id"], - "cell": event["event_params"]["cell_id"], - "parent": event["event_params"]["parent_call_id"], - "origin": event["event_params"]["originating_response_id"], - "subsequent": event["event_params"]["subsequent_response_id"], - }) - }) - .collect::>(); - assert_eq!( - actual, - vec![ - serde_json::json!({"tool_event_type":"model_tool_call","item":"exec-1","root":"root-a","cell":"cell-1","parent":null,"origin":"resp-a","subsequent":"resp-b"}), - serde_json::json!({"tool_event_type":"inner_tool_call","item":"child-1","root":"root-a","cell":"cell-1","parent":"exec-1","origin":"resp-a","subsequent":"resp-b"}), - serde_json::json!({"tool_event_type":"model_tool_call","item":"wait-1","root":"root-b","cell":"cell-1","parent":"exec-1","origin":"resp-c","subsequent":"resp-d"}), - ] - ); -} - -#[tokio::test] -async fn tool_event_types_require_exact_unambiguous_call_origin() { - for (sampled_ids, child_ids, expected) in [ - ( - vec!["command-1", "control-1"], - vec![], - json!("model_tool_call"), - ), - ( - vec![], - vec!["command-1", "control-1"], - json!("inner_tool_call"), - ), - (vec![], vec![], json!(null)), - ( - vec!["command-1", "control-1"], - vec!["command-1", "control-1"], - json!(null), - ), - (vec!["other-call"], vec!["other-child"], json!(null)), - ] { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - ingest_code_mode_facts( - &mut reducer, - &mut events, - [ - sampling_response("turn-1", "response-1", &sampled_ids), - CodeModeToolCallFact::CellStarted { - thread_id: "thread-1".into(), - turn_id: "turn-1".into(), - call_id: "exec-1".into(), - cell_id: "cell-1".into(), - }, - ], - ) - .await; - ingest_code_mode_facts( - &mut reducer, - &mut events, - child_ids - .into_iter() - .map(|call_id| CodeModeToolCallFact::ChildStarted { - thread_id: "thread-1".into(), - turn_id: "turn-1".into(), - call_id: call_id.into(), - cell_id: "cell-1".into(), - }), - ) - .await; - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "command-1") - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall(ControlToolCallFact { - thread_id: "thread-1".into(), - turn_id: "turn-1".into(), - turn_metadata: test_turn_metadata(/*root_turn_id*/ None), - call_id: "control-1".into(), - cell_id: Some("cell-1".into()), - tool_name: "view_image".into(), - started_at_ms: 1_000, - completed_at_ms: 1_042, - status: ControlToolCallStatus::Completed, - })), - &mut events, - ) - .await; - reducer.flush(&mut events); - let payload = serde_json::to_value(&events).expect("serialize tool events"); - assert_eq!( - payload - .as_array() - .expect("events") - .iter() - .map(|event| json!({ - "event": event["event_type"], - "type": event["event_params"]["tool_event_type"], - "status": event["event_params"]["terminal_status"], - "duration": event["event_params"]["duration_ms"], - })) - .collect::>(), - vec![ - json!({"event": "codex_command_execution_event", "type": expected, "status": "completed", "duration": 42}), - json!({"event": "codex_control_tool_call_event", "type": expected, "status": "completed", "duration": 42}), - ], - ); - } -} - -#[tokio::test] -async fn tool_event_emitted_before_sampling_evidence_keeps_unknown_origin() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_review_prerequisites(&mut reducer, &mut events).await; - ingest_completed_command_execution_item(&mut reducer, &mut events, "thread-1", "call-1").await; - assert_eq!(events.len(), 1); - ingest_code_mode_facts( - &mut reducer, - &mut events, - [sampling_response("turn-1", "response-1", &["call-1"])], - ) - .await; - reducer.flush(&mut events); - let payload = serde_json::to_value(&events).expect("serialize tool events"); - assert_eq!( - payload - .as_array() - .expect("events") - .iter() - .map(|event| json!({ - "item": event["event_params"]["item_id"], - "type": event["event_params"]["tool_event_type"], - "origin": event["event_params"]["originating_response_id"], - })) - .collect::>(), - vec![json!({"item": "call-1", "type": null, "origin": null})], - ); -} - -#[tokio::test] -async fn mcp_elicitation_classification_survives_turn_completion_and_preserves_call_grain() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - - let mut turn_metadata = test_turn_metadata(/*root_turn_id*/ None); - std::sync::Arc::get_mut(&mut turn_metadata) - .expect("unique metadata") - .turn_trigger = Some("automation_cron_scheduled".to_string()); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata, - ..sample_turn_resolved_config("thread-2", "turn-2") - }, - ))), - &mut events, - ) - .await; - - let mut items = Vec::new(); - for (item_id, connector_id, elicitation_type) in [ - ("auth", "calendar", Some(ElicitationType::AuthOrLink)), - ("retry", "calendar", None), - ("denied", "drive", Some(ElicitationType::Approval)), - ] { - let item = ThreadItemPayload::McpToolCall { - id: item_id.to_string(), - server: "server".to_string(), - tool: "search".to_string(), - status: McpToolCallStatus::Completed, - arguments: json!({ "token": "synthetic-private-input" }), - app_context: Some(McpToolCallAppContext { - connector_id: connector_id.to_string(), - link_id: None, - resource_uri: None, - app_name: None, - action_name: None, - }), - mcp_app_resource_uri: None, - mcp_app_ui: None, - plugin_id: None, - read_only_hint: None, - result: None, - error: None, - duration_ms: Some(2), - }; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item.clone(), - /*started_at_ms*/ 998, - ), - ))), - &mut events, - ) - .await; - if let Some(elicitation_type) = elicitation_type { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::McpToolCallElicitation( - McpToolCallElicitation { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - item_id: item_id.to_string(), - elicitation_type, - }, - )), - &mut events, - ) - .await; - } - items.push(item); - } - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - for item in items { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item, - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut events, - ) - .await; - } - - let payload = serde_json::to_value(&events).expect("serialize analytics events"); - for event in payload.as_array().expect("analytics events array") { - assert_eq!( - event["event_params"]["turn_trigger"], - "automation_cron_scheduled" - ); - } - let classifications = payload - .as_array() - .expect("analytics events array") - .iter() - .filter(|event| event["event_type"] == "codex_mcp_tool_call_event") - .map(|event| { - json!({ - "item_id": event["event_params"]["item_id"], - "connector_id": event["event_params"]["connector_id"], - "elicitation_type": event["event_params"].get("elicitation_type") - .expect("elicitation_type must be present"), - }) - }) - .collect::>(); - assert_eq!( - classifications, - vec![ - json!({"item_id": "auth", "connector_id": "calendar", "elicitation_type": "auth_or_link"}), - json!({"item_id": "retry", "connector_id": "calendar", "elicitation_type": null}), - json!({"item_id": "denied", "connector_id": "drive", "elicitation_type": "approval"}), - ] - ); - assert!(!payload.to_string().contains("synthetic-private-input")); -} - -#[tokio::test] -async fn reducer_ingests_artifact_operation_fact() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ArtifactOperation( - ArtifactOperationInput { - tracking: test_tracking_context("thread-1", "turn-1"), - operation: ArtifactOperation { - item_id: "call-1".to_string(), - lifecycle: ArtifactOperationLifecycle::Started, - occurred_at_ms: 1_786_000_000_000, - plugin_id: "presentations@openai-primary-runtime".to_string(), - script_path: "skills/presentations/container_tools/mark_artifact_operation_started.mjs".to_string(), - skill: "presentations".to_string(), - artifact_type: "presentation".to_string(), - operation_kind: "create".to_string(), - expected_output_count: 2, - output_format: "pptx".to_string(), - execution_backend: "unified_exec".to_string(), - }, - }, - )), - &mut events, - ) - .await; - - assert!(events[0].can_send_with_api_key_auth()); - assert_eq!( - serde_json::to_value(events).expect("serialize events"), - json!([{ - "event_type": "codex_artifact_operation", - "event_params": { - "thread_id": "thread-1", - "turn_id": "turn-1", - "item_id": "call-1", - "lifecycle": "started", - "occurred_at_ms": 1_786_000_000_000_u64, - "product_client_id": TEST_PRODUCT_CLIENT_ID, - "runtime": serde_json::to_value(current_runtime_metadata()) - .expect("serialize runtime metadata"), - "model_slug": "gpt-5", - "plugin_id": "presentations@openai-primary-runtime", - "script_path": "skills/presentations/container_tools/mark_artifact_operation_started.mjs", - "skill": "presentations", - "artifact_type": "presentation", - "operation_kind": "create", - "expected_output_count": 2, - "output_format": "pptx", - "execution_backend": "unified_exec" - } - }]) - ); -} - -#[tokio::test] -async fn image_generation_events_preserve_transparent_background_metadata() { - for (status, transparent_background) in [ - ("completed", Some(true)), - ("completed", Some(false)), - ("completed", None), - ("failed", None), - ] { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - - let item = ThreadItemPayload::ImageGeneration(ImageGenerationItem { - id: "image-1".to_string(), - status: status.to_string(), - revised_prompt: None, - image: GeneratedImageRef::Inline { - result: "ok".to_string(), - }, - transparent_background, - failure: None, - saved_path: None, - input_images: Vec::new(), - imagegen_request_id: None, - generation_id: None, - }); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item.clone(), - /*started_at_ms*/ 998, - ), - ))), - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item, - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut out, - ) - .await; - - let event = out - .iter() - .find(|event| matches!(event, TrackEventRequest::ImageGeneration(_))) - .expect("image generation event should be emitted"); - let payload = serde_json::to_value(event).expect("serialize image generation event"); - - assert_eq!( - payload["event_params"].get("transparent_background"), - Some(&json!(transparent_background)) - ); - assert_eq!(payload["event_params"]["terminal_status"], json!(status)); - } -} diff --git a/codex-rs/analytics/src/tests/suite/turns/accepted_lines_tests.rs b/codex-rs/analytics/src/tests/suite/turns/accepted_lines_tests.rs deleted file mode 100644 index 42171280..00000000 --- a/codex-rs/analytics/src/tests/suite/turns/accepted_lines_tests.rs +++ /dev/null @@ -1,322 +0,0 @@ -//! Accepted-line aggregation, finalization, and event payload tests. - -#[cfg(debug_assertions)] -use crate::client::AnalyticsEventsClient; -use crate::events::CodexAcceptedLineFingerprintsEventParams; -use crate::events::CodexAcceptedLineFingerprintsEventRequest; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -#[cfg(debug_assertions)] -use crate::facts::CustomAnalyticsFact; -#[cfg(debug_assertions)] -use crate::facts::TurnProfileFact; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::ingest_turn_prerequisites; -#[cfg(debug_assertions)] -use crate::tests::support::sample_initialize_fact; -#[cfg(debug_assertions)] -use crate::tests::support::sample_thread_start_response; -use crate::tests::support::sample_turn_completed_notification; -#[cfg(debug_assertions)] -use crate::tests::support::sample_turn_profile; -#[cfg(debug_assertions)] -use crate::tests::support::sample_turn_resolved_config; -#[cfg(debug_assertions)] -use crate::tests::support::sample_turn_start_request; -#[cfg(debug_assertions)] -use crate::tests::support::sample_turn_start_response; -#[cfg(debug_assertions)] -use crate::tests::support::sample_turn_started_notification; -#[cfg(debug_assertions)] -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::TurnDiffUpdatedNotification; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use pretty_assertions::assert_eq; -use serde_json::json; -#[cfg(debug_assertions)] -use std::time::SystemTime; - -#[test] -fn accepted_line_fingerprints_event_serializes_expected_shape() { - let event = TrackEventRequest::AcceptedLineFingerprints(Box::new( - CodexAcceptedLineFingerprintsEventRequest { - event_type: "codex_accepted_line_fingerprints", - event_params: CodexAcceptedLineFingerprintsEventParams { - event_type: "codex.accepted_line_fingerprints", - turn_id: "turn-1".to_string(), - thread_id: "thread-1".to_string(), - product_surface: Some("codex".to_string()), - model_slug: Some("gpt-5.1-codex".to_string()), - completed_at: 1710000000, - repo_hash: Some("repo-hash-1".to_string()), - accepted_added_lines: 42, - accepted_deleted_lines: 40, - line_fingerprints: [], - }, - }, - )); - - let payload = serde_json::to_value(&event).expect("serialize accepted line fingerprints event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_accepted_line_fingerprints", - "event_params": { - "event_type": "codex.accepted_line_fingerprints", - "turn_id": "turn-1", - "thread_id": "thread-1", - "product_surface": "codex", - "model_slug": "gpt-5.1-codex", - "completed_at": 1710000000, - "repo_hash": "repo-hash-1", - "accepted_added_lines": 42, - "accepted_deleted_lines": 40, - "line_fingerprints": [] - } - }) - ); -} - -#[tokio::test] -async fn reducer_emits_large_accepted_line_aggregates_without_fingerprints() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ true, - ) - .await; - events.clear(); - - let mut diff = "\ -diff --git a/src/lib.rs b/src/lib.rs -index 1111111..2222222 ---- a/src/lib.rs -+++ b/src/lib.rs -@@ -0,0 +1,20000 @@ -" - .to_string(); - for index in 0..20_000 { - diff.push_str(&format!("+let value_{index} = {index};\n")); - } - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::TurnDiffUpdated( - TurnDiffUpdatedNotification { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - diff, - }, - ))), - &mut events, - ) - .await; - assert!(events.is_empty()); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - - let accepted_line_events = events - .iter() - .filter_map(|event| match event { - TrackEventRequest::AcceptedLineFingerprints(event) => Some(event), - _ => None, - }) - .collect::>(); - assert_eq!(accepted_line_events.len(), 1); - let event = accepted_line_events[0]; - assert_eq!(event.event_params.turn_id, "turn-2"); - assert_eq!(event.event_params.thread_id, "thread-2"); - assert_eq!(event.event_params.accepted_added_lines, 20_000); - assert_eq!(event.event_params.accepted_deleted_lines, 0); - assert!(event.event_params.line_fingerprints.is_empty()); - assert!(serde_json::to_vec(event).expect("serialize event").len() < 2_100_000); -} - -#[tokio::test] -async fn reducer_emits_accepted_line_fingerprints_once_from_latest_turn_diff_on_completion() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ true, - ) - .await; - events.clear(); - - for line in ["let old_value = 1;", "let latest_value = 2;"] { - let diff = format!( - "\ -diff --git a/src/lib.rs b/src/lib.rs -index 1111111..2222222 ---- a/src/lib.rs -+++ b/src/lib.rs -@@ -0,0 +1 @@ -+{line} -" - ); - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::TurnDiffUpdated( - TurnDiffUpdatedNotification { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - diff, - }, - ))), - &mut events, - ) - .await; - } - assert!(events.is_empty()); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - - let accepted_line_events = events - .iter() - .filter_map(|event| match event { - TrackEventRequest::AcceptedLineFingerprints(event) => Some(event), - _ => None, - }) - .collect::>(); - assert_eq!(accepted_line_events.len(), 1); - let event = accepted_line_events[0]; - assert_eq!(event.event_params.accepted_added_lines, 1); - assert!(event.event_params.line_fingerprints.is_empty()); -} - -#[tokio::test] -#[cfg(debug_assertions)] -async fn analytics_flush_delivers_completed_turn_with_file_diff() { - let nonce = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .expect("system clock should be after Unix epoch") - .as_nanos(); - let capture_path = std::env::temp_dir().join(format!( - "codex-analytics-turn-flush-{}-{nonce}.jsonl", - std::process::id() - )); - let auth_manager = codex_login::AuthManager::from_auth_for_testing( - codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ); - let client = AnalyticsEventsClient::new_for_capture_file(auth_manager, capture_path.clone()); - - for fact in [ - sample_initialize_fact(/*connection_id*/ 7), - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - "thread-2", /*ephemeral*/ false, "gpt-5", - )), - thread_originator: None, - }, - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(3), - request: Box::new(sample_turn_start_request("thread-2", /*request_id*/ 3)), - }, - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-2")), - thread_originator: None, - }, - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - sample_turn_resolved_config("thread-2", "turn-2"), - ))), - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-2", - ))), - AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new( - TurnProfileFact { - turn_id: "turn-2".to_string(), - profile: sample_turn_profile(), - }, - ))), - AnalyticsFact::Notification(Box::new(ServerNotification::TurnDiffUpdated( - TurnDiffUpdatedNotification { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - diff: "\ -diff --git a/src/lib.rs b/src/lib.rs -index 1111111..2222222 ---- a/src/lib.rs -+++ b/src/lib.rs -@@ -0,0 +1 @@ -+let value = 1; -" - .to_string(), - }, - ))), - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - ] { - client.record_fact(fact); - } - - client.flush().await; - - let contents = std::fs::read_to_string(&capture_path).expect("read captured analytics events"); - let event_types = contents - .lines() - .flat_map(|line| { - serde_json::from_str::(line) - .expect("parse captured analytics events")["events"] - .as_array() - .expect("captured events should be an array") - .iter() - .map(|event| { - event["event_type"] - .as_str() - .expect("captured event type should be a string") - .to_string() - }) - .collect::>() - }) - .collect::>(); - assert!(event_types.iter().any(|event| event == "codex_turn_event")); - assert!( - event_types - .iter() - .any(|event| event == "codex_accepted_line_fingerprints") - ); - - std::fs::remove_file(capture_path).expect("remove analytics capture file"); -} diff --git a/codex-rs/analytics/src/tests/suite/turns/compaction_tests.rs b/codex-rs/analytics/src/tests/suite/turns/compaction_tests.rs deleted file mode 100644 index 88f86a39..00000000 --- a/codex-rs/analytics/src/tests/suite/turns/compaction_tests.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! Compaction fact, wire payload, and implementation tests. - -use crate::events::AppServerRpcTransport; -use crate::events::CodexCompactionEventRequest; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::CodexCompactionEvent; -use crate::facts::CodexErrKind; -use crate::facts::CompactionImplementation; -use crate::facts::CompactionPhase; -use crate::facts::CompactionReason; -use crate::facts::CompactionStatus; -use crate::facts::CompactionStrategy; -use crate::facts::CompactionTrigger; -use crate::facts::CustomAnalyticsFact; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::sample_app_server_client_metadata; -use crate::tests::support::sample_runtime_metadata; -use crate::tests::support::sample_thread_resume_response_with_source; -use crate::tests::support::sample_turn_started_notification; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SessionSource as AppServerSessionSource; -use codex_app_server_protocol::ThreadSource as AppServerThreadSource; -use codex_login::default_client::DEFAULT_ORIGINATOR; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadSource; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn compaction_event_serializes_expected_shape() { - let mut event_params = crate::events::codex_compaction_event_params( - CodexCompactionEvent { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - trigger: CompactionTrigger::Auto, - reason: CompactionReason::ContextLimit, - implementation: CompactionImplementation::ResponsesCompactionV2, - phase: CompactionPhase::MidTurn, - strategy: CompactionStrategy::Memento, - status: CompactionStatus::Completed, - codex_error_kind: None, - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - active_context_tokens_before: 120_000, - active_context_tokens_after: 18_000, - retained_image_count: None, - compaction_summary_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: Some(456), - started_at: 100, - completed_at: 106, - duration_ms: Some(6543), - }, - "session-thread-1".to_string(), - sample_app_server_client_metadata(), - sample_runtime_metadata(), - Some(ThreadSource::User), - /*subagent_source*/ None, - /*parent_thread_id*/ None, - ); - event_params.voice_session_id = Some("voice-session-1".to_string()); - let event = TrackEventRequest::Compaction(Box::new(CodexCompactionEventRequest { - event_type: "codex_compaction_event", - event_params, - })); - - let payload = serde_json::to_value(&event).expect("serialize compaction event"); - - assert_eq!( - payload, - json!({ - "event_type": "codex_compaction_event", - "event_params": { - "thread_id": "thread-1", - "session_id": "session-thread-1", - "turn_id": "turn-1", - "app_server_client": { - "product_client_id": DEFAULT_ORIGINATOR, - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "stdio", - "experimental_api_enabled": true - }, - "runtime": { - "codex_rs_version": "0.1.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64" - }, - "thread_source": "user", - "subagent_source": null, - "parent_thread_id": null, - "trigger": "auto", - "reason": "context_limit", - "implementation": "responses_compaction_v2", - "phase": "mid_turn", - "strategy": "memento", - "status": "completed", - "voice_session_id": "voice-session-1", - "codex_error_kind": null, - "codex_error_http_status_code": null, - "usage_limit_window_minutes": null, - "active_context_tokens_before": 120000, - "active_context_tokens_after": 18000, - "retained_image_count": null, - "compaction_summary_tokens": null, - "cached_input_tokens": null, - "cache_write_input_tokens": 456, - "started_at": 100, - "completed_at": 106, - "duration_ms": 6543 - } - }) - ); -} - -#[test] -fn compaction_implementation_serializes_remote_v2() { - let payload = serde_json::to_value(CompactionImplementation::ResponsesCompactionV2) - .expect("serialize compaction implementation"); - - assert_eq!(payload, json!("responses_compaction_v2")); -} - -#[tokio::test] -async fn compaction_events_keep_authoritative_voice_session_across_consecutive_calls() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - let parent_thread_id = - codex_protocol::ThreadId::from_string("22222222-2222-2222-2222-222222222222") - .expect("valid parent thread id"); - - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 7, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-tui".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: Some(InitializeCapabilities { - required_human_approval: false, - explicit_gateway_oauth: false, - experimental_api: false, - request_attestation: false, - opt_out_notification_methods: None, - mcp_server_openai_form_elicitation: false, - extensions: None, - }), - }, - product_client_id: DEFAULT_ORIGINATOR.to_string(), - runtime: sample_runtime_metadata(), - rpc_transport: AppServerRpcTransport::Websocket, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(2), - response: Box::new(sample_thread_resume_response_with_source( - "thread-1", - /*ephemeral*/ false, - "gpt-5", - AppServerSessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, - depth: 1, - agent_path: None, - agent_nickname: None, - agent_role: None, - }), - Some(AppServerThreadSource::Subagent), - Some(parent_thread_id.to_string()), - )), - thread_originator: None, - }, - &mut events, - ) - .await; - events.clear(); - - reducer - .ingest( - AnalyticsFact::RealtimeSessionStarted { - thread_id: "thread-1".to_string(), - realtime_session_id: None, - started_at: 100, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::RealtimeSessionUpdated { - thread_id: "thread-1".to_string(), - realtime_session_id: "voice-session-1".to_string(), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-1", - "turn-compact-1", - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::RealtimeSessionClosed { - thread_id: "thread-1".to_string(), - closed_at: 150, - }, - &mut events, - ) - .await; - - reducer - .ingest( - AnalyticsFact::RealtimeSessionStarted { - thread_id: "thread-1".to_string(), - realtime_session_id: None, - started_at: 200, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::RealtimeSessionUpdated { - thread_id: "thread-1".to_string(), - realtime_session_id: "voice-session-2".to_string(), - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-1", - "turn-compact-2", - ))), - &mut events, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::Compaction(Box::new( - CodexCompactionEvent { - thread_id: "thread-1".to_string(), - turn_id: "turn-compact-1".to_string(), - trigger: CompactionTrigger::Manual, - reason: CompactionReason::UserRequested, - implementation: CompactionImplementation::Responses, - phase: CompactionPhase::StandaloneTurn, - strategy: CompactionStrategy::Memento, - status: CompactionStatus::Failed, - codex_error_kind: Some(CodexErrKind::ContextWindowExceeded), - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - active_context_tokens_before: 131_000, - active_context_tokens_after: 131_000, - retained_image_count: None, - compaction_summary_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - started_at: 110, - completed_at: 210, - duration_ms: Some(1200), - }, - ))), - &mut events, - ) - .await; - - reducer - .ingest( - AnalyticsFact::RealtimeSessionClosed { - thread_id: "thread-1".to_string(), - closed_at: 250, - }, - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::Compaction(Box::new( - CodexCompactionEvent { - thread_id: "thread-1".to_string(), - turn_id: "turn-compact-2".to_string(), - trigger: CompactionTrigger::Auto, - reason: CompactionReason::ContextLimit, - implementation: CompactionImplementation::ResponsesCompactionV2, - phase: CompactionPhase::MidTurn, - strategy: CompactionStrategy::Memento, - status: CompactionStatus::Completed, - codex_error_kind: None, - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - active_context_tokens_before: 100_000, - active_context_tokens_after: 20_000, - retained_image_count: None, - compaction_summary_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - started_at: 210, - completed_at: 251, - duration_ms: Some(800), - }, - ))), - &mut events, - ) - .await; - - let payload = serde_json::to_value(&events).expect("serialize events"); - assert_eq!(payload.as_array().expect("events array").len(), 2); - assert_eq!(payload[0]["event_type"], "codex_compaction_event"); - assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1"); - assert_eq!(payload[0]["event_params"]["thread_id"], "thread-1"); - assert_eq!(payload[0]["event_params"]["turn_id"], "turn-compact-1"); - assert_eq!( - payload[0]["event_params"]["voice_session_id"], - "voice-session-1" - ); - assert_eq!( - payload[0]["event_params"]["codex_error_kind"], - json!("context_window_exceeded") - ); - assert_eq!( - payload[0]["event_params"]["codex_error_http_status_code"], - json!(null) - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["product_client_id"], - DEFAULT_ORIGINATOR - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["client_name"], - "codex-tui" - ); - assert_eq!( - payload[0]["event_params"]["app_server_client"]["rpc_transport"], - "websocket" - ); - assert_eq!( - payload[0]["event_params"]["runtime"]["codex_rs_version"], - "0.1.0" - ); - assert_eq!(payload[0]["event_params"]["thread_source"], "subagent"); - assert_eq!( - payload[0]["event_params"]["subagent_source"], - "thread_spawn" - ); - assert_eq!( - payload[0]["event_params"]["parent_thread_id"], - "22222222-2222-2222-2222-222222222222" - ); - assert_eq!(payload[0]["event_params"]["trigger"], "manual"); - assert_eq!(payload[0]["event_params"]["reason"], "user_requested"); - assert_eq!(payload[0]["event_params"]["implementation"], "responses"); - assert_eq!(payload[0]["event_params"]["phase"], "standalone_turn"); - assert_eq!(payload[0]["event_params"]["strategy"], "memento"); - assert_eq!(payload[0]["event_params"]["status"], "failed"); - assert_eq!(payload[1]["event_params"]["turn_id"], "turn-compact-2"); - assert_eq!( - payload[1]["event_params"]["voice_session_id"], - "voice-session-2" - ); - assert_eq!(payload[1]["event_params"]["status"], "completed"); -} diff --git a/codex-rs/analytics/src/tests/suite/turns/events_tests.rs b/codex-rs/analytics/src/tests/suite/turns/events_tests.rs deleted file mode 100644 index 8f2bd1be..00000000 --- a/codex-rs/analytics/src/tests/suite/turns/events_tests.rs +++ /dev/null @@ -1,1105 +0,0 @@ -//! Turn lifecycle, prerequisites, counts, image preparation, and event payload tests. - -use crate::events::CodexTurnEventRequest; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::ControlToolCallFact; -use crate::facts::ControlToolCallStatus; -use crate::facts::CustomAnalyticsFact; -use crate::facts::ImageDetailSetting; -use crate::facts::ImagePreparationFact; -use crate::facts::ImagePreparationMetadata; -use crate::facts::ThreadInitializationMode; -use crate::facts::TurnCodexErrorFact; -use crate::facts::TurnResolvedConfigFact; -use crate::facts::TurnStatus; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::ingest_turn_prerequisites; -use crate::tests::support::sample_app_server_client_metadata; -use crate::tests::support::sample_command_execution_item; -use crate::tests::support::sample_runtime_metadata; -use crate::tests::support::sample_turn_completed_notification; -use crate::tests::support::sample_turn_resolved_config; -use crate::tests::support::test_turn_metadata; -use codex_app_server_protocol::CollabAgentTool; -use codex_app_server_protocol::CollabAgentToolCallStatus; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::DynamicToolCallStatus; -use codex_app_server_protocol::GeneratedImageRef; -use codex_app_server_protocol::ImageGenerationItem; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::McpToolCallAppContext; -use codex_app_server_protocol::McpToolCallStatus; -use codex_app_server_protocol::PatchApplyStatus; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SubAgentActivityKind; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::ThreadRealtimeStartedNotification; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_app_server_protocol::WebSearchItem; -use codex_protocol::error::CodexErr; -use codex_protocol::error::UsageLimitReachedError; -use codex_protocol::protocol::RealtimeConversationVersion; -use codex_protocol::protocol::ThreadSource; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[tokio::test] -async fn image_preparation_fact_is_included_in_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut events = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut events, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - - let metadata = ImagePreparationMetadata { - message_role: None, - item_id: Some("call-1".to_string()), - effective_detail: ImageDetailSetting::High, - source_width: 2_048, - source_height: 2_048, - prepared_width: 1_600, - prepared_height: 1_600, - }; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ImagePreparation(Box::new( - ImagePreparationFact { - turn_id: "turn-2".to_string(), - metadata: metadata.clone(), - }, - ))), - &mut events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut events, - ) - .await; - - let [TrackEventRequest::TurnEvent(event)] = events.as_slice() else { - panic!("expected one turn event"); - }; - assert_eq!(event.event_params.image_preparations, vec![metadata]); -} - -#[test] -fn turn_event_serializes_expected_shape() { - let event = TrackEventRequest::TurnEvent(Box::new(CodexTurnEventRequest { - event_type: "codex_turn_event", - event_params: crate::events::CodexTurnEventParams { - critical_path: crate::TurnCriticalPath::Disabled.into(), - thread_id: "thread-2".to_string(), - session_id: "session-thread-2".to_string(), - turn_id: "turn-2".to_string(), - active_plugin_ids_at_turn_start: Some(vec![ - "plugins~Plugin_example".to_string(), - "test@marketplace".to_string(), - ]), - voice_session_id: None, - root_turn_id: Some("turn-2".to_string()), - turn_trigger: Some("user".to_string()), - codex_turn_source: Some("composer".to_string()), - app_server_client: sample_app_server_client_metadata(), - runtime: sample_runtime_metadata(), - submission_type: None, - ephemeral: false, - thread_source: Some(ThreadSource::User), - initialization_mode: ThreadInitializationMode::New, - subagent_source: None, - parent_thread_id: None, - model: Some("gpt-5".to_string()), - model_provider: "openai".to_string(), - sandbox_policy: Some("read_only"), - reasoning_effort: Some("high".to_string()), - reasoning_summary: Some("detailed".to_string()), - service_tier: "flex".to_string(), - approval_policy: "on-request".to_string(), - approvals_reviewer: "auto_review".to_string(), - guardian_v2_enabled: true, - multi_agent_version: codex_protocol::protocol::MultiAgentVersion::V2, - sandbox_network_access: true, - collaboration_mode: Some("plan"), - personality: Some("pragmatic".to_string()), - workspace_kind: Some("projectless".to_string()), - num_input_images: 2, - image_preparations: vec![ImagePreparationMetadata { - message_role: Some("user".to_string()), - item_id: None, - effective_detail: ImageDetailSetting::High, - source_width: 2_048, - source_height: 2_048, - prepared_width: 1_600, - prepared_height: 1_600, - }], - is_first_turn: true, - status: Some(TurnStatus::Completed), - explicit_client_interrupt_requested_at_ms: None, - turn_error: None, - codex_error_kind: None, - codex_error_http_status_code: None, - usage_limit_window_minutes: None, - steer_count: Some(0), - total_tool_call_count: None, - shell_command_count: None, - file_change_count: None, - mcp_tool_call_count: None, - dynamic_tool_call_count: None, - subagent_tool_call_count: None, - web_search_count: None, - image_generation_count: None, - input_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - output_tokens: None, - reasoning_output_tokens: None, - total_tokens: None, - before_first_sampling_ms: 100, - sampling_ms: 700, - compaction_ms: 40, - between_sampling_overhead_ms: 50, - tool_blocking_ms: 250, - after_last_sampling_ms: 94, - sampling_request_count: 2, - sampling_retry_count: 1, - tools_change_count: 2, - duration_ms: Some(1234), - started_at: Some(455), - completed_at: Some(456), - }, - })); - - let payload = serde_json::to_value(&event).expect("serialize turn event"); - let expected = serde_json::from_str::( - r#"{ - "event_type": "codex_turn_event", - "event_params": { - "critical_path_status": "disabled", - "critical_path_duration_ms": null, - "critical_path_inference_ms": null, - "critical_path_sampling_ms": null, - "critical_path_compaction_ms": null, - "critical_path_auto_review_ms": null, - "critical_path_auto_review_overhead_ms": null, - "critical_path_user_wait_ms": null, - "critical_path_tools_ms": null, - "critical_path_overhead_ms": null, - "critical_path_unknown_ms": null, - "thread_id": "thread-2", - "session_id": "session-thread-2", - "turn_id": "turn-2", - "active_plugin_ids_at_turn_start": ["plugins~Plugin_example", "test@marketplace"], - "voice_session_id": null, - "root_turn_id": "turn-2", - "turn_trigger": "user", - "codex_turn_source": "composer", - "submission_type": null, - "app_server_client": { - "product_client_id": "codex_cli_rs", - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "stdio", - "experimental_api_enabled": true - }, - "runtime": { - "codex_rs_version": "0.1.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64" - }, - "ephemeral": false, - "thread_source": "user", - "initialization_mode": "new", - "subagent_source": null, - "parent_thread_id": null, - "model": "gpt-5", - "model_provider": "openai", - "sandbox_policy": "read_only", - "reasoning_effort": "high", - "reasoning_summary": "detailed", - "service_tier": "flex", - "approval_policy": "on-request", - "approvals_reviewer": "auto_review", - "guardian_v2_enabled": true, - "multi_agent_version": "v2", - "sandbox_network_access": true, - "collaboration_mode": "plan", - "personality": "pragmatic", - "workspace_kind": "projectless", - "num_input_images": 2, - "image_preparations": [{ - "message_role": "user", - "item_id": null, - "effective_detail": "high", - "source_width": 2048, - "source_height": 2048, - "prepared_width": 1600, - "prepared_height": 1600 - }], - "is_first_turn": true, - "status": "completed", - "explicit_client_interrupt_requested_at_ms": null, - "turn_error": null, - "codex_error_kind": null, - "codex_error_http_status_code": null, - "usage_limit_window_minutes": null, - "steer_count": 0, - "total_tool_call_count": null, - "shell_command_count": null, - "file_change_count": null, - "mcp_tool_call_count": null, - "dynamic_tool_call_count": null, - "subagent_tool_call_count": null, - "web_search_count": null, - "image_generation_count": null, - "input_tokens": null, - "cached_input_tokens": null, - "cache_write_input_tokens": null, - "output_tokens": null, - "reasoning_output_tokens": null, - "total_tokens": null, - "before_first_sampling_ms": 100, - "sampling_ms": 700, - "compaction_ms": 40, - "between_sampling_overhead_ms": 50, - "tool_blocking_ms": 250, - "after_last_sampling_ms": 94, - "sampling_request_count": 2, - "sampling_retry_count": 1, - "tools_change_count": 2, - "duration_ms": 1234, - "started_at": 455, - "completed_at": 456 - } - }"#, - ) - .expect("parse expected turn event"); - - assert_eq!(payload, expected); -} - -#[tokio::test] -async fn turn_event_preserves_first_received_plugin_inventory() { - for plugin_ids in [ - None, - Some(vec![]), - Some(vec!["initial@marketplace".to_string()]), - ] { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - - let config = TurnResolvedConfigFact { - active_plugin_ids_at_turn_start: plugin_ids.clone(), - ..sample_turn_resolved_config("thread-2", "turn-2") - }; - let later_config = TurnResolvedConfigFact { - active_plugin_ids_at_turn_start: Some(vec!["later@marketplace".to_string()]), - is_first_turn: false, - ..config.clone() - }; - for fact in [ - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new(config))), - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - later_config, - ))), - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - ] { - reducer.ingest(fact, &mut out).await; - } - - let [TrackEventRequest::TurnEvent(event)] = out.as_slice() else { - panic!("expected one turn event"); - }; - assert_eq!( - ( - &event.event_params.active_plugin_ids_at_turn_start, - event.event_params.is_first_turn, - ), - (&plugin_ids, false), - ); - } -} - -#[tokio::test] -async fn turn_lifecycle_emits_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ true, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!(payload["event_type"], json!("codex_turn_event")); - assert_eq!(payload["event_params"]["thread_id"], json!("thread-2")); - assert_eq!( - payload["event_params"]["session_id"], - json!("session-thread-2") - ); - assert_eq!(payload["event_params"]["turn_id"], json!("turn-2")); - assert_eq!( - ( - payload["event_params"].get("turn_trigger"), - payload["event_params"].get("codex_turn_source"), - ), - ( - Some(&serde_json::Value::Null), - Some(&serde_json::Value::Null) - ) - ); - assert_eq!( - payload["event_params"]["app_server_client"], - json!({ - "product_client_id": "codex-tui", - "client_name": "codex-tui", - "client_version": "1.0.0", - "rpc_transport": "stdio", - "experimental_api_enabled": null, - }) - ); - assert_eq!( - payload["event_params"]["runtime"], - json!({ - "codex_rs_version": "0.1.0", - "runtime_os": "macos", - "runtime_os_version": "15.3.1", - "runtime_arch": "aarch64", - }) - ); - assert!(payload["event_params"].get("product_client_id").is_none()); - assert_eq!(payload["event_params"]["guardian_v2_enabled"], json!(false)); - assert_eq!(payload["event_params"]["ephemeral"], json!(false)); - assert_eq!(payload["event_params"]["workspace_kind"], json!(null)); - assert_eq!(payload["event_params"]["num_input_images"], json!(1)); - assert_eq!(payload["event_params"]["status"], json!("completed")); - assert_eq!(payload["event_params"]["steer_count"], json!(0)); - assert_eq!(payload["event_params"]["total_tool_call_count"], json!(0)); - assert_eq!(payload["event_params"]["shell_command_count"], json!(0)); - assert_eq!(payload["event_params"]["file_change_count"], json!(0)); - assert_eq!(payload["event_params"]["mcp_tool_call_count"], json!(0)); - assert_eq!(payload["event_params"]["dynamic_tool_call_count"], json!(0)); - assert_eq!( - payload["event_params"]["subagent_tool_call_count"], - json!(0) - ); - assert_eq!(payload["event_params"]["web_search_count"], json!(0)); - assert_eq!(payload["event_params"]["image_generation_count"], json!(0)); - assert_eq!(payload["event_params"]["started_at"], json!(455)); - assert_eq!(payload["event_params"]["completed_at"], json!(456)); - assert_eq!(payload["event_params"]["duration_ms"], json!(1234)); - assert_eq!(payload["event_params"]["input_tokens"], json!(123)); - assert_eq!(payload["event_params"]["cached_input_tokens"], json!(45)); - assert_eq!( - payload["event_params"]["cache_write_input_tokens"], - json!(7) - ); - assert_eq!(payload["event_params"]["output_tokens"], json!(140)); - assert_eq!( - payload["event_params"]["reasoning_output_tokens"], - json!(13) - ); - assert_eq!(payload["event_params"]["total_tokens"], json!(321)); -} - -#[tokio::test] -async fn turn_event_counts_completed_tool_items() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - TurnResolvedConfigFact { - turn_metadata: test_turn_metadata(Some("root-ancestor")), - ..sample_turn_resolved_config("thread-2", "turn-2") - }, - ))), - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ThreadRealtimeStarted( - ThreadRealtimeStartedNotification { - thread_id: "thread-2".to_string(), - realtime_session_id: Some("work-voice-456".to_string()), - version: RealtimeConversationVersion::V2, - }, - ))), - &mut out, - ) - .await; - - let mcp_tool_call_item = |status, duration_ms| ThreadItemPayload::McpToolCall { - id: "mcp-1".to_string(), - server: "server".to_string(), - tool: "search".to_string(), - status, - arguments: json!({}), - app_context: Some(McpToolCallAppContext { - connector_id: "connector-test".to_string(), - link_id: None, - resource_uri: None, - app_name: None, - action_name: None, - }), - mcp_app_resource_uri: None, - mcp_app_ui: None, - plugin_id: Some("sample@test".to_string()), - read_only_hint: None, - result: None, - error: None, - duration_ms, - }; - let completed_tool_items = vec![ - sample_command_execution_item(CommandExecutionStatus::Completed, Some(0), Some(1)), - ThreadItemPayload::FileChange { - id: "file-change-1".to_string(), - changes: Vec::new(), - status: PatchApplyStatus::Completed, - }, - mcp_tool_call_item(McpToolCallStatus::Completed, Some(2)), - ThreadItemPayload::DynamicToolCall { - id: "dynamic-1".to_string(), - // A name collision with code-mode exec must not change the event boundary. - namespace: Some("custom".to_string()), - tool: "exec".to_string(), - arguments: json!({}), - status: DynamicToolCallStatus::Completed, - content_items: None, - success: Some(true), - duration_ms: Some(3), - }, - ThreadItemPayload::CollabAgentToolCall { - id: "collab-1".to_string(), - tool: CollabAgentTool::SpawnAgent, - status: CollabAgentToolCallStatus::Completed, - sender_thread_id: "thread-2".to_string(), - receiver_thread_ids: vec!["thread-child".to_string()], - prompt: Some("help".to_string()), - model: Some("gpt-5".to_string()), - reasoning_effort: None, - agents_states: Default::default(), - }, - ThreadItemPayload::SubAgentActivity { - model: None, - reasoning_effort: None, - id: "sub-agent-activity-1".to_string(), - kind: SubAgentActivityKind::Interacted, - agent_thread_id: "thread-child".to_string(), - agent_path: "/root/child".to_string(), - }, - ThreadItemPayload::SubAgentActivity { - model: None, - reasoning_effort: None, - id: "sub-agent-activity-completed".to_string(), - kind: SubAgentActivityKind::Completed, - agent_thread_id: "thread-child".to_string(), - agent_path: "/root/child".to_string(), - }, - ThreadItemPayload::WebSearch(WebSearchItem { - id: "web-1".to_string(), - query: "codex".to_string(), - action: None, - results: None, - }), - ThreadItemPayload::ImageGeneration(ImageGenerationItem { - id: "image-1".to_string(), - status: "completed".to_string(), - revised_prompt: None, - image: GeneratedImageRef::Inline { - result: "ok".to_string(), - }, - transparent_background: None, - failure: None, - saved_path: None, - input_images: Vec::new(), - imagegen_request_id: Some("req-imagegen-123".to_string()), - generation_id: Some("gen-image-123".to_string()), - }), - ]; - - for item in &completed_tool_items { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item.clone(), - /*started_at_ms*/ 998, - ), - ))), - &mut out, - ) - .await; - } - - for item in completed_tool_items { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - "thread-2".to_string(), - "turn-2".to_string(), - item, - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_000, - ), - ))), - &mut out, - ) - .await; - } - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::ControlToolCall(ControlToolCallFact { - thread_id: "thread-2".to_string(), - turn_id: "turn-2".to_string(), - turn_metadata: test_turn_metadata(Some("root-ancestor")), - call_id: "control-1".to_string(), - cell_id: None, - tool_name: "update_plan".to_string(), - started_at_ms: 998, - completed_at_ms: 1_000, - status: ControlToolCallStatus::Completed, - })), - &mut out, - ) - .await; - reducer.flush(&mut out); - - let payload = serde_json::to_value(&out).expect("serialize tool item events"); - let emitted_tool_events = payload - .as_array() - .expect("tool item events array") - .iter() - .map(|event| { - ( - event["event_type"].as_str().expect("tool item event type"), - event["event_params"]["session_id"] - .as_str() - .expect("tool item event session ID"), - event["event_params"]["turn_id"] - .as_str() - .expect("tool item event turn ID"), - event["event_params"]["root_turn_id"] - .as_str() - .expect("tool item event root turn ID"), - event["event_params"]["tool_event_type"].as_str(), - ) - }) - .collect::>(); - assert_eq!( - emitted_tool_events, - [ - ("codex_command_execution_event", None), - ("codex_file_change_event", None), - ("codex_mcp_tool_call_event", None), - ("codex_dynamic_tool_call_event", None), - ("codex_web_search_event", None), - ("codex_image_generation_event", None), - ("codex_collab_agent_tool_call_event", None), - ("codex_control_tool_call_event", None), - ] - .map(|(event_type, tool_event_type)| { - ( - event_type, - "session-thread-2", - "turn-2", - "root-ancestor", - tool_event_type, - ) - }) - .to_vec() - ); - - let image_generation_event = out - .iter() - .find(|event| matches!(event, TrackEventRequest::ImageGeneration(_))) - .expect("image generation event should be emitted"); - let payload = - serde_json::to_value(image_generation_event).expect("serialize image generation event"); - assert_eq!( - payload["event_params"]["imagegen_request_id"], - json!("req-imagegen-123") - ); - assert_eq!( - payload["event_params"]["generation_id"], - json!("gen-image-123") - ); - - let mcp_tool_call_event = out - .iter() - .find(|event| matches!(event, TrackEventRequest::McpToolCall(_))) - .expect("MCP tool call event should be emitted"); - let payload = serde_json::to_value(mcp_tool_call_event).expect("serialize MCP tool call event"); - assert_eq!(payload["event_params"]["plugin_id"], json!("sample@test")); - assert_eq!( - payload["event_params"]["voice_session_id"], - "work-voice-456" - ); - assert_eq!( - payload["event_params"]["connector_id"], - json!("connector-test") - ); - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - let turn_event = out - .iter() - .find(|event| matches!(event, TrackEventRequest::TurnEvent(_))) - .expect("turn event should be emitted"); - let payload = serde_json::to_value(turn_event).expect("serialize turn event"); - assert_eq!(payload["event_params"]["root_turn_id"], "root-ancestor"); - assert_eq!( - payload["event_params"]["voice_session_id"], - "work-voice-456" - ); - assert_eq!(payload["event_params"]["total_tool_call_count"], json!(9)); - assert_eq!(payload["event_params"]["shell_command_count"], json!(1)); - assert_eq!(payload["event_params"]["file_change_count"], json!(1)); - assert_eq!(payload["event_params"]["mcp_tool_call_count"], json!(1)); - assert_eq!(payload["event_params"]["dynamic_tool_call_count"], json!(1)); - assert_eq!( - payload["event_params"]["subagent_tool_call_count"], - json!(2) - ); - assert_eq!(payload["event_params"]["web_search_count"], json!(1)); - assert_eq!(payload["event_params"]["image_generation_count"], json!(1)); -} - -#[tokio::test] -async fn turn_does_not_emit_without_required_prerequisites() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ false, - /*include_resolved_config*/ true, - /*include_started*/ false, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - assert!(out.is_empty()); - - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ false, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - assert!(out.is_empty()); -} - -#[tokio::test] -async fn turn_lifecycle_emits_failed_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnCodexError(Box::new( - TurnCodexErrorFact::from_codex_err( - "thread-2".to_string(), - "turn-2".to_string(), - &CodexErr::InvalidRequest("unknown turn environment id `env-2`".to_string()), - ), - ))), - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Failed, - Some(codex_app_server_protocol::CodexErrorInfo::BadRequest), - ))), - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!(payload["event_params"]["status"], json!("failed")); - assert_eq!(payload["event_params"]["turn_error"], json!("badRequest")); - assert_eq!( - payload["event_params"]["codex_error_kind"], - json!("invalid_request") - ); - assert_eq!( - payload["event_params"]["codex_error_http_status_code"], - json!(null) - ); - assert_eq!( - payload["event_params"]["usage_limit_window_minutes"], - json!(null) - ); -} - -#[tokio::test] -async fn turn_event_reports_decisive_usage_limit_window() { - let usage_limit = |limit_window_minutes| { - CodexErr::UsageLimitReached(UsageLimitReachedError { - plan_type: None, - resets_at: None, - rate_limits: None, - promo_message: None, - rate_limit_reached_type: None, - limit_window_minutes, - }) - }; - let cases = [ - ( - usage_limit(Some(300)), - codex_app_server_protocol::CodexErrorInfo::UsageLimitExceeded, - json!(["usageLimitExceeded", "usage_limit_reached", 300]), - ), - ( - usage_limit(Some(10_080)), - codex_app_server_protocol::CodexErrorInfo::UsageLimitExceeded, - json!(["usageLimitExceeded", "usage_limit_reached", 10080]), - ), - ( - usage_limit(None), - codex_app_server_protocol::CodexErrorInfo::UsageLimitExceeded, - json!(["usageLimitExceeded", "usage_limit_reached", null]), - ), - ( - CodexErr::InvalidRequest("invalid request".to_string()), - codex_app_server_protocol::CodexErrorInfo::BadRequest, - json!(["badRequest", "invalid_request", null]), - ), - ]; - - for (error, error_info, expected) in cases { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnCodexError(Box::new( - TurnCodexErrorFact::from_codex_err( - "thread-2".to_string(), - "turn-2".to_string(), - &error, - ), - ))), - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Failed, - Some(error_info), - ))), - &mut out, - ) - .await; - - let [event] = out.as_slice() else { - panic!("expected one turn event"); - }; - let payload = serde_json::to_value(event).expect("serialize turn event"); - let params = &payload["event_params"]; - assert_eq!( - json!([ - params["turn_error"], - params["codex_error_kind"], - params["usage_limit_window_minutes"], - ]), - expected - ); - } -} - -#[tokio::test] -async fn turn_completed_without_started_notification_emits_null_started_at() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ false, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!(payload["event_params"]["started_at"], json!(null)); - assert_eq!(payload["event_params"]["duration_ms"], json!(1234)); - assert_eq!(payload["event_params"]["input_tokens"], json!(null)); - assert_eq!(payload["event_params"]["cached_input_tokens"], json!(null)); - assert_eq!(payload["event_params"]["output_tokens"], json!(null)); - assert_eq!( - payload["event_params"]["reasoning_output_tokens"], - json!(null) - ); - assert_eq!(payload["event_params"]["total_tokens"], json!(null)); -} - -#[tokio::test] -async fn critical_path_payload_preserves_capture_status_and_emits_once() { - use crate::TurnCriticalPath; - use crate::TurnCriticalPathDurations; - use crate::TurnProfileFact; - use crate::tests::support::sample_turn_profile; - - for status in [ - AppServerTurnStatus::Completed, - AppServerTurnStatus::Interrupted, - ] { - for (critical_path, expected) in [ - ( - TurnCriticalPath::Disabled, - json!([ - "disabled", null, null, null, null, null, null, null, null, null - ]), - ), - ( - TurnCriticalPath::Incomplete, - json!([ - "incomplete", - null, - null, - null, - null, - null, - null, - null, - null, - null - ]), - ), - ( - TurnCriticalPath::Complete(TurnCriticalPathDurations { - duration_ms: 1234, - inference_ms: 700, - sampling_ms: 500, - compaction_ms: 200, - auto_review_ms: 200, - auto_review_overhead_ms: Some(40), - user_wait_ms: 100, - tools_ms: 150, - overhead_ms: 80, - unknown_ms: 4, - }), - json!(["complete", 1234, 700, 500, 200, 200, 100, 150, 80, 4]), - ), - ( - TurnCriticalPath::Complete(TurnCriticalPathDurations { - duration_ms: 1234, - inference_ms: 1234, - sampling_ms: 1234, - compaction_ms: 0, - auto_review_ms: 0, - auto_review_overhead_ms: Some(0), - user_wait_ms: 0, - tools_ms: 0, - overhead_ms: 0, - unknown_ms: 0, - }), - json!(["complete", 1234, 1234, 1234, 0, 0, 0, 0, 0, 0]), - ), - ] { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ true, - ) - .await; - let mut profile = sample_turn_profile(); - let expected_review_overhead = match &critical_path { - TurnCriticalPath::Complete(value) => value.auto_review_overhead_ms, - _ => None, - }; - profile.critical_path = critical_path; - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new( - TurnProfileFact { - turn_id: "turn-2".into(), - profile, - }, - ))), - &mut out, - ) - .await; - for _ in 0..2 { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - status.clone(), - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - } - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).unwrap(); - let params = &payload["event_params"]; - assert_eq!( - json!([ - params["critical_path_status"], - params["critical_path_duration_ms"], - params["critical_path_inference_ms"], - params["critical_path_sampling_ms"], - params["critical_path_compaction_ms"], - params["critical_path_auto_review_ms"], - params["critical_path_user_wait_ms"], - params["critical_path_tools_ms"], - params["critical_path_overhead_ms"], - params["critical_path_unknown_ms"], - ]), - expected - ); - assert_eq!( - params.get("critical_path_auto_review_overhead_ms"), - Some(&json!(expected_review_overhead)) - ); - assert_eq!(params["tool_blocking_ms"], json!(250)); - assert_eq!(params["duration_ms"], json!(1234)); - } - } -} diff --git a/codex-rs/analytics/src/tests/suite/turns/requests_tests.rs b/codex-rs/analytics/src/tests/suite/turns/requests_tests.rs deleted file mode 100644 index 2df7ff3a..00000000 --- a/codex-rs/analytics/src/tests/suite/turns/requests_tests.rs +++ /dev/null @@ -1,728 +0,0 @@ -//! Turn start, steer, and interrupt request event tests. - -use crate::events::AppServerRpcTransport; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::AnalyticsJsonRpcError; -use crate::facts::CustomAnalyticsFact; -use crate::facts::InputError; -use crate::facts::TurnSteerRequestError; -use crate::reducer::AnalyticsReducer; -use crate::tests::support::ingest_initialize; -use crate::tests::support::ingest_turn_prerequisites; -use crate::tests::support::sample_runtime_metadata; -use crate::tests::support::sample_thread_resume_response; -use crate::tests::support::sample_turn_completed_notification; -use crate::tests::support::sample_turn_resolved_config; -use crate::tests::support::sample_turn_start_request; -use crate::tests::support::sample_turn_start_response; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::NonSteerableTurnKind; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::TurnError as AppServerTurnError; -use codex_app_server_protocol::TurnInterruptResponse; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_app_server_protocol::TurnSteerParams; -use codex_app_server_protocol::TurnSteerResponse; -use codex_app_server_protocol::UserInput; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn sample_turn_steer_request( - thread_id: &str, - expected_turn_id: &str, - request_id: i64, -) -> ClientRequest { - ClientRequest::TurnSteer { - request_id: RequestId::Integer(request_id), - params: TurnSteerParams { - thread_id: thread_id.to_string(), - expected_turn_id: expected_turn_id.to_string(), - client_user_message_id: None, - input: vec![ - UserInput::Text { - text: "more".to_string(), - text_elements: vec![], - }, - UserInput::LocalImage { - path: "/tmp/a.png".into(), - detail: None, - }, - ], - responsesapi_client_metadata: None, - responsesapi_client_metadata_patch: None, - additional_context: None, - }, - } -} - -fn sample_turn_steer_response(turn_id: &str) -> ClientResponsePayload { - ClientResponsePayload::TurnSteer(TurnSteerResponse { - turn_id: turn_id.to_string(), - }) -} - -fn sample_turn_interrupt_response() -> ClientResponsePayload { - ClientResponsePayload::TurnInterrupt(TurnInterruptResponse {}) -} - -fn no_active_turn_steer_error() -> JSONRPCErrorError { - JSONRPCErrorError { - code: -32600, - message: "no active turn to steer".to_string(), - data: None, - } -} - -fn no_active_turn_steer_error_type() -> AnalyticsJsonRpcError { - AnalyticsJsonRpcError::TurnSteer(TurnSteerRequestError::NoActiveTurn) -} - -fn non_steerable_review_error() -> JSONRPCErrorError { - JSONRPCErrorError { - code: -32600, - message: "cannot steer a review turn".to_string(), - data: Some( - serde_json::to_value(AppServerTurnError { - misalignment: None, - message: "cannot steer a review turn".to_string(), - codex_error_info: Some(CodexErrorInfo::ActiveTurnNotSteerable { - turn_kind: NonSteerableTurnKind::Review, - }), - additional_details: None, - }) - .expect("serialize turn error"), - ), - } -} - -fn non_steerable_review_error_type() -> AnalyticsJsonRpcError { - AnalyticsJsonRpcError::TurnSteer(TurnSteerRequestError::NonSteerableReview) -} - -fn input_too_large_steer_error() -> JSONRPCErrorError { - JSONRPCErrorError { - code: -32602, - message: "Input exceeds the maximum length of 1048576 characters.".to_string(), - data: Some(json!({ - "input_error_code": "input_too_large", - "actual_chars": 1048577, - "max_chars": 1048576, - })), - } -} - -fn input_too_large_error_type() -> AnalyticsJsonRpcError { - AnalyticsJsonRpcError::Input(InputError::TooLarge) -} - -async fn ingest_rejected_turn_steer( - reducer: &mut AnalyticsReducer, - out: &mut Vec, - error: JSONRPCErrorError, - error_type: Option, -) -> serde_json::Value { - ingest_turn_prerequisites( - reducer, out, /*include_initialize*/ true, /*include_resolved_config*/ false, - /*include_started*/ false, /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 8, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-web".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: None, - }, - product_client_id: "codex-web".to_string(), - runtime: sample_runtime_metadata(), - rpc_transport: AppServerRpcTransport::Stdio, - }, - out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 8, - request_id: RequestId::Integer(6), - response: Box::new(sample_thread_resume_response( - "thread-2", /*ephemeral*/ false, "gpt-5", - )), - thread_originator: None, - }, - out, - ) - .await; - out.clear(); - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - request: Box::new(sample_turn_steer_request( - "thread-2", "turn-2", /*request_id*/ 4, - )), - }, - out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - error, - error_type, - }, - out, - ) - .await; - - assert_eq!(out.len(), 1); - serde_json::to_value(&out[0]).expect("serialize turn steer event") -} - -#[tokio::test] -async fn accepted_turn_steer_emits_expected_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ false, - /*include_started*/ false, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - request: Box::new(sample_turn_steer_request( - "thread-2", "turn-2", /*request_id*/ 4, - )), - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - response: Box::new(sample_turn_steer_response("turn-2")), - thread_originator: None, - }, - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn steer event"); - assert_eq!(payload["event_type"], json!("codex_turn_steer_event")); - assert_eq!(payload["event_params"]["thread_id"], json!("thread-2")); - assert_eq!( - payload["event_params"]["session_id"], - json!("session-thread-2") - ); - assert_eq!(payload["event_params"]["expected_turn_id"], json!("turn-2")); - assert_eq!(payload["event_params"]["accepted_turn_id"], json!("turn-2")); - assert_eq!(payload["event_params"]["num_input_images"], json!(1)); - assert_eq!(payload["event_params"]["result"], json!("accepted")); - assert_eq!(payload["event_params"]["rejection_reason"], json!(null)); - assert!( - payload["event_params"]["created_at"] - .as_u64() - .expect("created_at") - > 0 - ); - assert_eq!( - payload["event_params"]["app_server_client"]["product_client_id"], - json!("codex-tui") - ); - assert_eq!( - payload["event_params"]["runtime"]["codex_rs_version"], - json!("0.1.0") - ); - assert_eq!(payload["event_params"]["thread_source"], json!("user")); - assert_eq!(payload["event_params"]["subagent_source"], json!(null)); - assert_eq!(payload["event_params"]["parent_thread_id"], json!(null)); - assert!(payload["event_params"].get("product_client_id").is_none()); -} - -#[tokio::test] -async fn rejected_turn_steer_uses_request_connection_metadata() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - let payload = ingest_rejected_turn_steer( - &mut reducer, - &mut out, - no_active_turn_steer_error(), - Some(no_active_turn_steer_error_type()), - ) - .await; - - assert_eq!(payload["event_type"], json!("codex_turn_steer_event")); - assert_eq!(payload["event_params"]["thread_id"], json!("thread-2")); - assert_eq!(payload["event_params"]["expected_turn_id"], json!("turn-2")); - assert_eq!(payload["event_params"]["accepted_turn_id"], json!(null)); - assert_eq!(payload["event_params"]["num_input_images"], json!(1)); - assert_eq!( - payload["event_params"]["app_server_client"]["product_client_id"], - json!("codex-tui") - ); - assert_eq!( - payload["event_params"]["runtime"]["codex_rs_version"], - json!("0.1.0") - ); - assert_eq!(payload["event_params"]["thread_source"], json!("user")); - assert_eq!(payload["event_params"]["subagent_source"], json!(null)); - assert_eq!(payload["event_params"]["parent_thread_id"], json!(null)); - assert_eq!(payload["event_params"]["result"], json!("rejected")); - assert_eq!( - payload["event_params"]["rejection_reason"], - json!("no_active_turn") - ); - assert!( - payload["event_params"]["created_at"] - .as_u64() - .expect("created_at") - > 0 - ); -} - -#[tokio::test] -async fn rejected_turn_steer_maps_active_turn_not_steerable_error_type() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - let payload = ingest_rejected_turn_steer( - &mut reducer, - &mut out, - non_steerable_review_error(), - Some(non_steerable_review_error_type()), - ) - .await; - - assert_eq!( - payload["event_params"]["rejection_reason"], - json!("non_steerable_review") - ); -} - -#[tokio::test] -async fn rejected_turn_steer_maps_input_too_large_error_type() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - let payload = ingest_rejected_turn_steer( - &mut reducer, - &mut out, - input_too_large_steer_error(), - Some(input_too_large_error_type()), - ) - .await; - - assert_eq!( - payload["event_params"]["rejection_reason"], - json!("input_too_large") - ); -} - -#[tokio::test] -async fn turn_steer_does_not_emit_without_pending_request() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - error: no_active_turn_steer_error(), - error_type: Some(no_active_turn_steer_error_type()), - }, - &mut out, - ) - .await; - - assert!(out.is_empty()); -} - -#[tokio::test] -async fn turn_start_error_response_discards_pending_start_request() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_initialize(&mut reducer, &mut out).await; - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(3), - request: Box::new(sample_turn_start_request("thread-2", /*request_id*/ 3)), - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - error: no_active_turn_steer_error(), - error_type: None, - }, - &mut out, - ) - .await; - - // A late/synthetic response for the same request id must not resurrect the - // failed turn/start request and attach request-scoped connection metadata. - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-2")), - thread_originator: None, - }, - &mut out, - ) - .await; - assert!(out.is_empty()); - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - sample_turn_resolved_config("thread-2", "turn-2"), - ))), - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert!(out.is_empty()); -} - -#[tokio::test] -async fn accepted_steers_increment_turn_steer_count() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - request: Box::new(sample_turn_steer_request( - "thread-2", "turn-2", /*request_id*/ 4, - )), - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - response: Box::new(sample_turn_steer_response("turn-2")), - thread_originator: None, - }, - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(5), - request: Box::new(sample_turn_steer_request( - "thread-2", "turn-2", /*request_id*/ 5, - )), - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id: 7, - request_id: RequestId::Integer(5), - error: no_active_turn_steer_error(), - error_type: Some(no_active_turn_steer_error_type()), - }, - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(6), - request: Box::new(sample_turn_steer_request( - "thread-2", "turn-2", /*request_id*/ 6, - )), - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(6), - response: Box::new(sample_turn_steer_response("turn-2")), - thread_originator: None, - }, - &mut out, - ) - .await; - - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - let turn_event = out - .iter() - .find(|event| matches!(event, TrackEventRequest::TurnEvent(_))) - .expect("turn event should be emitted"); - let payload = serde_json::to_value(turn_event).expect("serialize turn event"); - assert_eq!(payload["event_params"]["steer_count"], json!(2)); -} - -#[tokio::test] -async fn rejected_turn_interrupt_does_not_tag_interrupted_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - turn_id: "turn-2".to_string(), - requested_at_ms: 1716000000123, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ErrorResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - error: no_active_turn_steer_error(), - error_type: None, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Interrupted, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!(payload["event_params"]["status"], json!("interrupted")); - assert_eq!( - payload["event_params"]["explicit_client_interrupt_requested_at_ms"], - json!(null) - ); - assert_eq!(payload["event_params"]["turn_error"], json!(null)); - assert_eq!(payload["event_params"]["codex_error_kind"], json!(null)); -} - -#[tokio::test] -async fn accepted_turn_interrupt_records_requested_at_on_turn_event() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - turn_id: "turn-2".to_string(), - requested_at_ms: 1716000000123, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - response: Box::new(sample_turn_interrupt_response()), - thread_originator: None, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Interrupted, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!( - payload["event_params"]["explicit_client_interrupt_requested_at_ms"], - json!(1716000000123_u64) - ); -} - -#[tokio::test] -async fn accepted_turn_interrupt_retries_preserve_earliest_requested_at() { - let mut reducer = AnalyticsReducer::default(); - let mut out = Vec::new(); - - ingest_turn_prerequisites( - &mut reducer, - &mut out, - /*include_initialize*/ true, - /*include_resolved_config*/ true, - /*include_started*/ true, - /*include_token_usage*/ false, - ) - .await; - reducer - .ingest( - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id: 7, - request_id: RequestId::Integer(4), - turn_id: "turn-2".to_string(), - requested_at_ms: 1716000000123, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ExplicitClientInterruptRequest { - connection_id: 7, - request_id: RequestId::Integer(5), - turn_id: "turn-2".to_string(), - requested_at_ms: 1716000000456, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(5), - response: Box::new(sample_turn_interrupt_response()), - thread_originator: None, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(4), - response: Box::new(sample_turn_interrupt_response()), - thread_originator: None, - }, - &mut out, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - "thread-2", - "turn-2", - AppServerTurnStatus::Interrupted, - /*codex_error_info*/ None, - ))), - &mut out, - ) - .await; - - assert_eq!(out.len(), 1); - let payload = serde_json::to_value(&out[0]).expect("serialize turn event"); - assert_eq!( - payload["event_params"]["explicit_client_interrupt_requested_at_ms"], - json!(1716000000123_u64) - ); -} diff --git a/codex-rs/analytics/src/tests/suite/turns_tests.rs b/codex-rs/analytics/src/tests/suite/turns_tests.rs deleted file mode 100644 index c2b0d0a5..00000000 --- a/codex-rs/analytics/src/tests/suite/turns_tests.rs +++ /dev/null @@ -1,8 +0,0 @@ -#[path = "turns/accepted_lines_tests.rs"] -mod accepted_lines; -#[path = "turns/compaction_tests.rs"] -mod compaction; -#[path = "turns/events_tests.rs"] -mod events; -#[path = "turns/requests_tests.rs"] -mod requests; diff --git a/codex-rs/analytics/src/tests/support.rs b/codex-rs/analytics/src/tests/support.rs deleted file mode 100644 index b1cc0dd4..00000000 --- a/codex-rs/analytics/src/tests/support.rs +++ /dev/null @@ -1,708 +0,0 @@ -//! Shared analytics test facts, fixtures, and reducer setup. - -use crate::events::AppServerRpcTransport; -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexRuntimeMetadata; -use crate::events::TrackEventRequest; -use crate::facts::AnalyticsFact; -use crate::facts::CodeModeToolCallFact; -use crate::facts::CustomAnalyticsFact; -use crate::facts::TrackEventsContext; -use crate::facts::TurnAnalyticsMetadata; -use crate::facts::TurnProfile; -use crate::facts::TurnProfileFact; -use crate::facts::TurnResolvedConfigFact; -use crate::facts::TurnTokenUsageFact; -use crate::reducer::AnalyticsReducer; -use codex_app_server_protocol::ApprovalsReviewer as AppServerApprovalsReviewer; -use codex_app_server_protocol::AskForApproval as AppServerAskForApproval; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ClientResponsePayload; -use codex_app_server_protocol::CommandExecutionSource; -use codex_app_server_protocol::CommandExecutionStatus; -use codex_app_server_protocol::ImageReference; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SandboxPolicy as AppServerSandboxPolicy; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionSource as AppServerSessionSource; -use codex_app_server_protocol::Thread; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::ThreadResumeResponse; -use codex_app_server_protocol::ThreadSource as AppServerThreadSource; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::ThreadStatus as AppServerThreadStatus; -use codex_app_server_protocol::Turn; -use codex_app_server_protocol::TurnCompletedNotification; -use codex_app_server_protocol::TurnError as AppServerTurnError; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartedNotification; -use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; -use codex_app_server_protocol::UserInput; -use codex_login::default_client::DEFAULT_ORIGINATOR; -use codex_plugin::AppConnectorId; -use codex_plugin::PluginCapabilitySummary; -use codex_plugin::PluginId; -use codex_plugin::PluginTelemetryMetadata; -use codex_protocol::config_types::ApprovalsReviewer; -use codex_protocol::config_types::ModeKind; -use codex_protocol::models::PermissionProfile as CorePermissionProfile; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::TokenUsage; -use codex_utils_absolute_path::test_support::PathBufExt; -use codex_utils_absolute_path::test_support::test_path_buf; -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::Mutex; - -pub(super) const TEST_PRODUCT_CLIENT_ID: &str = "codex_work_desktop"; - -pub(super) struct TestTurnMetadata { - pub(super) root_turn_id: Mutex>, - pub(super) turn_trigger: Option, -} - -impl TurnAnalyticsMetadata for TestTurnMetadata { - fn root_turn_id(&self) -> Option { - self.root_turn_id.lock().expect("root turn ID").clone() - } - - fn turn_trigger(&self) -> Option { - self.turn_trigger.clone() - } - - fn codex_turn_source(&self) -> Option { - None - } -} - -pub(super) fn test_turn_metadata(root_turn_id: Option<&str>) -> Arc { - Arc::new(TestTurnMetadata { - root_turn_id: Mutex::new(root_turn_id.map(str::to_string)), - turn_trigger: None, - }) -} - -pub(super) fn test_tracking_context(thread_id: &str, turn_id: &str) -> TrackEventsContext { - TrackEventsContext { - model_slug: "gpt-5".to_string(), - thread_id: thread_id.to_string(), - turn_id: turn_id.to_string(), - product_client_id: TEST_PRODUCT_CLIENT_ID.to_string(), - turn_metadata: None, - } -} - -pub(super) fn sample_thread_with_metadata( - thread_id: &str, - ephemeral: bool, - source: AppServerSessionSource, - thread_source: Option, - parent_thread_id: Option, -) -> Thread { - Thread { - originator: None, - environments: None, - id: thread_id.to_string(), - extra: None, - session_id: format!("session-{thread_id}"), - forked_from_id: None, - parent_thread_id, - preview: "first prompt".to_string(), - ephemeral, - section: None, - section_entered_at: None, - project_id: None, - daybreak_enabled: None, - history_mode: Default::default(), - model_provider: "openai".to_string(), - model: None, - reasoning_effort: None, - created_at: 1, - updated_at: 2, - recency_at: Some(2), - status: AppServerThreadStatus::Idle, - path: None, - cwd: test_path_buf("/tmp").abs(), - cli_version: "0.0.0".to_string(), - source, - can_accept_direct_input: None, - thread_source, - agent_nickname: None, - agent_role: None, - git_info: None, - name: None, - turns: Vec::new(), - } -} - -pub(super) fn sample_thread_start_response( - thread_id: &str, - ephemeral: bool, - model: &str, -) -> ClientResponsePayload { - ClientResponsePayload::ThreadStart(ThreadStartResponse { - disabled_plugin_ids: Vec::new(), - thread: sample_thread_with_metadata( - thread_id, - ephemeral, - AppServerSessionSource::Exec, - Some(AppServerThreadSource::User), - /*parent_thread_id*/ None, - ), - model: model.to_string(), - model_provider: "openai".to_string(), - service_tier: None, - cwd: test_path_buf("/tmp").abs(), - runtime_workspace_roots: Vec::new(), - instruction_sources: Vec::new(), - approval_policy: AppServerAskForApproval::OnRequest, - approvals_reviewer: AppServerApprovalsReviewer::User, - sandbox: AppServerSandboxPolicy::DangerFullAccess, - active_permission_profile: None, - reasoning_effort: None, - multi_agent_mode: Default::default(), - }) -} - -pub(super) fn sample_app_server_client_metadata() -> CodexAppServerClientMetadata { - CodexAppServerClientMetadata { - product_client_id: DEFAULT_ORIGINATOR.to_string(), - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - rpc_transport: AppServerRpcTransport::Stdio, - experimental_api_enabled: Some(true), - } -} - -pub(super) fn sample_runtime_metadata() -> CodexRuntimeMetadata { - CodexRuntimeMetadata { - codex_rs_version: "0.1.0".to_string(), - runtime_os: "macos".to_string(), - runtime_os_version: "15.3.1".to_string(), - runtime_arch: "aarch64".to_string(), - } -} - -pub(super) fn sample_thread_resume_response( - thread_id: &str, - ephemeral: bool, - model: &str, -) -> ClientResponsePayload { - sample_thread_resume_response_with_source( - thread_id, - ephemeral, - model, - AppServerSessionSource::Exec, - Some(AppServerThreadSource::User), - /*parent_thread_id*/ None, - ) -} - -pub(super) fn sample_thread_resume_response_with_source( - thread_id: &str, - ephemeral: bool, - model: &str, - source: AppServerSessionSource, - thread_source: Option, - parent_thread_id: Option, -) -> ClientResponsePayload { - ClientResponsePayload::ThreadResume(ThreadResumeResponse { - disabled_plugin_ids: Vec::new(), - thread: sample_thread_with_metadata( - thread_id, - ephemeral, - source, - thread_source, - parent_thread_id, - ), - model: model.to_string(), - model_provider: "openai".to_string(), - service_tier: None, - cwd: test_path_buf("/tmp").abs(), - runtime_workspace_roots: Vec::new(), - instruction_sources: Vec::new(), - approval_policy: AppServerAskForApproval::OnRequest, - approvals_reviewer: AppServerApprovalsReviewer::User, - sandbox: AppServerSandboxPolicy::DangerFullAccess, - active_permission_profile: None, - reasoning_effort: None, - collaboration_mode: None, - multi_agent_mode: Default::default(), - initial_turns_page: None, - turns_backwards_cursor: None, - items_backwards_cursor: None, - }) -} - -pub(super) fn sample_turn_start_request(thread_id: &str, request_id: i64) -> ClientRequest { - ClientRequest::TurnStart { - request_id: RequestId::Integer(request_id), - params: TurnStartParams { - thread_id: thread_id.to_string(), - client_user_message_id: None, - input: vec![ - UserInput::Text { - text: "hello".to_string(), - text_elements: vec![], - }, - UserInput::Image { - image: ImageReference::Inline { - url: "https://example.com/a.png".to_string(), - }, - detail: None, - }, - ], - ..Default::default() - }, - } -} - -pub(super) fn sample_turn_start_response(turn_id: &str) -> ClientResponsePayload { - ClientResponsePayload::TurnStart(codex_app_server_protocol::TurnStartResponse { - turn: Turn { - id: turn_id.to_string(), - root_turn_id: None, - items_view: codex_app_server_protocol::TurnItemsView::Full, - items: vec![], - status: AppServerTurnStatus::InProgress, - error: None, - started_at: None, - completed_at: None, - duration_ms: None, - }, - }) -} - -pub(super) fn sample_turn_started_notification( - thread_id: &str, - turn_id: &str, -) -> ServerNotification { - ServerNotification::TurnStarted(TurnStartedNotification { - thread_id: thread_id.to_string(), - turn: Turn { - id: turn_id.to_string(), - root_turn_id: None, - items_view: codex_app_server_protocol::TurnItemsView::Full, - items: vec![], - status: AppServerTurnStatus::InProgress, - error: None, - started_at: Some(455), - completed_at: None, - duration_ms: None, - }, - }) -} - -pub(super) fn sample_turn_token_usage_fact(thread_id: &str, turn_id: &str) -> TurnTokenUsageFact { - TurnTokenUsageFact { - thread_id: thread_id.to_string(), - turn_id: turn_id.to_string(), - token_usage: TokenUsage { - total_tokens: 321, - input_tokens: 123, - cached_input_tokens: 45, - cache_write_input_tokens: 7, - output_tokens: 140, - reasoning_output_tokens: 13, - codex_rollout_budget_units: None, - }, - } -} - -pub(super) fn sample_turn_completed_notification( - thread_id: &str, - turn_id: &str, - status: AppServerTurnStatus, - codex_error_info: Option, -) -> ServerNotification { - ServerNotification::TurnCompleted(TurnCompletedNotification { - thread_id: thread_id.to_string(), - turn: Turn { - id: turn_id.to_string(), - root_turn_id: None, - items_view: codex_app_server_protocol::TurnItemsView::Full, - items: vec![], - status, - error: codex_error_info.map(|codex_error_info| AppServerTurnError { - misalignment: None, - message: "turn failed".to_string(), - codex_error_info: Some(codex_error_info), - additional_details: None, - }), - started_at: None, - completed_at: Some(456), - duration_ms: Some(1234), - }, - }) -} - -pub(super) fn sample_turn_resolved_config( - thread_id: &str, - turn_id: &str, -) -> TurnResolvedConfigFact { - TurnResolvedConfigFact { - turn_id: turn_id.to_string(), - thread_id: thread_id.to_string(), - turn_metadata: test_turn_metadata(/*root_turn_id*/ None), - active_plugin_ids_at_turn_start: None, - num_input_images: 1, - submission_type: None, - ephemeral: false, - session_source: SessionSource::Exec, - model: "gpt-5".to_string(), - model_provider: "openai".to_string(), - permission_profile: CorePermissionProfile::read_only(), - permission_profile_cwd: PathBuf::from("/tmp"), - reasoning_effort: None, - reasoning_summary: None, - service_tier: None, - approval_policy: AskForApproval::OnRequest, - approvals_reviewer: ApprovalsReviewer::AutoReview, - guardian_v2_enabled: false, - multi_agent_version: codex_protocol::protocol::MultiAgentVersion::Disabled, - sandbox_network_access: true, - collaboration_mode: ModeKind::Plan, - personality: None, - workspace_kind: None, - is_first_turn: true, - } -} - -pub(super) fn sample_turn_profile() -> TurnProfile { - TurnProfile { - critical_path: crate::TurnCriticalPath::Disabled, - before_first_sampling_ms: 100, - sampling_ms: 700, - compaction_ms: 40, - between_sampling_overhead_ms: 50, - tool_blocking_ms: 250, - after_last_sampling_ms: 94, - sampling_request_count: 2, - sampling_retry_count: 1, - tools_change_count: 2, - } -} - -pub(super) async fn ingest_initialize( - reducer: &mut AnalyticsReducer, - out: &mut Vec, -) { - reducer - .ingest( - AnalyticsFact::Initialize { - connection_id: 7, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-tui".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: None, - }, - product_client_id: "codex-tui".to_string(), - runtime: sample_runtime_metadata(), - rpc_transport: AppServerRpcTransport::Stdio, - }, - out, - ) - .await; -} - -pub(super) async fn ingest_turn_prerequisites( - reducer: &mut AnalyticsReducer, - out: &mut Vec, - include_initialize: bool, - include_resolved_config: bool, - include_started: bool, - include_token_usage: bool, -) { - if include_initialize { - ingest_initialize(reducer, out).await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - "thread-2", /*ephemeral*/ false, "gpt-5", - )), - thread_originator: None, - }, - out, - ) - .await; - out.clear(); - } - - reducer - .ingest( - AnalyticsFact::ClientRequest { - connection_id: 7, - request_id: RequestId::Integer(3), - request: Box::new(sample_turn_start_request("thread-2", /*request_id*/ 3)), - }, - out, - ) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(3), - response: Box::new(sample_turn_start_response("turn-2")), - thread_originator: None, - }, - out, - ) - .await; - - if include_resolved_config { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - sample_turn_resolved_config("thread-2", "turn-2"), - ))), - out, - ) - .await; - } - - if include_started { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - "thread-2", "turn-2", - ))), - out, - ) - .await; - } - - if include_token_usage { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnTokenUsage(Box::new( - sample_turn_token_usage_fact("thread-2", "turn-2"), - ))), - out, - ) - .await; - } - - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new( - TurnProfileFact { - turn_id: "turn-2".to_string(), - profile: sample_turn_profile(), - }, - ))), - out, - ) - .await; -} - -pub(super) async fn ingest_review_prerequisites( - reducer: &mut AnalyticsReducer, - events: &mut Vec, -) { - reducer - .ingest(sample_initialize_fact(/*connection_id*/ 7), events) - .await; - reducer - .ingest( - AnalyticsFact::ClientResponse { - connection_id: 7, - request_id: RequestId::Integer(1), - response: Box::new(sample_thread_start_response( - "thread-1", /*ephemeral*/ false, "gpt-5", - )), - thread_originator: None, - }, - events, - ) - .await; - events.clear(); -} - -pub(super) async fn ingest_completed_command_execution_item( - reducer: &mut AnalyticsReducer, - events: &mut Vec, - thread_id: &str, - item_id: &str, -) { - reducer - .ingest( - AnalyticsFact::Notification(Box::new(sample_turn_started_notification( - thread_id, "turn-1", - ))), - events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted( - ItemStartedNotification::new( - thread_id.to_string(), - "turn-1".to_string(), - sample_command_execution_item_with_id( - item_id, - CommandExecutionStatus::InProgress, - /*exit_code*/ None, - /*duration_ms*/ None, - ), - /*started_at_ms*/ 1_000, - ), - ))), - events, - ) - .await; - reducer - .ingest( - AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted( - ItemCompletedNotification::new( - thread_id.to_string(), - "turn-1".to_string(), - sample_command_execution_item_with_id( - item_id, - CommandExecutionStatus::Completed, - Some(0), - Some(42), - ), - /*started_at_ms*/ None, - /*completed_at_ms*/ 1_042, - ), - ))), - events, - ) - .await; -} - -pub(super) fn sample_initialize_fact(connection_id: u64) -> AnalyticsFact { - AnalyticsFact::Initialize { - connection_id, - params: InitializeParams { - client_info: ClientInfo { - name: "codex-tui".to_string(), - title: None, - version: "1.0.0".to_string(), - }, - capabilities: Some(InitializeCapabilities { - required_human_approval: false, - explicit_gateway_oauth: false, - experimental_api: false, - request_attestation: false, - opt_out_notification_methods: None, - mcp_server_openai_form_elicitation: false, - extensions: None, - }), - }, - product_client_id: DEFAULT_ORIGINATOR.to_string(), - runtime: CodexRuntimeMetadata { - codex_rs_version: "0.99.0".to_string(), - runtime_os: "linux".to_string(), - runtime_os_version: "24.04".to_string(), - runtime_arch: "x86_64".to_string(), - }, - rpc_transport: AppServerRpcTransport::Websocket, - } -} - -pub(super) async fn ingest_complete_child_turn( - reducer: &mut AnalyticsReducer, - events: &mut Vec, - thread_id: &str, - turn_id: &str, -) { - for fact in [ - AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new( - sample_turn_resolved_config(thread_id, turn_id), - ))), - AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new( - TurnProfileFact { - turn_id: turn_id.to_string(), - profile: sample_turn_profile(), - }, - ))), - AnalyticsFact::Notification(Box::new(sample_turn_completed_notification( - thread_id, - turn_id, - AppServerTurnStatus::Completed, - /*codex_error_info*/ None, - ))), - ] { - reducer.ingest(fact, events).await; - } -} - -pub(super) fn sample_command_execution_item( - status: CommandExecutionStatus, - exit_code: Option, - duration_ms: Option, -) -> ThreadItemPayload { - sample_command_execution_item_with_id("item-1", status, exit_code, duration_ms) -} - -pub(super) fn sample_command_execution_item_with_id( - id: &str, - status: CommandExecutionStatus, - exit_code: Option, - duration_ms: Option, -) -> ThreadItemPayload { - ThreadItemPayload::CommandExecution { - model_context: None, - sandbox_type: None, - id: id.to_string(), - plugin_id: None, - script_path: None, - command: "echo hi".to_string(), - cwd: test_path_buf("/tmp").abs().into(), - process_id: Some("pid-1".to_string()), - source: CommandExecutionSource::Agent, - status, - command_actions: Vec::new(), - aggregated_output: None, - exit_code, - duration_ms, - } -} - -pub(super) async fn ingest_code_mode_facts( - reducer: &mut AnalyticsReducer, - events: &mut Vec, - facts: impl IntoIterator, -) { - for fact in facts { - reducer - .ingest( - AnalyticsFact::Custom(CustomAnalyticsFact::CodeModeToolCall(fact)), - events, - ) - .await; - } -} - -pub(super) fn sample_plugin_metadata() -> PluginTelemetryMetadata { - PluginTelemetryMetadata { - plugin_id: Some(PluginId::parse("sample@test").expect("valid plugin id")), - remote_plugin_id: None, - capability_summary: Some(PluginCapabilitySummary { - config_name: "sample@test".to_string(), - display_name: "sample".to_string(), - plugin_namespace: None, - description: None, - has_skills: true, - mcp_server_names: vec!["mcp-1".to_string(), "mcp-2".to_string()], - app_connector_ids: vec![ - AppConnectorId("calendar".to_string()), - AppConnectorId("drive".to_string()), - ], - }), - } -} diff --git a/codex-rs/analytics/src/thread_hint.rs b/codex-rs/analytics/src/thread_hint.rs deleted file mode 100644 index c863558b..00000000 --- a/codex-rs/analytics/src/thread_hint.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! Per-attempt thread hint status analytics without hint contents. - -use crate::events::CodexAppServerClientMetadata; -use crate::events::CodexRuntimeMetadata; -use codex_protocol::protocol::ThreadSource; -use serde::Serialize; - -#[derive(Clone, Copy, Debug, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum ThreadHintStatus { - Succeeded, - Failed, -} - -pub struct ThreadHintStatusEvent { - pub thread_id: String, - pub status: ThreadHintStatus, - pub occurred_at_ms: u64, -} - -#[derive(Serialize)] -pub(crate) struct ThreadHintStatusEventRequest { - pub(crate) event_type: &'static str, - pub(crate) event_params: ThreadHintStatusEventParams, -} - -#[derive(Serialize)] -pub(crate) struct ThreadHintStatusEventParams { - pub(crate) thread_id: String, - pub(crate) session_id: String, - pub(crate) app_server_client: CodexAppServerClientMetadata, - pub(crate) runtime: CodexRuntimeMetadata, - pub(crate) thread_source: Option, - pub(crate) subagent_source: Option, - pub(crate) parent_thread_id: Option, - pub(crate) status: ThreadHintStatus, - pub(crate) occurred_at_ms: u64, -} diff --git a/codex-rs/analytics/src/turn_critical_path.rs b/codex-rs/analytics/src/turn_critical_path.rs deleted file mode 100644 index 649a2f4f..00000000 --- a/codex-rs/analytics/src/turn_critical_path.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! Turn critical-path facts and their nullable analytics fields. -//! Missing capture never becomes a zero-duration measurement. - -use serde::Serialize; - -/// Capture coverage for one finalized turn, independent of its completion status. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] -pub enum TurnCriticalPath { - #[default] - Disabled, - Incomplete, - Complete(TurnCriticalPathDurations), -} - -impl TurnCriticalPath { - pub fn status(&self) -> &'static str { - match self { - Self::Disabled => "disabled", - Self::Incomplete => "incomplete", - Self::Complete(_) => "complete", - } - } - - pub fn durations(&self) -> Option<&TurnCriticalPathDurations> { - match self { - Self::Complete(durations) => Some(durations), - Self::Disabled | Self::Incomplete => None, - } - } -} - -/// Category totals over the server turn interval, truncated to milliseconds. -/// Inference is the compatibility total of sampling and compaction, not another leaf. -/// Independent truncation can leave the seven leaf categories up to six milliseconds -/// below duration_ms, and sampling_ms + compaction_ms up to one below inference_ms. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct TurnCriticalPathDurations { - pub duration_ms: u64, - pub inference_ms: u64, - pub sampling_ms: u64, - pub compaction_ms: u64, - pub auto_review_ms: u64, - /// Portion of auto_review_ms outside observed Guardian turn execution; not additive. - pub auto_review_overhead_ms: Option, - pub user_wait_ms: u64, - pub tools_ms: u64, - pub overhead_ms: u64, - pub unknown_ms: u64, -} - -#[derive(Serialize)] -pub(crate) struct CriticalPathEventParams { - critical_path_status: &'static str, - critical_path_duration_ms: Option, - critical_path_inference_ms: Option, - critical_path_sampling_ms: Option, - critical_path_compaction_ms: Option, - critical_path_auto_review_ms: Option, - critical_path_auto_review_overhead_ms: Option, - critical_path_user_wait_ms: Option, - critical_path_tools_ms: Option, - critical_path_overhead_ms: Option, - critical_path_unknown_ms: Option, -} - -impl From for CriticalPathEventParams { - fn from(path: TurnCriticalPath) -> Self { - let durations = path.durations(); - Self { - critical_path_status: path.status(), - critical_path_duration_ms: durations.map(|value| value.duration_ms), - critical_path_inference_ms: durations.map(|value| value.inference_ms), - critical_path_sampling_ms: durations.map(|value| value.sampling_ms), - critical_path_compaction_ms: durations.map(|value| value.compaction_ms), - critical_path_auto_review_ms: durations.map(|value| value.auto_review_ms), - critical_path_auto_review_overhead_ms: durations - .and_then(|value| value.auto_review_overhead_ms), - critical_path_user_wait_ms: durations.map(|value| value.user_wait_ms), - critical_path_tools_ms: durations.map(|value| value.tools_ms), - critical_path_overhead_ms: durations.map(|value| value.overhead_ms), - critical_path_unknown_ms: durations.map(|value| value.unknown_ms), - } - } -} diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index bf0380b7..0a3cf9f1 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -65,7 +65,6 @@ use codex_config::CloudConfigBundleLoader; use codex_config::LoaderOverrides; use codex_config::NoopThreadConfigLoader; use codex_core::config::Config; -pub use codex_core::otel_init::build_provider as build_otel_provider; pub use codex_exec_server::EnvironmentManager; pub use codex_exec_server::ExecServerRuntimeOptions; use codex_feedback::CodexFeedback; @@ -99,8 +98,8 @@ pub mod legacy_core { } const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); -// Covers the embedded drain, its analytics flush, and final task join. -const IN_PROCESS_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(45); +// Covers the embedded drain and final task join. +const IN_PROCESS_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(20); /// Raw app-server request result for typed in-process requests. /// diff --git a/codex-rs/app-server-daemon/src/backend/pid.rs b/codex-rs/app-server-daemon/src/backend/pid.rs index 2d84a3ee..8adb46b9 100644 --- a/codex-rs/app-server-daemon/src/backend/pid.rs +++ b/codex-rs/app-server-daemon/src/backend/pid.rs @@ -409,8 +409,6 @@ impl PidBackend { } }; if matches!(self.command_kind, PidCommandKind::AppServer { .. }) { - // Match first-party clients' default while preserving explicit analytics opt-outs. - args.push("--analytics-default-enabled".into()); for (name, enabled) in &self.feature_overrides { args.extend(["-c".into(), format!("features.{name}={enabled}").into()]); } diff --git a/codex-rs/app-server-daemon/src/backend/pid_start.rs b/codex-rs/app-server-daemon/src/backend/pid_start.rs index e6a3998a..237e22ad 100644 --- a/codex-rs/app-server-daemon/src/backend/pid_start.rs +++ b/codex-rs/app-server-daemon/src/backend/pid_start.rs @@ -10,7 +10,7 @@ use super::PidFileState; use super::PidRecord; use super::read_process_start_time; use crate::managed_install::executable_identity; -use crate::telemetry::StartFailure; +use crate::start_error::StartFailure; use anyhow::Context; use anyhow::Result; use anyhow::bail; @@ -107,8 +107,6 @@ impl PidBackend { } }; command - // Handoff suppression belongs to the foreground CLI, not its long-lived children. - .env_remove(crate::telemetry::HANDOFF_ENV) .args(self.command_args().iter().map(std::borrow::Cow::as_ref)) .stdin(Stdio::null()) .stdout(Stdio::null()) diff --git a/codex-rs/app-server-daemon/src/backend/pid_tests.rs b/codex-rs/app-server-daemon/src/backend/pid_tests.rs index 8fe71690..44329619 100644 --- a/codex-rs/app-server-daemon/src/backend/pid_tests.rs +++ b/codex-rs/app-server-daemon/src/backend/pid_tests.rs @@ -274,7 +274,7 @@ async fn start_retries_stale_empty_pid_file_under_its_own_lock() { .starts_with("failed to spawn detached app-server process using ") ); assert_eq!( - crate::telemetry::StartError::from(err).failure_reason(), + crate::start_error::StartError::from(err).failure_reason(), "spawn" ); } @@ -721,12 +721,7 @@ fn app_server_remote_control_setting_never_passes_runtime_flag() { assert_eq!( backend.command_args(), - vec![ - "app-server", - "--listen", - "unix://", - "--analytics-default-enabled" - ] + vec!["app-server", "--listen", "unix://"] ); } @@ -740,12 +735,7 @@ fn app_server_disabled_remote_control_uses_compatible_args_and_runtime_env() { assert_eq!( backend.command_args(), - vec![ - "app-server", - "--listen", - "unix://", - "--analytics-default-enabled" - ] + vec!["app-server", "--listen", "unix://"] ); assert_eq!( backend.command_env(), diff --git a/codex-rs/app-server-daemon/src/backend/windows.rs b/codex-rs/app-server-daemon/src/backend/windows.rs index 9c27220a..449e8c15 100644 --- a/codex-rs/app-server-daemon/src/backend/windows.rs +++ b/codex-rs/app-server-daemon/src/backend/windows.rs @@ -157,7 +157,7 @@ pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> { let child = match command.spawn() { Ok(child) => child, Err(_) => { - return Err(err).context(crate::telemetry::StartFailure::Spawn( + return Err(err).context(crate::start_error::StartFailure::Spawn( "cannot launch detached daemon".into(), )); } @@ -165,7 +165,7 @@ pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> { (child, Err(err).context(DetachedLaunchRestricted)) } Err(err) => { - return Err(err).context(crate::telemetry::StartFailure::Spawn( + return Err(err).context(crate::start_error::StartFailure::Spawn( "cannot launch detached daemon".into(), )); } diff --git a/codex-rs/app-server-daemon/src/launch.rs b/codex-rs/app-server-daemon/src/launch.rs index e09ed2ae..e9009e48 100644 --- a/codex-rs/app-server-daemon/src/launch.rs +++ b/codex-rs/app-server-daemon/src/launch.rs @@ -4,7 +4,7 @@ use crate::Daemon; use crate::LifecycleOutput; use crate::ensure_supported_platform; -use crate::telemetry::StartError; +use crate::start_error::StartError; use anyhow::Result; use anyhow::ensure; use std::collections::BTreeMap; diff --git a/codex-rs/app-server-daemon/src/lib.rs b/codex-rs/app-server-daemon/src/lib.rs index 3a7bb366..d5c0bf57 100644 --- a/codex-rs/app-server-daemon/src/lib.rs +++ b/codex-rs/app-server-daemon/src/lib.rs @@ -22,7 +22,7 @@ pub use prepare_install::InstallRequest; pub use prepare_install::update_from_cli; mod remote_control_client; mod settings; -pub mod telemetry; +pub mod start_error; mod thread_recovery; mod update_loop; @@ -47,8 +47,8 @@ use managed_install::managed_codex_version; use serde::Serialize; use settings::DaemonSettings; use settings::MAX_SHUTDOWN_GRACE_SECONDS; -use telemetry::StartError; -use telemetry::StartFailure; +use start_error::StartError; +use start_error::StartFailure; use tokio::time::sleep; const START_POLL_INTERVAL: Duration = Duration::from_millis(50); diff --git a/codex-rs/app-server-daemon/src/settings.rs b/codex-rs/app-server-daemon/src/settings.rs index 49d89cfa..096ca7f3 100644 --- a/codex-rs/app-server-daemon/src/settings.rs +++ b/codex-rs/app-server-daemon/src/settings.rs @@ -193,38 +193,6 @@ impl DaemonSettings { } } -pub(crate) async fn telemetry_tags(path: &Path) -> Result<[(&'static str, &'static str); 4]> { - let raw: Map = read_settings(path).await?; - // Validate the same snapshot used for presence checks, using the existing settings parser. - let settings: StoredSettings = serde_json::from_value(Value::Object(raw.clone()))?; - settings.updater.validate()?; - validate_shutdown_grace(settings.shutdown_grace_seconds)?; - let updater = raw.get("updater"); - let presence = |configured| if configured { "configured" } else { "default" }; - Ok([ - ( - "auto_update", - if settings.updater.auto_update_enabled { - "enabled" - } else { - "disabled" - }, - ), - ( - "auto_update_setting", - presence(updater.is_some_and(|value| value.get("autoUpdateEnabled").is_some())), - ), - ( - "update_interval_setting", - presence(updater.is_some_and(|value| value.get("updateIntervalMinutes").is_some())), - ), - ( - "shutdown_grace_setting", - presence(raw.contains_key("shutdownGraceSeconds")), - ), - ]) -} - async fn read_settings(path: &Path) -> Result { let contents = match fs::read_to_string(path).await { Ok(contents) => contents, diff --git a/codex-rs/app-server-daemon/src/settings_tests.rs b/codex-rs/app-server-daemon/src/settings_tests.rs index c8d81fb8..cc411e52 100644 --- a/codex-rs/app-server-daemon/src/settings_tests.rs +++ b/codex-rs/app-server-daemon/src/settings_tests.rs @@ -129,27 +129,3 @@ async fn update_interval_accepts_long_values_and_rejects_zero() { } } } - -#[tokio::test] -async fn telemetry_distinguishes_presence_from_default_values() -> anyhow::Result<()> { - let home = TempDir::new()?; - let dir = home.path().join("app-server-daemon"); - tokio::fs::create_dir(&dir).await?; - let path = dir.join("settings.json"); - for (contents, presence) in [ - ("{}", "default"), - ( - r#"{"updater":{"autoUpdateEnabled":true,"updateIntervalMinutes":60},"shutdownGraceSeconds":60}"#, - "configured", - ), - ] { - tokio::fs::write(&path, contents).await?; - assert_eq!( - crate::telemetry::settings_tags(home.path()) - .await - .map(|(_, value)| value), - ["enabled", presence, presence, presence] - ); - } - Ok(()) -} diff --git a/codex-rs/app-server-daemon/src/telemetry.rs b/codex-rs/app-server-daemon/src/start_error.rs similarity index 61% rename from codex-rs/app-server-daemon/src/telemetry.rs rename to codex-rs/app-server-daemon/src/start_error.rs index aed8eead..987e98bc 100644 --- a/codex-rs/app-server-daemon/src/telemetry.rs +++ b/codex-rs/app-server-daemon/src/start_error.rs @@ -1,9 +1,6 @@ -//! Bounded observations for foreground callers. This module never exports telemetry; -//! in particular, the detached updater must not create a telemetry provider. +//! Typed start failures for foreground callers. Nothing here is reported anywhere. -use std::path::Path; - -/// Failure of a foreground auto-start, with the original diagnostic kept separate from the metric. +/// Failure of a foreground auto-start, with the original diagnostic kept separate from its reason. #[derive(Debug)] pub struct StartError { pub error: anyhow::Error, @@ -59,20 +56,3 @@ impl std::fmt::Display for StartFailure { } } } - -/// Suppress child reporting when the foreground TUI handoff owns the observation. -pub const HANDOFF_ENV: &str = "CODEX_DAEMON_TELEMETRY_HANDOFF"; - -/// Only presence and enabled state leave the settings reader, never values or contents. -/// Missing files mean defaults; unreadable or invalid settings remain unknown. -pub async fn settings_tags(codex_home: &Path) -> [(&'static str, &'static str); 4] { - let path = codex_home - .join(crate::STATE_DIR_NAME) - .join(crate::SETTINGS_FILE_NAME); - crate::settings::telemetry_tags(&path).await.unwrap_or([ - ("auto_update", "unknown"), - ("auto_update_setting", "unknown"), - ("update_interval_setting", "unknown"), - ("shutdown_grace_setting", "unknown"), - ]) -} diff --git a/codex-rs/app-server-daemon/src/update_loop_tests.rs b/codex-rs/app-server-daemon/src/update_loop_tests.rs index 97c82480..2d00b344 100644 --- a/codex-rs/app-server-daemon/src/update_loop_tests.rs +++ b/codex-rs/app-server-daemon/src/update_loop_tests.rs @@ -842,7 +842,7 @@ async fn readiness_waits_for_a_slow_managed_daemon() { // The process is alive but has no listening socket throughout the first deadline. let error = daemon.wait_until_ready().await.unwrap_err(); assert_eq!( - crate::telemetry::StartError::from(error).failure_reason(), + crate::start_error::StartError::from(error).failure_reason(), "readiness_timeout" ); let (ready, listener) = tokio::join!(daemon.wait_until_ready(), async { @@ -900,9 +900,9 @@ async fn daemon_start_and_restart_preserve_launch_features() { features ); let expected = if features.is_empty() { - "app-server\n--listen\nunix://\n--analytics-default-enabled\n--managed-daemon\n" + "app-server\n--listen\nunix://\n--managed-daemon\n" } else { - "app-server\n--listen\nunix://\n--analytics-default-enabled\n-c\nfeatures.api_key_model_discovery=true\n-c\nfeatures.code_mode_host=false\n--managed-daemon\n" + "app-server\n--listen\nunix://\n-c\nfeatures.api_key_model_discovery=true\n-c\nfeatures.code_mode_host=false\n--managed-daemon\n" }; assert_eq!(std::fs::read_to_string(&args_path).unwrap(), expected); let reused = daemon diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index f5ad15c2..dba09f5f 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1168,7 +1168,7 @@ ] }, "providerId": { - "description": "Opaque provider identifier supplied by the caller for analytics attribution and import history display. This does not select the migration source.", + "description": "Opaque provider identifier supplied by the caller for attribution and import history display. This does not select the migration source.", "type": [ "string", "null" @@ -1235,6 +1235,7 @@ "type": "string" }, "FeedbackSaveParams": { + "description": "Report contents for `feedback/save`. Feedback is only ever saved locally.", "properties": { "classification": { "type": "string" @@ -1287,50 +1288,6 @@ ], "type": "object" }, - "FeedbackUploadParams": { - "properties": { - "classification": { - "type": "string" - }, - "extraLogFiles": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "includeLogs": { - "type": "boolean" - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "tags": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "threadId": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "classification" - ], - "type": "object" - }, "FsCopyParams": { "description": "Copy a file or directory tree on the host filesystem.", "properties": { @@ -4853,7 +4810,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this forked thread." + "description": "Optional client-supplied source classification for this forked thread." } }, "required": [ @@ -5943,7 +5900,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this thread." + "description": "Optional client-supplied source classification for this thread." } }, "type": "object" @@ -8816,30 +8773,6 @@ "title": "Account/sendAddCreditsNudgeEmailRequest", "type": "object" }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "feedback/upload" - ], - "title": "Feedback/uploadRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/FeedbackUploadParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "Feedback/uploadRequest", - "type": "object" - }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 6750a891..a52cb4f4 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -4478,7 +4478,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", 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 b72ef37a..791b88fa 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 @@ -2455,30 +2455,6 @@ "title": "Account/sendAddCreditsNudgeEmailRequest", "type": "object" }, - { - "properties": { - "id": { - "$ref": "#/definitions/v2/RequestId" - }, - "method": { - "enum": [ - "feedback/upload" - ], - "title": "Feedback/uploadRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/v2/FeedbackUploadParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "Feedback/uploadRequest", - "type": "object" - }, { "properties": { "id": { @@ -7514,18 +7490,6 @@ ], "type": "string" }, - "AnalyticsConfig": { - "additionalProperties": true, - "properties": { - "enabled": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, "AppBranding": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -9833,16 +9797,6 @@ "Config": { "additionalProperties": true, "properties": { - "analytics": { - "anyOf": [ - { - "$ref": "#/definitions/v2/AnalyticsConfig" - }, - { - "type": "null" - } - ] - }, "approval_policy": { "anyOf": [ { @@ -12071,7 +12025,7 @@ ] }, "providerId": { - "description": "Opaque provider identifier supplied by the caller for analytics attribution and import history display. This does not select the migration source.", + "description": "Opaque provider identifier supplied by the caller for attribution and import history display. This does not select the migration source.", "type": [ "string", "null" @@ -12264,6 +12218,7 @@ }, "FeedbackSaveParams": { "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Report contents for `feedback/save`. Feedback is only ever saved locally.", "properties": { "classification": { "type": "string" @@ -12321,7 +12276,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "properties": { "promptHash": { - "description": "Same prompt hash as feedback/upload; null when prompt metadata is absent.", + "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the saved `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", "type": [ "string", "null" @@ -12341,73 +12296,6 @@ "title": "FeedbackSaveResponse", "type": "object" }, - "FeedbackUploadParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "classification": { - "type": "string" - }, - "extraLogFiles": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "includeLogs": { - "type": "boolean" - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "tags": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "threadId": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "classification" - ], - "title": "FeedbackUploadParams", - "type": "object" - }, - "FeedbackUploadResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "promptHash": { - "default": null, - "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the uploaded `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", - "type": [ - "string", - "null" - ] - }, - "threadId": { - "type": "string" - } - }, - "required": [ - "threadId" - ], - "title": "FeedbackUploadResponse", - "type": "object" - }, "FileChangeOutputDeltaNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Deprecated legacy notification for `apply_patch` textual output.\n\nThe server no longer emits this notification.", @@ -17117,136 +17005,8 @@ ], "title": "Nullable_GetAccountTokenUsageParams" }, - "OtelExporter": { - "oneOf": [ - { - "enum": [ - "none", - "statsig" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "otlp-http": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "protocol": { - "$ref": "#/definitions/v2/OtelHttpProtocol" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/v2/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers", - "protocol" - ], - "type": "object" - } - }, - "required": [ - "otlp-http" - ], - "title": "OtlpHttpOtelExporter", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "otlp-grpc": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/v2/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers" - ], - "type": "object" - } - }, - "required": [ - "otlp-grpc" - ], - "title": "OtlpGrpcOtelExporter", - "type": "object" - } - ] - }, - "OtelHttpProtocol": { - "enum": [ - "binary", - "json" - ], - "type": "string" - }, "OtelRequirements": { "properties": { - "environment": { - "type": [ - "string", - "null" - ] - }, - "exporter": { - "anyOf": [ - { - "$ref": "#/definitions/v2/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "log_agent_responses": { - "type": [ - "boolean", - "null" - ] - }, - "log_guardian_assessments": { - "type": [ - "boolean", - "null" - ] - }, "log_sse_deltas": { "type": [ "boolean", @@ -17259,25 +17019,6 @@ "null" ] }, - "metrics_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/v2/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "span_attributes": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, "tool_result": { "anyOf": [ { @@ -17287,51 +17028,6 @@ "type": "null" } ] - }, - "trace_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/v2/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "tracestate": { - "additionalProperties": { - "additionalProperties": { - "type": "string" - }, - "type": "object" - }, - "type": [ - "object", - "null" - ] - } - }, - "type": "object" - }, - "OtelTlsConfig": { - "properties": { - "ca-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-private-key": { - "type": [ - "string", - "null" - ] } }, "type": "object" @@ -22582,7 +22278,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", @@ -23141,7 +22837,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this forked thread." + "description": "Optional client-supplied source classification for this forked thread." } }, "required": [ @@ -26518,7 +26214,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this thread." + "description": "Optional client-supplied source classification for this thread." } }, "title": "ThreadStartParams", 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 25170e10..88795232 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 @@ -629,18 +629,6 @@ ], "type": "string" }, - "AnalyticsConfig": { - "additionalProperties": true, - "properties": { - "enabled": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, "AppBranding": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -4293,30 +4281,6 @@ "title": "Account/sendAddCreditsNudgeEmailRequest", "type": "object" }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "feedback/upload" - ], - "title": "Feedback/uploadRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/FeedbackUploadParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "Feedback/uploadRequest", - "type": "object" - }, { "properties": { "id": { @@ -5614,16 +5578,6 @@ "Config": { "additionalProperties": true, "properties": { - "analytics": { - "anyOf": [ - { - "$ref": "#/definitions/AnalyticsConfig" - }, - { - "type": "null" - } - ] - }, "approval_policy": { "anyOf": [ { @@ -7852,7 +7806,7 @@ ] }, "providerId": { - "description": "Opaque provider identifier supplied by the caller for analytics attribution and import history display. This does not select the migration source.", + "description": "Opaque provider identifier supplied by the caller for attribution and import history display. This does not select the migration source.", "type": [ "string", "null" @@ -8045,6 +7999,7 @@ }, "FeedbackSaveParams": { "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Report contents for `feedback/save`. Feedback is only ever saved locally.", "properties": { "classification": { "type": "string" @@ -8102,7 +8057,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "properties": { "promptHash": { - "description": "Same prompt hash as feedback/upload; null when prompt metadata is absent.", + "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the saved `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", "type": [ "string", "null" @@ -8122,73 +8077,6 @@ "title": "FeedbackSaveResponse", "type": "object" }, - "FeedbackUploadParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "classification": { - "type": "string" - }, - "extraLogFiles": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "includeLogs": { - "type": "boolean" - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "tags": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "threadId": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "classification" - ], - "title": "FeedbackUploadParams", - "type": "object" - }, - "FeedbackUploadResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "promptHash": { - "default": null, - "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the uploaded `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", - "type": [ - "string", - "null" - ] - }, - "threadId": { - "type": "string" - } - }, - "required": [ - "threadId" - ], - "title": "FeedbackUploadResponse", - "type": "object" - }, "FileChangeOutputDeltaNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Deprecated legacy notification for `apply_patch` textual output.\n\nThe server no longer emits this notification.", @@ -13078,136 +12966,8 @@ ], "title": "Nullable_GetAccountTokenUsageParams" }, - "OtelExporter": { - "oneOf": [ - { - "enum": [ - "none", - "statsig" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "otlp-http": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "protocol": { - "$ref": "#/definitions/OtelHttpProtocol" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers", - "protocol" - ], - "type": "object" - } - }, - "required": [ - "otlp-http" - ], - "title": "OtlpHttpOtelExporter", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "otlp-grpc": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers" - ], - "type": "object" - } - }, - "required": [ - "otlp-grpc" - ], - "title": "OtlpGrpcOtelExporter", - "type": "object" - } - ] - }, - "OtelHttpProtocol": { - "enum": [ - "binary", - "json" - ], - "type": "string" - }, "OtelRequirements": { "properties": { - "environment": { - "type": [ - "string", - "null" - ] - }, - "exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "log_agent_responses": { - "type": [ - "boolean", - "null" - ] - }, - "log_guardian_assessments": { - "type": [ - "boolean", - "null" - ] - }, "log_sse_deltas": { "type": [ "boolean", @@ -13220,25 +12980,6 @@ "null" ] }, - "metrics_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "span_attributes": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, "tool_result": { "anyOf": [ { @@ -13248,51 +12989,6 @@ "type": "null" } ] - }, - "trace_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "tracestate": { - "additionalProperties": { - "additionalProperties": { - "type": "string" - }, - "type": "object" - }, - "type": [ - "object", - "null" - ] - } - }, - "type": "object" - }, - "OtelTlsConfig": { - "properties": { - "ca-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-private-key": { - "type": [ - "string", - "null" - ] } }, "type": "object" @@ -20285,7 +19981,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", @@ -20844,7 +20540,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this forked thread." + "description": "Optional client-supplied source classification for this forked thread." } }, "required": [ @@ -24221,7 +23917,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this thread." + "description": "Optional client-supplied source classification for this thread." } }, "title": "ThreadStartParams", 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 4fd6ad20..cb177235 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -12,18 +12,6 @@ ], "type": "string" }, - "AnalyticsConfig": { - "additionalProperties": true, - "properties": { - "enabled": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, "AppConfig": { "properties": { "approvals_reviewer": { @@ -470,16 +458,6 @@ "Config": { "additionalProperties": true, "properties": { - "analytics": { - "anyOf": [ - { - "$ref": "#/definitions/AnalyticsConfig" - }, - { - "type": "null" - } - ] - }, "approval_policy": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 5f9311e3..5d83499c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -1148,136 +1148,8 @@ }, "type": "object" }, - "OtelExporter": { - "oneOf": [ - { - "enum": [ - "none", - "statsig" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "otlp-http": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "protocol": { - "$ref": "#/definitions/OtelHttpProtocol" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers", - "protocol" - ], - "type": "object" - } - }, - "required": [ - "otlp-http" - ], - "title": "OtlpHttpOtelExporter", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "otlp-grpc": { - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "description": "Header names are retained; values are redacted by the server.", - "type": "object" - }, - "tls": { - "anyOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "endpoint", - "headers" - ], - "type": "object" - } - }, - "required": [ - "otlp-grpc" - ], - "title": "OtlpGrpcOtelExporter", - "type": "object" - } - ] - }, - "OtelHttpProtocol": { - "enum": [ - "binary", - "json" - ], - "type": "string" - }, "OtelRequirements": { "properties": { - "environment": { - "type": [ - "string", - "null" - ] - }, - "exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "log_agent_responses": { - "type": [ - "boolean", - "null" - ] - }, - "log_guardian_assessments": { - "type": [ - "boolean", - "null" - ] - }, "log_sse_deltas": { "type": [ "boolean", @@ -1290,25 +1162,6 @@ "null" ] }, - "metrics_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "span_attributes": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, "tool_result": { "anyOf": [ { @@ -1318,51 +1171,6 @@ "type": "null" } ] - }, - "trace_exporter": { - "anyOf": [ - { - "$ref": "#/definitions/OtelExporter" - }, - { - "type": "null" - } - ] - }, - "tracestate": { - "additionalProperties": { - "additionalProperties": { - "type": "string" - }, - "type": "object" - }, - "type": [ - "object", - "null" - ] - } - }, - "type": "object" - }, - "OtelTlsConfig": { - "properties": { - "ca-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-certificate": { - "type": [ - "string", - "null" - ] - }, - "client-private-key": { - "type": [ - "string", - "null" - ] } }, "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ExternalAgentConfigImportParams.json b/codex-rs/app-server-protocol/schema/json/v2/ExternalAgentConfigImportParams.json index 41c0d421..f6f20c46 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ExternalAgentConfigImportParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ExternalAgentConfigImportParams.json @@ -218,7 +218,7 @@ ] }, "providerId": { - "description": "Opaque provider identifier supplied by the caller for analytics attribution and import history display. This does not select the migration source.", + "description": "Opaque provider identifier supplied by the caller for attribution and import history display. This does not select the migration source.", "type": [ "string", "null" diff --git a/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveParams.json b/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveParams.json index 62132f7b..fc817a2e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveParams.json @@ -5,6 +5,7 @@ "type": "string" } }, + "description": "Report contents for `feedback/save`. Feedback is only ever saved locally.", "properties": { "classification": { "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveResponse.json index 29c8c44a..791b22cd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FeedbackSaveResponse.json @@ -7,7 +7,7 @@ }, "properties": { "promptHash": { - "description": "Same prompt hash as feedback/upload; null when prompt metadata is absent.", + "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the saved `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", "type": [ "string", "null" diff --git a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json b/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json deleted file mode 100644 index 3bf0c621..00000000 --- a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "classification": { - "type": "string" - }, - "extraLogFiles": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "includeLogs": { - "type": "boolean" - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "tags": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "threadId": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "classification" - ], - "title": "FeedbackUploadParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadResponse.json deleted file mode 100644 index 06af2678..00000000 --- a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadResponse.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "promptHash": { - "default": null, - "description": "Whitespace-normalized SHA-256 of the session base instructions, matching the uploaded `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", - "type": [ - "string", - "null" - ] - }, - "threadId": { - "type": "string" - } - }, - "required": [ - "threadId" - ], - "title": "FeedbackUploadResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json index 6908b54c..42ae3912 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -178,7 +178,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this forked thread." + "description": "Optional client-supplied source classification for this forked thread." } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 68829f93..4b933570 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -1591,7 +1591,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index ad46c3e8..c1e491c1 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index c23c6c34..b2aae31a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index c3e0785f..46bbd4b4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 6e653afc..8db75fdc 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -1643,7 +1643,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRevertResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRevertResponse.json index e3772a19..b005aa35 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRevertResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRevertResponse.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 5164caf6..61403bbd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -418,7 +418,7 @@ "type": "null" } ], - "description": "Optional client-supplied analytics source classification for this thread." + "description": "Optional client-supplied source classification for this thread." } }, "title": "ThreadStartParams", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 7d24279f..1d544547 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -1591,7 +1591,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 5de7051c..4e7fe40a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index a960ccf2..c738c0f0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -1382,7 +1382,7 @@ "type": "null" } ], - "description": "Optional analytics source classification for this thread." + "description": "Optional source classification for this thread." }, "turns": { "description": "Only populated on `thread/resume`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst index 80818ead..58656415 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst index cf46d378..04f53d37 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index de12ebd4..a3caa6b0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -25,7 +25,6 @@ import type { ExternalAgentConfigDetectParams } from "./v2/ExternalAgentConfigDe import type { ExternalAgentConfigImportHistoryRecordParams } from "./v2/ExternalAgentConfigImportHistoryRecordParams"; import type { ExternalAgentConfigImportParams } from "./v2/ExternalAgentConfigImportParams"; import type { FeedbackSaveParams } from "./v2/FeedbackSaveParams"; -import type { FeedbackUploadParams } from "./v2/FeedbackUploadParams"; import type { FsCopyParams } from "./v2/FsCopyParams"; import type { FsCreateDirectoryParams } from "./v2/FsCreateDirectoryParams"; import type { FsGetMetadataParams } from "./v2/FsGetMetadataParams"; @@ -110,4 +109,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/delete", id: RequestId, params: ThreadDeleteParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/attachment/add", id: RequestId, params: ThreadAttachmentAddParams, } | { "method": "thread/attachment/list", id: RequestId, params: ThreadAttachmentListParams, } | { "method": "thread/attachmentOwner/list", id: RequestId, params: ThreadAttachmentOwnerListParams, } | { "method": "thread/attachment/remove", id: RequestId, params: ThreadAttachmentRemoveParams, } | { "method": "thread/section/move", id: RequestId, params: ThreadSectionMoveParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/revert", id: RequestId, params: ThreadRevertParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "threadSection/list", id: RequestId, params: ThreadSectionListParams, } | { "method": "threadSection/create", id: RequestId, params: ThreadSectionCreateParams, } | { "method": "threadSection/update", id: RequestId, params: ThreadSectionUpdateParams, } | { "method": "threadSection/delete", id: RequestId, params: ThreadSectionDeleteParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/turns/list", id: RequestId, params: ThreadTurnsListParams, } | { "method": "thread/items/list", id: RequestId, params: ThreadItemsListParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/extraRoots/set", id: RequestId, params: SkillsExtraRootsSetParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/reconcile", id: RequestId, params: PluginReconcileParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/read", id: RequestId, params: AppsReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "app/installed", id: RequestId, params: AppsInstalledParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "account/gatewayOAuth/read", id: RequestId, params?: GatewayOAuthReadParams | null | undefined, } | { "method": "account/gatewayOAuth/login", id: RequestId, params?: GatewayOAuthLoginParams | null | undefined, } | { "method": "account/gatewayOAuth/cancel", id: RequestId, params: undefined, } | { "method": "modelProvider/list", id: RequestId, params: ModelProviderListParams, } | { "method": "modelProvider/config/write", id: RequestId, params: ModelProviderConfigWriteParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/securitySetup/read", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params?: GetAccountRateLimitsParams | undefined, } | { "method": "account/rateLimitResetCredit/consume", id: RequestId, params: ConsumeAccountRateLimitResetCreditParams, } | { "method": "account/usage/read", id: RequestId, params?: GetAccountTokenUsageParams | undefined, } | { "method": "account/workspaceMessages/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "feedback/save", id: RequestId, params: FeedbackSaveParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "externalAgentConfig/import/recordHistory", id: RequestId, params: ExternalAgentConfigImportHistoryRecordParams, } | { "method": "externalAgentConfig/import/readHistories", id: RequestId, params: undefined, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/delete", id: RequestId, params: ThreadDeleteParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/attachment/add", id: RequestId, params: ThreadAttachmentAddParams, } | { "method": "thread/attachment/list", id: RequestId, params: ThreadAttachmentListParams, } | { "method": "thread/attachmentOwner/list", id: RequestId, params: ThreadAttachmentOwnerListParams, } | { "method": "thread/attachment/remove", id: RequestId, params: ThreadAttachmentRemoveParams, } | { "method": "thread/section/move", id: RequestId, params: ThreadSectionMoveParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/revert", id: RequestId, params: ThreadRevertParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "threadSection/list", id: RequestId, params: ThreadSectionListParams, } | { "method": "threadSection/create", id: RequestId, params: ThreadSectionCreateParams, } | { "method": "threadSection/update", id: RequestId, params: ThreadSectionUpdateParams, } | { "method": "threadSection/delete", id: RequestId, params: ThreadSectionDeleteParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/turns/list", id: RequestId, params: ThreadTurnsListParams, } | { "method": "thread/items/list", id: RequestId, params: ThreadItemsListParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/extraRoots/set", id: RequestId, params: SkillsExtraRootsSetParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/reconcile", id: RequestId, params: PluginReconcileParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/read", id: RequestId, params: AppsReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "app/installed", id: RequestId, params: AppsInstalledParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "account/gatewayOAuth/read", id: RequestId, params?: GatewayOAuthReadParams | null | undefined, } | { "method": "account/gatewayOAuth/login", id: RequestId, params?: GatewayOAuthLoginParams | null | undefined, } | { "method": "account/gatewayOAuth/cancel", id: RequestId, params: undefined, } | { "method": "modelProvider/list", id: RequestId, params: ModelProviderListParams, } | { "method": "modelProvider/config/write", id: RequestId, params: ModelProviderConfigWriteParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/securitySetup/read", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params?: GetAccountRateLimitsParams | undefined, } | { "method": "account/rateLimitResetCredit/consume", id: RequestId, params: ConsumeAccountRateLimitResetCreditParams, } | { "method": "account/usage/read", id: RequestId, params?: GetAccountTokenUsageParams | undefined, } | { "method": "account/workspaceMessages/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/save", id: RequestId, params: FeedbackSaveParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "externalAgentConfig/import/recordHistory", id: RequestId, params: ExternalAgentConfigImportHistoryRecordParams, } | { "method": "externalAgentConfig/import/readHistories", id: RequestId, params: undefined, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AnalyticsConfig.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AnalyticsConfig.ts deleted file mode 100644 index d095439a..00000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AnalyticsConfig.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { JsonValue } from "../serde_json/JsonValue"; - -export type AnalyticsConfig = { enabled: boolean | null, } & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts index e80beb8e..4192e842 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts @@ -9,7 +9,6 @@ import type { Verbosity } from "../Verbosity"; import type { WebSearchMode } from "../WebSearchMode"; import type { WebSearchProvider } from "../WebSearchProvider"; import type { JsonValue } from "../serde_json/JsonValue"; -import type { AnalyticsConfig } from "./AnalyticsConfig"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; import type { BrowserUseConfig } from "./BrowserUseConfig"; @@ -26,4 +25,4 @@ export type Config = {model: string | null, review_model: string | null, model_c approvals_reviewer: ApprovalsReviewer | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: ForcedChatgptWorkspaceIds | null, forced_login_method: ForcedLoginMethod | null, web_search: WebSearchMode | null, /** * Effective tools.client_search_provider hint. Model-selected providers take precedence. */ -client_search_provider: WebSearchProvider | null, tools: ToolsV2 | null, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, service_tier: string | null, analytics: AnalyticsConfig | null, browser_use: BrowserUseConfig | null, computer_use: ComputerUseConfig | null, desktop: { [key in string]?: JsonValue } | null} & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); +client_search_provider: WebSearchProvider | null, tools: ToolsV2 | null, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, service_tier: string | null, browser_use: BrowserUseConfig | null, computer_use: ComputerUseConfig | null, desktop: { [key in string]?: JsonValue } | null} & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ExternalAgentConfigImportParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ExternalAgentConfigImportParams.ts index ebe23a72..59f2a4a3 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ExternalAgentConfigImportParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ExternalAgentConfigImportParams.ts @@ -9,7 +9,7 @@ export type ExternalAgentConfigImportParams = { migrationItems: Array | null, tags?: { [key in string]?: string } | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadResponse.ts deleted file mode 100644 index d4f03973..00000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -// 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 FeedbackUploadResponse = { threadId: string, -/** - * Whitespace-normalized SHA-256 of the session base instructions, matching the - * uploaded `prompt_hash` tag. Does not include later developer messages. - * Null when the reported rollout has no prompt metadata. - */ -promptHash: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/OtelExporter.ts b/codex-rs/app-server-protocol/schema/typescript/v2/OtelExporter.ts deleted file mode 100644 index f18fa658..00000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/OtelExporter.ts +++ /dev/null @@ -1,15 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { OtelHttpProtocol } from "./OtelHttpProtocol"; -import type { OtelTlsConfig } from "./OtelTlsConfig"; - -export type OtelExporter = "none" | "statsig" | { "otlp-http": { endpoint: string, -/** - * Header names are retained; values are redacted by the server. - */ -headers: { [key in string]?: string }, protocol: OtelHttpProtocol, tls: OtelTlsConfig | null, } } | { "otlp-grpc": { endpoint: string, -/** - * Header names are retained; values are redacted by the server. - */ -headers: { [key in string]?: string }, tls: OtelTlsConfig | null, } }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/OtelHttpProtocol.ts b/codex-rs/app-server-protocol/schema/typescript/v2/OtelHttpProtocol.ts deleted file mode 100644 index dc24d2e2..00000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/OtelHttpProtocol.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 OtelHttpProtocol = "binary" | "json"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/OtelRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/OtelRequirements.ts index 588d9993..b444fa01 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/OtelRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/OtelRequirements.ts @@ -1,7 +1,6 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { OtelExporter } from "./OtelExporter"; import type { OtelToolResultLogConfig } from "./OtelToolResultLogConfig"; -export type OtelRequirements = { tool_result: OtelToolResultLogConfig | null, log_sse_deltas: boolean | null, log_user_prompt: boolean | null, log_agent_responses: boolean | null, log_guardian_assessments: boolean | null, environment: string | null, exporter: OtelExporter | null, trace_exporter: OtelExporter | null, metrics_exporter: OtelExporter | null, span_attributes: { [key in string]?: string } | null, tracestate: { [key in string]?: { [key in string]?: string } } | null, }; +export type OtelRequirements = { tool_result: OtelToolResultLogConfig | null, log_sse_deltas: boolean | null, log_user_prompt: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/OtelTlsConfig.ts b/codex-rs/app-server-protocol/schema/typescript/v2/OtelTlsConfig.ts deleted file mode 100644 index db35d2cc..00000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/OtelTlsConfig.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 OtelTlsConfig = { "ca-certificate": string | null, "client-certificate": string | null, "client-private-key": string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts index 9a0f865d..2dc7c8e0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts @@ -81,7 +81,7 @@ originator: string | null, /** * Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.). */ source: SessionSource, /** - * Optional analytics source classification for this thread. + * Optional source classification for this thread. */ threadSource: ThreadSource | null, /** * Optional random unique nickname assigned to an AgentControl-spawned sub-agent. diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts index 88ff6936..42c27ad4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -31,7 +31,7 @@ model?: string | null, modelProvider?: string | null, serviceTier?: string | nul * and subsequent turns. */ approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** - * Optional client-supplied analytics source classification for this forked thread. + * Optional client-supplied source classification for this forked thread. */ threadSource?: ThreadSource | null, /** * When true, return only thread metadata and live fork state without diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts index 69280c0b..fb54d98a 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts @@ -17,6 +17,6 @@ approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, conf * @deprecated `friendly` and `pragmatic` no longer select a style. */ personality?: Personality | null, ephemeral?: boolean | null, sessionStartSource?: ThreadStartSource | null, /** - * Optional client-supplied analytics source classification for this thread. + * Optional client-supplied source classification for this thread. */ threadSource?: ThreadSource | null}; 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 53c270e7..22f51d22 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -25,7 +25,6 @@ export type { AgentMessageDeltaNotification } from "./AgentMessageDeltaNotificat export type { AgentMessageDisplay } from "./AgentMessageDisplay"; export type { AgentMessageModeration } from "./AgentMessageModeration"; export type { AllowDenyRequirement } from "./AllowDenyRequirement"; -export type { AnalyticsConfig } from "./AnalyticsConfig"; export type { AppBranding } from "./AppBranding"; export type { AppInfo } from "./AppInfo"; export type { AppLinksConfig } from "./AppLinksConfig"; @@ -176,8 +175,6 @@ export type { ExternalAgentImportedConnectorSource } from "./ExternalAgentImport export type { FeedbackRequirements } from "./FeedbackRequirements"; export type { FeedbackSaveParams } from "./FeedbackSaveParams"; export type { FeedbackSaveResponse } from "./FeedbackSaveResponse"; -export type { FeedbackUploadParams } from "./FeedbackUploadParams"; -export type { FeedbackUploadResponse } from "./FeedbackUploadResponse"; export type { FileChangeApprovalDecision } from "./FileChangeApprovalDecision"; export type { FileChangeOutputDeltaNotification } from "./FileChangeOutputDeltaNotification"; export type { FileChangePatchUpdatedNotification } from "./FileChangePatchUpdatedNotification"; @@ -367,10 +364,7 @@ export type { NetworkRequirements } from "./NetworkRequirements"; export type { NetworkUnixSocketPermission } from "./NetworkUnixSocketPermission"; export type { NewThreadModelDefaults } from "./NewThreadModelDefaults"; export type { NonSteerableTurnKind } from "./NonSteerableTurnKind"; -export type { OtelExporter } from "./OtelExporter"; -export type { OtelHttpProtocol } from "./OtelHttpProtocol"; export type { OtelRequirements } from "./OtelRequirements"; -export type { OtelTlsConfig } from "./OtelTlsConfig"; export type { OtelToolResultLogConfig } from "./OtelToolResultLogConfig"; export type { OverriddenMetadata } from "./OverriddenMetadata"; export type { PatchApplyStatus } from "./PatchApplyStatus"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index d61e1b3c..fa91d852 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -1457,12 +1457,6 @@ client_request_definitions! { response: v2::SendAddCreditsNudgeEmailResponse, }, - FeedbackUpload => "feedback/upload" { - params: v2::FeedbackUploadParams, - serialization: None, - response: v2::FeedbackUploadResponse, - }, - FeedbackSave => "feedback/save" { params: v2::FeedbackSaveParams, serialization: None, 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 2158fa23..ecdabbdc 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -163,15 +163,6 @@ pub struct ToolsV2 { pub web_search: Option, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "snake_case")] -#[ts(export_to = "v2/")] -pub struct AnalyticsConfig { - pub enabled: Option, - #[serde(default, flatten)] - pub additional: HashMap, -} - #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] #[ts(export_to = "v2/")] @@ -307,7 +298,6 @@ pub struct Config { pub model_reasoning_summary: Option, pub model_verbosity: Option, pub service_tier: Option, - pub analytics: Option, #[experimental("config/read.apps")] #[serde(default)] pub apps: Option, @@ -510,14 +500,6 @@ pub struct OtelRequirements { pub tool_result: Option, pub log_sse_deltas: Option, pub log_user_prompt: Option, - pub log_agent_responses: Option, - pub log_guardian_assessments: Option, - pub environment: Option, - pub exporter: Option, - pub trace_exporter: Option, - pub metrics_exporter: Option, - pub span_attributes: Option>, - pub tracestate: Option>>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] @@ -527,48 +509,6 @@ pub struct OtelToolResultLogConfig { pub max_bytes: usize, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(rename_all = "kebab-case")] -#[ts(export_to = "v2/", rename_all = "kebab-case")] -pub enum OtelExporter { - None, - Statsig, - OtlpHttp { - endpoint: String, - /// Header names are retained; values are redacted by the server. - #[schemars(with = "HashMap")] - #[ts(as = "HashMap")] - headers: HashMap, - protocol: OtelHttpProtocol, - tls: Option, - }, - OtlpGrpc { - endpoint: String, - /// Header names are retained; values are redacted by the server. - #[schemars(with = "HashMap")] - #[ts(as = "HashMap")] - headers: HashMap, - tls: Option, - }, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(rename_all = "kebab-case")] -#[ts(export_to = "v2/", rename_all = "kebab-case")] -pub enum OtelHttpProtocol { - Binary, - Json, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(rename_all = "kebab-case")] -#[ts(export_to = "v2/", rename_all = "kebab-case")] -pub struct OtelTlsConfig { - pub ca_certificate: Option, - pub client_certificate: Option, - pub client_private_key: Option, -} - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -1013,7 +953,7 @@ pub struct ExternalAgentConfigImportParams { /// Optional identifier for the product that initiated the import. #[ts(optional = nullable)] pub source: Option, - /// Opaque provider identifier supplied by the caller for analytics attribution and import + /// Opaque provider identifier supplied by the caller for attribution and import /// history display. This does not select the migration source. #[ts(optional = nullable)] pub provider_id: Option, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/feedback.rs b/codex-rs/app-server-protocol/src/protocol/v2/feedback.rs index f617d333..30d88c5c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/feedback.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/feedback.rs @@ -9,7 +9,8 @@ use std::path::PathBuf; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] -pub struct FeedbackUploadParams { +/// Report contents for `feedback/save`. Feedback is only ever saved locally. +pub struct FeedbackReportParams { pub classification: String, #[ts(optional = nullable)] pub reason: Option, @@ -23,24 +24,12 @@ pub struct FeedbackUploadParams { pub tags: Option>, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub struct FeedbackUploadResponse { - pub thread_id: String, - /// Whitespace-normalized SHA-256 of the session base instructions, matching the - /// uploaded `prompt_hash` tag. Does not include later developer messages. - /// Null when the reported rollout has no prompt metadata. - #[serde(default)] - pub prompt_hash: Option, -} - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct FeedbackSaveParams { #[serde(flatten)] - pub feedback: FeedbackUploadParams, + pub feedback: FeedbackReportParams, /// Absolute, previously unused ZIP path on the app-server host. /// The caller owns this file, including after a disconnected RPC. pub save_path: LegacyAppPathString, @@ -52,6 +41,8 @@ pub struct FeedbackSaveParams { pub struct FeedbackSaveResponse { pub saved_path: LegacyAppPathString, pub thread_id: String, - /// Same prompt hash as feedback/upload; null when prompt metadata is absent. + /// Whitespace-normalized SHA-256 of the session base instructions, matching the + /// saved `prompt_hash` tag. Does not include later developer messages. + /// Null when the reported rollout has no prompt metadata. pub prompt_hash: Option, } 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 d6ea06fc..291f79f9 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -2142,7 +2142,6 @@ fn config_granular_approval_policy_is_marked_experimental() { model_reasoning_summary: None, model_verbosity: None, service_tier: None, - analytics: None, apps: None, browser_use: None, computer_use: None, @@ -2178,7 +2177,6 @@ fn config_approvals_reviewer_is_marked_experimental() { model_reasoning_summary: None, model_verbosity: None, service_tier: None, - analytics: None, apps: None, browser_use: None, computer_use: None, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs index 8c7e5f56..af924282 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -119,7 +119,7 @@ pub struct ThreadStartParams { pub history_mode: Option, #[ts(optional = nullable)] pub session_start_source: Option, - /// Optional client-supplied analytics source classification for this thread. + /// Optional client-supplied source classification for this thread. #[ts(optional = nullable)] pub thread_source: Option, /// Optional project identity for this new thread. Durable threads persist @@ -629,7 +629,7 @@ pub struct ThreadForkParams { #[experimental("thread/fork.attachToSource")] #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub attach_to_source: bool, - /// Optional client-supplied analytics source classification for this forked thread. + /// Optional client-supplied source classification for this forked thread. #[ts(optional = nullable)] pub thread_source: Option, /// When true, return only thread metadata and live fork state without diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs index dd7c0d85..90613d37 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs @@ -274,7 +274,7 @@ pub struct Thread { /// `None` means the capability is unavailable, such as for an unloaded stored thread. #[experimental("thread.canAcceptDirectInput")] pub can_accept_direct_input: Option, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub thread_source: Option, /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. pub agent_nickname: Option, diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index 6c6cbc24..bb4c1069 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -68,19 +68,12 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; -use codex_core::config::Config; -use codex_otel::OtelProvider; -use codex_otel::current_span_w3c_trace_context; use codex_protocol::dynamic_tools::normalize_dynamic_tool_specs; use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::W3cTraceContext; -use codex_utils_cli::CliConfigOverrides; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; use tracing::info_span; -use tracing_subscriber::layer::SubscriberExt; -use tracing_subscriber::util::SubscriberInitExt; use tungstenite::Message; use tungstenite::WebSocket; use tungstenite::connect; @@ -88,10 +81,6 @@ use tungstenite::stream::MaybeTlsStream; use url::Url; use uuid::Uuid; -mod loopback_responses_server; -mod plugin_analytics_capture; -mod plugin_analytics_mutation_smoke; -mod plugin_analytics_smoke; mod request_user_input; const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[ @@ -105,10 +94,6 @@ const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[ ]; const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); const APP_SERVER_GRACEFUL_SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100); -const DEFAULT_ANALYTICS_ENABLED: bool = true; -const OTEL_SERVICE_NAME: &str = "codex-app-server-test-client"; -const TRACE_DISABLED_MESSAGE: &str = - "Not enabled - enable tracing in $CODEX_HOME/config.toml to get a trace URL!"; /// Minimal launcher that initializes the Codex app-server and logs the handshake. #[derive(Parser)] @@ -278,39 +263,6 @@ enum CliCommand { #[arg(long, default_value_t = 15)] hold_seconds: u64, }, - /// Exercise remote plugin analytics through production app-server RPC paths. - #[command(name = "plugin-analytics-smoke")] - PluginAnalyticsSmoke { - /// Installed local plugin id, such as `linear@openai-curated-remote`. - #[arg(long)] - plugin_id: String, - /// JSONL output path. Defaults to a PID-specific file under the system temp directory. - #[arg(long)] - capture_file: Option, - }, - /// Install and uninstall one remote plugin while validating analytics capture. - #[command(name = "plugin-analytics-mutation-smoke")] - PluginAnalyticsMutationSmoke { - /// Backend remote plugin id. The plugin must be initially uninstalled. - #[arg(long)] - remote_plugin_id: String, - /// Acknowledge that this command mutates the active account's plugin state. - #[arg(long)] - confirm_account_mutation: bool, - /// JSONL output path. Defaults to a PID-specific file under the system temp directory. - #[arg(long)] - capture_file: Option, - }, - /// Best-effort recovery command that uninstalls one remote plugin. - #[command(name = "plugin-remote-uninstall")] - PluginRemoteUninstall { - /// Backend remote plugin id to uninstall. - #[arg(long)] - remote_plugin_id: String, - /// Acknowledge that this command mutates the active account's plugin state. - #[arg(long)] - confirm_account_mutation: bool, - }, } enum TestLoginMode { @@ -471,58 +423,6 @@ pub async fn run() -> Result<()> { hold_seconds, ) } - CliCommand::PluginAnalyticsSmoke { - plugin_id, - capture_file, - } => { - ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-smoke")?; - if url.is_some() { - bail!("plugin-analytics-smoke requires --codex-bin and does not support --url"); - } - let codex_bin = codex_bin.context("plugin-analytics-smoke requires --codex-bin")?; - plugin_analytics_smoke::run(&codex_bin, &config_overrides, &plugin_id, capture_file) - } - CliCommand::PluginAnalyticsMutationSmoke { - remote_plugin_id, - confirm_account_mutation, - capture_file, - } => { - ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-mutation-smoke")?; - if url.is_some() { - bail!( - "plugin-analytics-mutation-smoke requires --codex-bin and does not support --url" - ); - } - let codex_bin = - codex_bin.context("plugin-analytics-mutation-smoke requires --codex-bin")?; - plugin_analytics_mutation_smoke::run( - &codex_bin, - &config_overrides, - &remote_plugin_id, - plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag( - confirm_account_mutation, - ), - capture_file, - ) - } - CliCommand::PluginRemoteUninstall { - remote_plugin_id, - confirm_account_mutation, - } => { - ensure_dynamic_tools_unused(&dynamic_tools, "plugin-remote-uninstall")?; - if url.is_some() { - bail!("plugin-remote-uninstall requires --codex-bin and does not support --url"); - } - let codex_bin = codex_bin.context("plugin-remote-uninstall requires --codex-bin")?; - plugin_analytics_mutation_smoke::run_cleanup( - &codex_bin, - &config_overrides, - &remote_plugin_id, - plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag( - confirm_account_mutation, - ), - ) - } } } @@ -1199,20 +1099,16 @@ async fn with_client( config_overrides: &[String], f: impl FnOnce(&mut CodexClient) -> Result, ) -> Result { - let tracing = TestClientTracing::initialize(config_overrides).await?; let command_span = info_span!( "app_server_test_client.command", otel.kind = "client", otel.name = command_name, app_server_test_client.command = command_name, ); - let trace_summary = command_span.in_scope(|| TraceSummary::capture(tracing.traces_enabled)); - let result = command_span.in_scope(|| { + command_span.in_scope(|| { let mut client = CodexClient::connect(endpoint, config_overrides)?; f(&mut client) - }); - print_trace_summary(&trace_summary); - result + }) } fn thread_increment_elicitation(url: &str, thread_id: String) -> Result<()> { @@ -1917,7 +1813,7 @@ impl CodexClient { let request_value = serde_json::to_value(request)?; let mut request: JSONRPCRequest = serde_json::from_value(request_value) .context("client request was not a valid JSON-RPC request")?; - request.trace = current_span_w3c_trace_context(); + request.trace = codex_otel::current_span_w3c_trace_context(); let request_json = serde_json::to_string(&request)?; let mut request_for_logging = serde_json::to_value(&request)?; if request.method == "account/login/start" @@ -2205,85 +2101,6 @@ fn print_multiline_with_prefix(prefix: &str, payload: &str) { } } -struct TestClientTracing { - _otel_provider: Option, - traces_enabled: bool, -} - -impl TestClientTracing { - async fn initialize(config_overrides: &[String]) -> Result { - let cli_kv_overrides = CliConfigOverrides { - raw_overrides: config_overrides.to_vec(), - } - .parse_overrides() - .map_err(|e| anyhow::anyhow!("error parsing -c overrides: {e}"))?; - let config = Config::load_with_cli_overrides(cli_kv_overrides) - .await - .context("error loading config")?; - let otel_provider = codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - Some(OTEL_SERVICE_NAME), - DEFAULT_ANALYTICS_ENABLED, - ) - .map_err(|e| anyhow::anyhow!("error loading otel config: {e}"))?; - let traces_enabled = otel_provider - .as_ref() - .and_then(|provider| provider.tracer_provider.as_ref()) - .is_some(); - if let Some(provider) = otel_provider.as_ref() - && traces_enabled - { - let _ = tracing_subscriber::registry() - .with(provider.tracing_layer()) - .try_init(); - } - Ok(Self { - traces_enabled, - _otel_provider: otel_provider, - }) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -enum TraceSummary { - Enabled { url: String }, - Disabled, -} - -impl TraceSummary { - fn capture(traces_enabled: bool) -> Self { - if !traces_enabled { - return Self::Disabled; - } - current_span_w3c_trace_context() - .as_ref() - .and_then(trace_url_from_context) - .map_or(Self::Disabled, |url| Self::Enabled { url }) - } -} - -fn trace_url_from_context(trace: &W3cTraceContext) -> Option { - let traceparent = trace.traceparent.as_deref()?; - let mut parts = traceparent.split('-'); - match (parts.next(), parts.next(), parts.next(), parts.next()) { - (Some(_version), Some(trace_id), Some(_span_id), Some(_trace_flags)) - if trace_id.len() == 32 => - { - Some(format!("go/trace/{trace_id}")) - } - _ => None, - } -} - -fn print_trace_summary(trace_summary: &TraceSummary) { - println!("\n[Datadog trace]"); - match trace_summary { - TraceSummary::Enabled { url } => println!("{url}\n"), - TraceSummary::Disabled => println!("{TRACE_DISABLED_MESSAGE}\n"), - } -} - impl Drop for CodexClient { fn drop(&mut self) { let ClientTransport::Stdio { child, stdin, .. } = &mut self.transport else { diff --git a/codex-rs/app-server-test-client/src/loopback_responses_server.rs b/codex-rs/app-server-test-client/src/loopback_responses_server.rs deleted file mode 100644 index 74b7c753..00000000 --- a/codex-rs/app-server-test-client/src/loopback_responses_server.rs +++ /dev/null @@ -1,145 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use std::io; -use std::io::Read; -use std::io::Write; -use std::net::TcpListener; -use std::net::TcpStream; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::thread; -use std::thread::JoinHandle; -use std::time::Duration; - -pub(super) struct LoopbackResponsesServer { - base_url: String, - shutdown: Arc, - thread: Option>, -} - -impl LoopbackResponsesServer { - pub(super) fn start() -> Result { - let listener = - TcpListener::bind("127.0.0.1:0").context("bind loopback Responses API server")?; - listener - .set_nonblocking(true) - .context("set loopback Responses API server nonblocking")?; - let address = listener.local_addr()?; - let shutdown = Arc::new(AtomicBool::new(false)); - let thread_shutdown = Arc::clone(&shutdown); - let thread = thread::spawn(move || { - while !thread_shutdown.load(Ordering::Relaxed) { - match listener.accept() { - Ok((stream, _)) => { - if let Err(err) = handle_model_connection(stream) { - eprintln!("loopback Responses API server error: {err}"); - } - } - Err(err) if err.kind() == io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(err) => { - eprintln!("loopback Responses API accept error: {err}"); - break; - } - } - } - }); - Ok(Self { - base_url: format!("http://{address}"), - shutdown, - thread: Some(thread), - }) - } - - pub(super) fn base_url(&self) -> &str { - &self.base_url - } -} - -impl Drop for LoopbackResponsesServer { - fn drop(&mut self) { - self.shutdown.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} - -fn handle_model_connection(mut stream: TcpStream) -> io::Result<()> { - stream.set_nonblocking(false)?; - stream.set_read_timeout(Some(Duration::from_secs(2)))?; - let request = read_http_request(&mut stream)?; - let request_line = request - .split(|byte| *byte == b'\n') - .next() - .and_then(|line| std::str::from_utf8(line).ok()) - .unwrap_or_default(); - if request_line.starts_with("POST ") && request_line.contains("/responses ") { - let body = concat!( - "event: response.created\n", - "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp-plugin-analytics\"}}\n\n", - "event: response.completed\n", - "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp-plugin-analytics\",\"usage\":{\"input_tokens\":0,\"input_tokens_details\":null,\"output_tokens\":0,\"output_tokens_details\":null,\"total_tokens\":0}}}\n\n" - ); - write_http_response(&mut stream, "200 OK", "text/event-stream", body) - } else { - write_http_response( - &mut stream, - "404 Not Found", - "application/json", - r#"{"error":"not found"}"#, - ) - } -} - -fn read_http_request(stream: &mut TcpStream) -> io::Result> { - let mut request = Vec::new(); - let mut buffer = [0_u8; 4096]; - let header_end = loop { - let read = stream.read(&mut buffer)?; - if read == 0 { - return Ok(request); - } - request.extend_from_slice(&buffer[..read]); - if let Some(position) = request.windows(4).position(|window| window == b"\r\n\r\n") { - break position + 4; - } - }; - let content_length = parse_content_length(&request[..header_end]); - while request.len() < header_end + content_length { - let read = stream.read(&mut buffer)?; - if read == 0 { - break; - } - request.extend_from_slice(&buffer[..read]); - } - Ok(request) -} - -fn parse_content_length(headers: &[u8]) -> usize { - String::from_utf8_lossy(headers) - .lines() - .find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse().ok()) - .flatten() - }) - .unwrap_or(0) -} - -fn write_http_response( - stream: &mut TcpStream, - status: &str, - content_type: &str, - body: &str, -) -> io::Result<()> { - write!( - stream, - "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - )?; - stream.flush() -} diff --git a/codex-rs/app-server-test-client/src/plugin_analytics_capture.rs b/codex-rs/app-server-test-client/src/plugin_analytics_capture.rs deleted file mode 100644 index 8a68a574..00000000 --- a/codex-rs/app-server-test-client/src/plugin_analytics_capture.rs +++ /dev/null @@ -1,107 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::bail; -use serde_json::Value; -use std::fs; -use std::io; -use std::path::Path; - -pub(super) fn read_events_for_remote_plugin( - path: &Path, - remote_plugin_id: &str, -) -> Result> { - let contents = match fs::read_to_string(path) { - Ok(contents) => contents, - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(err) => { - return Err(err).with_context(|| format!("read capture file {}", path.display())); - } - }; - let mut matching = Vec::new(); - for (index, line) in contents.lines().enumerate() { - if line.trim().is_empty() { - continue; - } - let payload: Value = serde_json::from_str(line).with_context(|| { - format!( - "parse analytics capture line {} from {}", - index + 1, - path.display() - ) - })?; - let events = payload["events"] - .as_array() - .context("analytics capture payload is missing events")?; - matching.extend( - events - .iter() - .filter(|event| event["event_params"]["remote_plugin_id"] == remote_plugin_id) - .cloned(), - ); - } - Ok(matching) -} - -pub(super) struct PluginEventIdentity<'a> { - pub(super) plugin_id: &'a str, - pub(super) remote_plugin_id: &'a str, - pub(super) plugin_name: &'a str, - pub(super) marketplace_name: &'a str, -} - -pub(super) fn validate_mutation_events( - events: Vec, - expected: PluginEventIdentity<'_>, -) -> Result> { - let mut validated = Vec::new(); - for event_type in ["codex_plugin_installed", "codex_plugin_uninstalled"] { - let matching = events - .iter() - .filter(|event| event["event_type"] == event_type) - .collect::>(); - let [event] = matching.as_slice() else { - bail!( - "expected exactly one `{event_type}` event for `{}`, found {}", - expected.remote_plugin_id, - matching.len() - ); - }; - validate_event(event, &expected)?; - validated.push((*event).clone()); - } - Ok(validated) -} - -fn validate_event(event: &Value, expected: &PluginEventIdentity<'_>) -> Result<()> { - let params = &event["event_params"]; - require_string(params, "plugin_id", expected.plugin_id)?; - require_string(params, "remote_plugin_id", expected.remote_plugin_id)?; - require_string(params, "plugin_name", expected.plugin_name)?; - require_string(params, "marketplace_name", expected.marketplace_name)?; - for field in [ - "has_skills", - "mcp_server_count", - "connector_ids", - "product_client_id", - ] { - if params.get(field).is_none_or(Value::is_null) { - bail!( - "{} event has null or missing `{field}`", - event["event_type"] - ); - } - } - Ok(()) -} - -fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> { - let actual = params.get(field).and_then(Value::as_str); - if actual != Some(expected) { - bail!("expected `{field}` to be `{expected}`, got {actual:?}"); - } - Ok(()) -} - -#[cfg(test)] -#[path = "plugin_analytics_capture_tests.rs"] -mod tests; diff --git a/codex-rs/app-server-test-client/src/plugin_analytics_capture_tests.rs b/codex-rs/app-server-test-client/src/plugin_analytics_capture_tests.rs deleted file mode 100644 index b85bd48b..00000000 --- a/codex-rs/app-server-test-client/src/plugin_analytics_capture_tests.rs +++ /dev/null @@ -1,97 +0,0 @@ -use super::PluginEventIdentity; -use super::read_events_for_remote_plugin; -use super::validate_mutation_events; -use serde_json::Value; -use serde_json::json; -use std::fs; -use std::path::PathBuf; -use std::process; -use std::time::SystemTime; - -const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_test"; - -#[test] -fn reads_and_validates_remote_plugin_mutation_events() { - let path = unique_capture_path("valid"); - let installed = mutation_event("codex_plugin_installed"); - let uninstalled = mutation_event("codex_plugin_uninstalled"); - let unrelated = json!({ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "other@openai-curated-remote", - "remote_plugin_id": "plugins~Plugin_other" - } - }); - let contents = [ - json!({"events": [unrelated]}), - json!({"events": [installed, uninstalled]}), - ] - .into_iter() - .map(|payload| serde_json::to_string(&payload).expect("serialize capture payload")) - .collect::>() - .join("\n"); - fs::write(&path, contents).expect("write capture file"); - - let events = read_events_for_remote_plugin(&path, REMOTE_PLUGIN_ID) - .expect("read matching plugin events"); - let validated = - validate_mutation_events(events, expected_identity()).expect("validate mutation events"); - - assert_eq!(validated, vec![installed, uninstalled]); - fs::remove_file(path).expect("remove capture file"); -} - -#[test] -fn rejects_duplicate_mutation_events() { - let installed = mutation_event("codex_plugin_installed"); - let error = validate_mutation_events(vec![installed.clone(), installed], expected_identity()) - .expect_err("duplicate install events should fail validation"); - - assert!(error.to_string().contains("found 2")); -} - -#[test] -fn rejects_missing_capability_metadata() { - let mut installed = mutation_event("codex_plugin_installed"); - installed["event_params"]["has_skills"] = Value::Null; - let error = validate_mutation_events(vec![installed], expected_identity()) - .expect_err("missing capability metadata should fail validation"); - - assert!(error.to_string().contains("has_skills")); -} - -fn mutation_event(event_type: &str) -> Value { - json!({ - "event_type": event_type, - "event_params": { - "plugin_id": "sample@openai-curated-remote", - "remote_plugin_id": REMOTE_PLUGIN_ID, - "plugin_name": "sample", - "marketplace_name": "openai-curated-remote", - "has_skills": true, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": "test-client" - } - }) -} - -fn expected_identity() -> PluginEventIdentity<'static> { - PluginEventIdentity { - plugin_id: "sample@openai-curated-remote", - remote_plugin_id: REMOTE_PLUGIN_ID, - plugin_name: "sample", - marketplace_name: "openai-curated-remote", - } -} - -fn unique_capture_path(name: &str) -> PathBuf { - let nonce = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .expect("system clock should be after Unix epoch") - .as_nanos(); - std::env::temp_dir().join(format!( - "codex-plugin-analytics-capture-{name}-{}-{nonce}.jsonl", - process::id() - )) -} diff --git a/codex-rs/app-server-test-client/src/plugin_analytics_mutation_smoke.rs b/codex-rs/app-server-test-client/src/plugin_analytics_mutation_smoke.rs deleted file mode 100644 index 94ab863b..00000000 --- a/codex-rs/app-server-test-client/src/plugin_analytics_mutation_smoke.rs +++ /dev/null @@ -1,488 +0,0 @@ -use super::CodexClient; -use super::plugin_analytics_capture::PluginEventIdentity; -use super::plugin_analytics_capture::read_events_for_remote_plugin; -use super::plugin_analytics_capture::validate_mutation_events; -use super::plugin_analytics_smoke::ANALYTICS_CAPTURE_ENV_VAR; -use super::plugin_analytics_smoke::prepare_capture_file; -use super::plugin_analytics_smoke::wait_until_capture_is_ready; -use super::shell_quote; -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use anyhow::bail; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::PluginAvailability; -use codex_app_server_protocol::PluginInstallParams; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginInstallResponse; -use codex_app_server_protocol::PluginReadParams; -use codex_app_server_protocol::PluginReadResponse; -use codex_app_server_protocol::PluginUninstallParams; -use codex_app_server_protocol::PluginUninstallResponse; -use serde_json::Value; -use std::ffi::OsString; -use std::path::Path; -use std::path::PathBuf; -use std::process; -use std::thread; -use std::time::Duration; -use std::time::Instant; - -const REMOTE_MARKETPLACE_HINT: &str = "openai-curated-remote"; -const STATE_TIMEOUT: Duration = Duration::from_secs(15); -const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10); -const POLL_INTERVAL: Duration = Duration::from_millis(100); - -pub(super) fn run( - codex_bin: &Path, - config_overrides: &[String], - remote_plugin_id: &str, - confirmation: AccountMutationConfirmation, - capture_file: Option, -) -> Result<()> { - require_confirmation(confirmation)?; - let capture_path = capture_file.unwrap_or_else(|| { - std::env::temp_dir().join(format!( - "codex-plugin-analytics-mutation-{}.jsonl", - process::id() - )) - }); - prepare_capture_file(&capture_path)?; - let mut client = spawn_client(codex_bin, config_overrides, &capture_path)?; - wait_until_capture_is_ready(&capture_path)?; - client.initialize()?; - - let initial = read_remote_plugin(&mut client, remote_plugin_id)?; - validate_initial_plugin(&initial, remote_plugin_id)?; - println!( - "remote plugin mutation smoke: local_id={} remote_id={} marketplace={}", - initial.plugin_id, initial.remote_plugin_id, initial.marketplace_name - ); - - let MutationSequenceResult { - result: sequence_result, - uninstall_rpc_failed, - } = run_mutation_sequence(&mut client, &capture_path, &initial); - let restoration = restore_uninstalled_state(&mut client, remote_plugin_id); - println!("capture file: {}", capture_path.display()); - - match (sequence_result, restoration) { - (Ok(events), RestorationStatus::Clean) => { - println!( - "\n[plugin analytics mutation smoke validated]\n{}", - serde_json::to_string_pretty(&events)? - ); - println!("PASS: analytics validated; original uninstalled state restored"); - Ok(()) - } - (Err(err), RestorationStatus::Clean) if uninstall_rpc_failed => { - eprintln!( - "FAIL-LOCAL-CACHE: backend state is uninstalled, but the uninstall RPC failed after the backend mutation: {err:#}" - ); - Err(err) - } - (Err(err), RestorationStatus::Clean) => { - eprintln!("FAIL-CLEAN: {err:#}"); - eprintln!("The original uninstalled account state was restored."); - Err(err) - } - (sequence_result, RestorationStatus::LocalCleanupFailure(cleanup_err)) => { - let sequence_err = sequence_result.err(); - eprintln!( - "FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {cleanup_err:#}" - ); - Err(sequence_err.unwrap_or(cleanup_err)) - } - (sequence_result, RestorationStatus::Dirty(cleanup_err)) => { - if let Err(err) = sequence_result { - eprintln!("mutation smoke failed before cleanup: {err:#}"); - } - print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &cleanup_err); - Err(cleanup_err) - } - (sequence_result, RestorationStatus::Unknown(cleanup_err)) => { - if let Err(err) = sequence_result { - eprintln!("mutation smoke failed before final state verification: {err:#}"); - } - eprintln!( - "FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {cleanup_err:#}" - ); - print_recovery_command(codex_bin, config_overrides, remote_plugin_id); - Err(cleanup_err) - } - } -} - -pub(super) fn run_cleanup( - codex_bin: &Path, - config_overrides: &[String], - remote_plugin_id: &str, - confirmation: AccountMutationConfirmation, -) -> Result<()> { - require_confirmation(confirmation)?; - let mut overrides = config_overrides.to_vec(); - overrides.extend([ - "analytics.enabled=false".to_string(), - "features.plugins=true".to_string(), - ]); - let mut client = CodexClient::spawn_stdio(codex_bin, &overrides)?; - client.initialize()?; - - match restore_uninstalled_state(&mut client, remote_plugin_id) { - RestorationStatus::Clean => { - println!("PASS: `{remote_plugin_id}` is uninstalled"); - Ok(()) - } - RestorationStatus::LocalCleanupFailure(err) => { - eprintln!( - "FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {err:#}" - ); - Err(err) - } - RestorationStatus::Dirty(err) => { - print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &err); - Err(err) - } - RestorationStatus::Unknown(err) => { - eprintln!( - "FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {err:#}" - ); - Err(err) - } - } -} - -#[derive(Clone, Copy)] -pub(super) enum AccountMutationConfirmation { - Confirmed, - Missing, -} - -impl AccountMutationConfirmation { - pub(super) fn from_flag(confirm_account_mutation: bool) -> Self { - if confirm_account_mutation { - Self::Confirmed - } else { - Self::Missing - } - } -} - -fn require_confirmation(confirmation: AccountMutationConfirmation) -> Result<()> { - if matches!(confirmation, AccountMutationConfirmation::Missing) { - bail!( - "this command installs and uninstalls a plugin on the active account; rerun with --confirm-account-mutation" - ); - } - Ok(()) -} - -#[derive(Clone, Copy, Debug)] -enum ExpectedInstalledState { - Installed, - Uninstalled, -} - -impl ExpectedInstalledState { - fn is_installed(self) -> bool { - matches!(self, Self::Installed) - } -} - -fn spawn_client( - codex_bin: &Path, - config_overrides: &[String], - capture_path: &Path, -) -> Result { - let mut overrides = config_overrides.to_vec(); - overrides.extend([ - "analytics.enabled=true".to_string(), - "features.plugins=true".to_string(), - ]); - let environment = vec![( - OsString::from(ANALYTICS_CAPTURE_ENV_VAR), - capture_path.as_os_str().to_os_string(), - )]; - CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &environment) -} - -#[derive(Clone, Debug)] -struct RemotePluginExpectation { - plugin_id: String, - remote_plugin_id: String, - plugin_name: String, - marketplace_name: String, - installed: bool, - install_policy: PluginInstallPolicy, - availability: PluginAvailability, -} - -fn read_remote_plugin( - client: &mut CodexClient, - remote_plugin_id: &str, -) -> Result { - let request_id = client.request_id(); - let response: PluginReadResponse = client.send_request( - ClientRequest::PluginRead { - request_id: request_id.clone(), - params: PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some(REMOTE_MARKETPLACE_HINT.to_string()), - plugin_name: remote_plugin_id.to_string(), - }, - }, - request_id, - "plugin/read", - )?; - let summary = response.plugin.summary; - let actual_remote_plugin_id = summary - .remote_plugin_id - .with_context(|| format!("plugin/read returned no remote id for `{remote_plugin_id}`"))?; - if actual_remote_plugin_id != remote_plugin_id { - bail!( - "plugin/read returned remote id `{actual_remote_plugin_id}` for requested id `{remote_plugin_id}`" - ); - } - Ok(RemotePluginExpectation { - plugin_id: summary.id, - remote_plugin_id: actual_remote_plugin_id, - plugin_name: summary.name, - marketplace_name: response.plugin.marketplace_name, - installed: summary.installed, - install_policy: summary.install_policy, - availability: summary.availability, - }) -} - -fn validate_initial_plugin(plugin: &RemotePluginExpectation, remote_plugin_id: &str) -> Result<()> { - if plugin.installed { - bail!( - "refusing to run: remote plugin `{remote_plugin_id}` is already installed; choose an initially uninstalled plugin" - ); - } - if plugin.availability != PluginAvailability::Available { - bail!( - "remote plugin `{remote_plugin_id}` is not available: {:?}", - plugin.availability - ); - } - if plugin.install_policy == PluginInstallPolicy::NotAvailable { - bail!("remote plugin `{remote_plugin_id}` is not available for install"); - } - Ok(()) -} - -struct MutationSequenceResult { - result: Result>, - uninstall_rpc_failed: bool, -} - -fn run_mutation_sequence( - client: &mut CodexClient, - capture_path: &Path, - expected: &RemotePluginExpectation, -) -> MutationSequenceResult { - let mut uninstall_rpc_failed = false; - let result = (|| { - install_remote_plugin(client, expected)?; - wait_for_installed_state( - client, - &expected.remote_plugin_id, - ExpectedInstalledState::Installed, - )?; - wait_for_remote_plugin_event( - capture_path, - &expected.remote_plugin_id, - "codex_plugin_installed", - )?; - - let uninstall_error = uninstall_remote_plugin(client, &expected.remote_plugin_id).err(); - uninstall_rpc_failed = uninstall_error.is_some(); - wait_for_installed_state( - client, - &expected.remote_plugin_id, - ExpectedInstalledState::Uninstalled, - ) - .map_err(|state_err| { - if let Some(err) = uninstall_error.as_ref() { - anyhow!("plugin/uninstall failed: {err:#}; final state check failed: {state_err:#}") - } else { - state_err - } - })?; - wait_for_remote_plugin_event( - capture_path, - &expected.remote_plugin_id, - "codex_plugin_uninstalled", - )?; - - let captured_events = - read_events_for_remote_plugin(capture_path, &expected.remote_plugin_id)?; - let events = validate_mutation_events( - captured_events, - PluginEventIdentity { - plugin_id: &expected.plugin_id, - remote_plugin_id: &expected.remote_plugin_id, - plugin_name: &expected.plugin_name, - marketplace_name: &expected.marketplace_name, - }, - )?; - if let Some(err) = uninstall_error { - return Err(err.context( - "plugin/uninstall reported an error after the backend became uninstalled", - )); - } - Ok(events) - })(); - - MutationSequenceResult { - result, - uninstall_rpc_failed, - } -} - -fn install_remote_plugin(client: &mut CodexClient, plugin: &RemotePluginExpectation) -> Result<()> { - let request_id = client.request_id(); - let _: PluginInstallResponse = client.send_request( - ClientRequest::PluginInstall { - request_id: request_id.clone(), - params: PluginInstallParams { - marketplace_path: None, - remote_marketplace_name: Some(plugin.marketplace_name.clone()), - install_attempt_id: None, - plugin_name: plugin.remote_plugin_id.clone(), - }, - }, - request_id, - "plugin/install", - )?; - Ok(()) -} - -fn uninstall_remote_plugin(client: &mut CodexClient, remote_plugin_id: &str) -> Result<()> { - let request_id = client.request_id(); - let _: PluginUninstallResponse = client.send_request( - ClientRequest::PluginUninstall { - request_id: request_id.clone(), - params: PluginUninstallParams { - plugin_id: remote_plugin_id.to_string(), - }, - }, - request_id, - "plugin/uninstall", - )?; - Ok(()) -} - -fn wait_for_installed_state( - client: &mut CodexClient, - remote_plugin_id: &str, - expected_state: ExpectedInstalledState, -) -> Result { - let deadline = Instant::now() + STATE_TIMEOUT; - loop { - match read_remote_plugin(client, remote_plugin_id) { - Ok(plugin) if plugin.installed == expected_state.is_installed() => return Ok(plugin), - Ok(_) => {} - Err(err) if Instant::now() >= deadline => return Err(err), - Err(_) => {} - } - if Instant::now() >= deadline { - bail!( - "timed out waiting for remote plugin `{remote_plugin_id}` to become {expected_state:?}" - ); - } - thread::sleep(POLL_INTERVAL); - } -} - -enum RestorationStatus { - Clean, - LocalCleanupFailure(anyhow::Error), - Dirty(anyhow::Error), - Unknown(anyhow::Error), -} - -fn restore_uninstalled_state( - client: &mut CodexClient, - remote_plugin_id: &str, -) -> RestorationStatus { - let current = match read_remote_plugin(client, remote_plugin_id) { - Ok(current) => current, - Err(err) => return RestorationStatus::Unknown(err), - }; - if !current.installed { - return RestorationStatus::Clean; - } - - let uninstall_result = uninstall_remote_plugin(client, remote_plugin_id); - match wait_for_installed_state( - client, - remote_plugin_id, - ExpectedInstalledState::Uninstalled, - ) { - Ok(_) => match uninstall_result { - Ok(()) => RestorationStatus::Clean, - Err(err) => RestorationStatus::LocalCleanupFailure(err), - }, - Err(state_err) => { - let error = match uninstall_result { - Ok(()) => state_err, - Err(uninstall_err) => anyhow!( - "cleanup uninstall failed: {uninstall_err:#}; state verification failed: {state_err:#}" - ), - }; - RestorationStatus::Dirty(error) - } - } -} - -fn wait_for_remote_plugin_event( - path: &Path, - remote_plugin_id: &str, - event_type: &str, -) -> Result<()> { - let deadline = Instant::now() + CAPTURE_TIMEOUT; - loop { - let events = read_events_for_remote_plugin(path, remote_plugin_id)?; - if events.iter().any(|event| event["event_type"] == event_type) { - return Ok(()); - } - if Instant::now() >= deadline { - bail!("timed out waiting for `{event_type}` for remote plugin `{remote_plugin_id}`"); - } - thread::sleep(POLL_INTERVAL); - } -} - -fn print_dirty_recovery( - codex_bin: &Path, - config_overrides: &[String], - remote_plugin_id: &str, - err: &anyhow::Error, -) { - eprintln!( - "FAIL-DIRTY: remote plugin `{remote_plugin_id}` still appears installed after cleanup: {err:#}" - ); - print_recovery_command(codex_bin, config_overrides, remote_plugin_id); -} - -fn print_recovery_command(codex_bin: &Path, config_overrides: &[String], remote_plugin_id: &str) { - let test_client = std::env::current_exe() - .map(|path| path.display().to_string()) - .unwrap_or_else(|_| "codex-app-server-test-client".to_string()); - let mut command = format!( - "{} --codex-bin {}", - shell_quote(&test_client), - shell_quote(&codex_bin.display().to_string()) - ); - for override_kv in config_overrides { - command.push_str(&format!(" --config {}", shell_quote(override_kv))); - } - command.push_str(&format!( - " plugin-remote-uninstall --remote-plugin-id {} --confirm-account-mutation", - shell_quote(remote_plugin_id) - )); - eprintln!("Recovery command:"); - eprintln!(" {command}"); -} diff --git a/codex-rs/app-server-test-client/src/plugin_analytics_smoke.rs b/codex-rs/app-server-test-client/src/plugin_analytics_smoke.rs deleted file mode 100644 index aaf54dd2..00000000 --- a/codex-rs/app-server-test-client/src/plugin_analytics_smoke.rs +++ /dev/null @@ -1,504 +0,0 @@ -use super::CodexClient; -use super::loopback_responses_server::LoopbackResponsesServer; -use anyhow::Context; -use anyhow::Result; -use anyhow::bail; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ConfigValueWriteParams; -use codex_app_server_protocol::ConfigWriteResponse; -use codex_app_server_protocol::MergeStrategy; -use codex_app_server_protocol::PluginAvailability; -use codex_app_server_protocol::PluginInstalledParams; -use codex_app_server_protocol::PluginInstalledResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; -use codex_app_server_protocol::WriteStatus; -use serde_json::Value; -use serde_json::json; -use std::ffi::OsString; -use std::fs; -use std::io; -use std::path::Path; -use std::path::PathBuf; -use std::process; -use std::thread; -use std::time::Duration; -use std::time::Instant; - -pub(super) const ANALYTICS_CAPTURE_ENV_VAR: &str = "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE"; -const TEST_USER_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE"; -const CAPTURE_READY_TIMEOUT: Duration = Duration::from_secs(5); -const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10); -const CAPTURE_POLL_INTERVAL: Duration = Duration::from_millis(50); -const PLUGIN_READY_TIMEOUT: Duration = Duration::from_secs(30); -const PLUGIN_READY_RETRY_INTERVAL: Duration = Duration::from_millis(250); -const MOCK_MODEL_SLUG: &str = "plugin-analytics-smoke"; -const MOCK_PROVIDER_ID: &str = "plugin_analytics_smoke"; - -pub(super) fn run( - codex_bin: &Path, - config_overrides: &[String], - plugin_id: &str, - capture_file: Option, -) -> Result<()> { - let capture_path = capture_file.unwrap_or_else(|| { - std::env::temp_dir().join(format!("codex-plugin-analytics-{}.jsonl", process::id())) - }); - prepare_capture_file(&capture_path)?; - - let temporary_config = TemporaryConfigFile::create()?; - let responses_server = LoopbackResponsesServer::start()?; - let mut overrides = config_overrides.to_vec(); - overrides.extend(smoke_config_overrides(responses_server.base_url())?); - - let child_environment = vec![ - ( - OsString::from(ANALYTICS_CAPTURE_ENV_VAR), - capture_path.as_os_str().to_os_string(), - ), - ( - OsString::from(TEST_USER_CONFIG_ENV_VAR), - temporary_config.path().as_os_str().to_os_string(), - ), - ]; - let mut client = CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &child_environment)?; - wait_until_capture_is_ready(&capture_path)?; - client.initialize()?; - - let installed = plugin_installed(&mut client)?; - let expected = expected_plugin(&installed, plugin_id)?; - write_plugin_enabled( - &mut client, - temporary_config.path(), - plugin_id, - /*enabled*/ false, - )?; - write_plugin_enabled( - &mut client, - temporary_config.path(), - plugin_id, - /*enabled*/ true, - )?; - - wait_for_plugin_usage(&mut client, &capture_path, &expected)?; - - let events = wait_for_plugin_events(&capture_path, plugin_id)?; - let validated = validate_plugin_events(events, &expected)?; - println!( - "\n[plugin analytics smoke validated]\n{}", - serde_json::to_string_pretty(&validated)? - ); - println!("capture file: {}", capture_path.display()); - Ok(()) -} - -fn run_plugin_turn(client: &mut CodexClient, expected: &ExpectedPlugin) -> Result { - let thread = client.thread_start(ThreadStartParams { - model: Some(MOCK_MODEL_SLUG.to_string()), - model_provider: Some(MOCK_PROVIDER_ID.to_string()), - base_instructions: Some(String::new()), - developer_instructions: Some(String::new()), - ephemeral: Some(true), - ..Default::default() - })?; - let turn = client.turn_start(TurnStartParams { - thread_id: thread.thread.id.clone(), - client_user_message_id: None, - input: vec![UserInput::Mention { - name: expected.plugin_name.clone(), - path: format!("plugin://{}", expected.plugin_id), - }], - ..Default::default() - })?; - client.stream_turn(&thread.thread.id, &turn.turn.id)?; - if client.last_turn_status != Some(TurnStatus::Completed) { - bail!( - "plugin analytics smoke turn did not complete: status={:?}, error={:?}", - client.last_turn_status, - client.last_turn_error_message - ); - } - Ok(turn.turn.id) -} - -fn wait_for_plugin_usage( - client: &mut CodexClient, - capture_path: &Path, - expected: &ExpectedPlugin, -) -> Result<()> { - let deadline = Instant::now() + PLUGIN_READY_TIMEOUT; - let mut attempts = 0; - loop { - attempts += 1; - let turn_id = run_plugin_turn(client, expected)?; - // Turn completion is queued after plugin usage, so its captured event is the - // barrier that tells us whether this attempt resolved the plugin. - let events = wait_for_turn_analytics(capture_path, &turn_id)?; - if events.iter().any(|event| { - event["event_type"] == "codex_plugin_used" - && event["event_params"]["turn_id"].as_str() == Some(turn_id.as_str()) - && event["event_params"]["plugin_id"].as_str() == Some(expected.plugin_id.as_str()) - }) { - if attempts > 1 { - println!("remote plugin bundle became ready after {attempts} turn attempts"); - } - return Ok(()); - } - if Instant::now() >= deadline { - bail!( - "timed out waiting for remote plugin bundle `{}` to become usable after {attempts} turn attempts", - expected.plugin_id - ); - } - thread::sleep(PLUGIN_READY_RETRY_INTERVAL); - } -} - -#[derive(Debug)] -struct ExpectedPlugin { - plugin_id: String, - remote_plugin_id: String, - plugin_name: String, - marketplace_name: String, -} - -fn plugin_installed(client: &mut CodexClient) -> Result { - let request_id = client.request_id(); - client.send_request( - ClientRequest::PluginInstalled { - request_id: request_id.clone(), - params: PluginInstalledParams { - cwds: None, - install_suggestion_plugin_names: None, - }, - }, - request_id, - "plugin/installed", - ) -} - -fn expected_plugin(response: &PluginInstalledResponse, plugin_id: &str) -> Result { - let matches = response - .marketplaces - .iter() - .flat_map(|marketplace| { - marketplace - .plugins - .iter() - .filter(move |plugin| plugin.id == plugin_id) - .map(move |plugin| (marketplace, plugin)) - }) - .collect::>(); - let [(marketplace, plugin)] = matches.as_slice() else { - bail!( - "expected exactly one installed plugin with local id `{plugin_id}`, found {}", - matches.len() - ); - }; - if !plugin.installed { - bail!("plugin `{plugin_id}` is not installed"); - } - if !plugin.enabled { - bail!("plugin `{plugin_id}` is installed remotely but disabled"); - } - if plugin.availability != PluginAvailability::Available { - bail!( - "plugin `{plugin_id}` is not available: {:?}", - plugin.availability - ); - } - let remote_plugin_id = plugin - .remote_plugin_id - .as_ref() - .with_context(|| format!("plugin `{plugin_id}` does not have a remote plugin id"))? - .clone(); - - Ok(ExpectedPlugin { - plugin_id: plugin.id.clone(), - remote_plugin_id, - plugin_name: plugin.name.clone(), - marketplace_name: marketplace.name.clone(), - }) -} - -fn write_plugin_enabled( - client: &mut CodexClient, - config_path: &Path, - plugin_id: &str, - enabled: bool, -) -> Result<()> { - let request_id = client.request_id(); - let response: ConfigWriteResponse = client.send_request( - ClientRequest::ConfigValueWrite { - request_id: request_id.clone(), - params: ConfigValueWriteParams { - key_path: format!("plugins.{plugin_id}.enabled"), - value: json!(enabled), - merge_strategy: MergeStrategy::Replace, - file_path: Some(config_path.display().to_string()), - expected_version: None, - }, - }, - request_id, - "config/value/write", - )?; - println!( - "< config/value/write plugin={plugin_id} enabled={enabled} status={:?}", - response.status - ); - if response.status != WriteStatus::Ok { - bail!( - "config/value/write for plugin `{plugin_id}` enabled={enabled} was overridden: {:?}", - response.overridden_metadata - ); - } - Ok(()) -} - -fn smoke_config_overrides(responses_base_url: &str) -> Result> { - let provider_base_url = serde_json::to_string(&format!("{responses_base_url}/v1")) - .context("serialize mock provider base URL")?; - Ok(vec![ - "analytics.enabled=true".to_string(), - "features.plugins=true".to_string(), - format!("model={}", quoted(MOCK_MODEL_SLUG)?), - format!("model_provider={}", quoted(MOCK_PROVIDER_ID)?), - format!( - "model_providers.{MOCK_PROVIDER_ID}.name={}", - quoted("Plugin analytics smoke mock provider")? - ), - format!("model_providers.{MOCK_PROVIDER_ID}.base_url={provider_base_url}"), - format!( - "model_providers.{MOCK_PROVIDER_ID}.wire_api={}", - quoted("responses")? - ), - format!("model_providers.{MOCK_PROVIDER_ID}.requires_openai_auth=false"), - format!("model_providers.{MOCK_PROVIDER_ID}.request_max_retries=0"), - format!("model_providers.{MOCK_PROVIDER_ID}.stream_max_retries=0"), - ]) -} - -fn quoted(value: &str) -> Result { - serde_json::to_string(value).context("serialize config string") -} - -pub(super) fn prepare_capture_file(path: &Path) -> Result<()> { - let parent = path - .parent() - .context("capture file must have a parent directory")?; - if !parent.is_dir() { - bail!( - "capture file parent directory does not exist: {}", - parent.display() - ); - } - match fs::remove_file(path) { - Ok(()) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => { - return Err(err) - .with_context(|| format!("remove previous capture file {}", path.display())); - } - } - Ok(()) -} - -pub(super) fn wait_until_capture_is_ready(path: &Path) -> Result<()> { - let deadline = Instant::now() + CAPTURE_READY_TIMEOUT; - loop { - match fs::metadata(path) { - Ok(_) => return Ok(()), - Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => { - return Err(err) - .with_context(|| format!("inspect capture file {}", path.display())); - } - } - if Instant::now() >= deadline { - bail!( - "analytics capture did not become ready at {}; use a debug Codex binary", - path.display() - ); - } - thread::sleep(CAPTURE_POLL_INTERVAL); - } -} - -fn wait_for_plugin_events(path: &Path, plugin_id: &str) -> Result> { - let deadline = Instant::now() + CAPTURE_TIMEOUT; - loop { - let events = read_plugin_events(path, plugin_id)?; - if required_event_types() - .iter() - .all(|event_type| event_count(&events, event_type) >= 1) - { - return Ok(events); - } - if Instant::now() >= deadline { - bail!( - "timed out waiting for plugin analytics events in {}: found {:?}", - path.display(), - events - .iter() - .filter_map(|event| event["event_type"].as_str()) - .collect::>() - ); - } - thread::sleep(CAPTURE_POLL_INTERVAL); - } -} - -fn wait_for_turn_analytics(path: &Path, turn_id: &str) -> Result> { - let deadline = Instant::now() + CAPTURE_TIMEOUT; - loop { - let events = read_capture_events(path)?; - if events.iter().any(|event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"].as_str() == Some(turn_id) - }) { - return Ok(events); - } - if Instant::now() >= deadline { - bail!( - "timed out waiting for turn analytics for `{turn_id}` in {}", - path.display() - ); - } - thread::sleep(CAPTURE_POLL_INTERVAL); - } -} - -fn read_plugin_events(path: &Path, plugin_id: &str) -> Result> { - Ok(read_capture_events(path)? - .into_iter() - .filter(|event| event["event_params"]["plugin_id"] == plugin_id) - .collect()) -} - -fn read_capture_events(path: &Path) -> Result> { - let contents = match fs::read_to_string(path) { - Ok(contents) => contents, - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(err) => { - return Err(err).with_context(|| format!("read capture file {}", path.display())); - } - }; - let mut captured = Vec::new(); - for (index, line) in contents.lines().enumerate() { - if line.trim().is_empty() { - continue; - } - let payload: Value = serde_json::from_str(line).with_context(|| { - format!( - "parse analytics capture line {} from {}", - index + 1, - path.display() - ) - })?; - let events = payload["events"] - .as_array() - .context("analytics capture payload is missing events")?; - captured.extend(events.iter().cloned()); - } - Ok(captured) -} - -fn validate_plugin_events(events: Vec, expected: &ExpectedPlugin) -> Result> { - let mut validated = Vec::new(); - for event_type in required_event_types() { - let matching = events - .iter() - .filter(|event| event["event_type"] == event_type) - .collect::>(); - let [event] = matching.as_slice() else { - bail!( - "expected exactly one `{event_type}` event for `{}`, found {}", - expected.plugin_id, - matching.len() - ); - }; - validate_identity(event, expected)?; - if event_type == "codex_plugin_used" { - validate_used_metadata(event)?; - } - validated.push((*event).clone()); - } - Ok(validated) -} - -fn required_event_types() -> [&'static str; 3] { - [ - "codex_plugin_disabled", - "codex_plugin_enabled", - "codex_plugin_used", - ] -} - -fn event_count(events: &[Value], event_type: &str) -> usize { - events - .iter() - .filter(|event| event["event_type"] == event_type) - .count() -} - -fn validate_identity(event: &Value, expected: &ExpectedPlugin) -> Result<()> { - let params = &event["event_params"]; - require_string(params, "plugin_id", &expected.plugin_id)?; - require_string(params, "remote_plugin_id", &expected.remote_plugin_id)?; - require_string(params, "plugin_name", &expected.plugin_name)?; - require_string(params, "marketplace_name", &expected.marketplace_name) -} - -fn validate_used_metadata(event: &Value) -> Result<()> { - let params = &event["event_params"]; - for field in [ - "has_skills", - "mcp_server_count", - "connector_ids", - "mcp_server_names", - "thread_id", - "turn_id", - "model_slug", - ] { - if params.get(field).is_none_or(Value::is_null) { - bail!("codex_plugin_used event has null or missing `{field}`"); - } - } - require_string(params, "model_slug", MOCK_MODEL_SLUG) -} - -fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> { - let actual = params.get(field).and_then(Value::as_str); - if actual != Some(expected) { - bail!("expected `{field}` to be `{expected}`, got {actual:?}"); - } - Ok(()) -} - -struct TemporaryConfigFile { - path: PathBuf, -} - -impl TemporaryConfigFile { - fn create() -> Result { - let path = std::env::temp_dir().join(format!( - "codex-plugin-analytics-config-{}.toml", - process::id() - )); - fs::write(&path, "") - .with_context(|| format!("create temporary config file {}", path.display()))?; - Ok(Self { path }) - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TemporaryConfigFile { - fn drop(&mut self) { - let _ = fs::remove_file(&self.path); - } -} diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index cd4bba01..ccb464fd 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -35,7 +35,6 @@ axum = { workspace = true, default-features = false, features = [ "tokio", "ws", ] } -codex-analytics = { workspace = true } codex-app-server-daemon = { workspace = true } codex-arg0 = { workspace = true } codex-aws-auth = { workspace = true } diff --git a/codex-rs/app-server/src/account_notifications_tests.rs b/codex-rs/app-server/src/account_notifications_tests.rs index df55eaa4..89e4882b 100644 --- a/codex-rs/app-server/src/account_notifications_tests.rs +++ b/codex-rs/app-server/src/account_notifications_tests.rs @@ -11,10 +11,7 @@ use test_case::test_case; async fn queued_notifications_follow_auth_owner_changes(owner_generation: u64) { for login in [false, true] { let (tx, mut rx) = mpsc::channel(/*buffer*/ 1); - let outgoing = OutgoingMessageSender::new( - tx.clone(), - codex_analytics::AnalyticsEventsClient::disabled(), - ); + let outgoing = OutgoingMessageSender::new(tx.clone()); let (changes, auth_changes) = watch::channel(AuthChangeState::default()); let updated = AccountUpdatedNotification { auth_mode: None, diff --git a/codex-rs/app-server/src/analytics_utils.rs b/codex-rs/app-server/src/analytics_utils.rs deleted file mode 100644 index 9ff55f7d..00000000 --- a/codex-rs/app-server/src/analytics_utils.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::sync::Arc; - -use codex_analytics::AnalyticsEventsClient; -use codex_core::config::Config; -use codex_login::AuthManager; -use codex_runtime_agent_instance::RuntimeAuthSlot; - -pub(crate) fn analytics_events_client_from_config( - auth_manager: Arc, - config: &Config, - runtime_auth_slot: Option, -) -> AnalyticsEventsClient { - let api_key_headers = - if codex_model_provider::provider_uses_first_party_auth_path(&config.model_provider) { - match config.model_provider.build_header_map() { - Ok(headers) => headers, - Err(error) => { - tracing::warn!(%error, "failed to resolve analytics resource selectors"); - return AnalyticsEventsClient::disabled(); - } - } - } else { - Default::default() - }; - AnalyticsEventsClient::new_with_runtime( - auth_manager, - config.chatgpt_backend_url(), - config.analytics_enabled, - runtime_auth_slot.map(|slot| (slot, config.runtime_auth_mode)), - api_key_headers, - ) -} diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 41e0b49f..8995569b 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -498,10 +498,7 @@ pub(crate) async fn apply_bespoke_event_handling( )) .await; } - RealtimeEvent::SessionUpdated { - realtime_session_id, - .. - } => outgoing.track_realtime_session_updated(realtime_session_id), + RealtimeEvent::SessionUpdated { .. } => {} RealtimeEvent::InputAudioSpeechStarted(event) => { let notification = ThreadRealtimeItemAddedNotification { thread_id: conversation_id.to_string(), @@ -1924,8 +1921,6 @@ async fn on_request_permissions_response( return; } }; - outgoing.track_effective_permissions_approval_response(pending_request_id, response.clone()); - if let Err(err) = conversation .submit(Op::RequestPermissionsResponse { id: call_id, @@ -2565,10 +2560,7 @@ mod tests { let conversation_id = ThreadId::new(); let thread_state = new_thread_state(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -2638,10 +2630,7 @@ mod tests { let conversation_id = ThreadId::new(); let thread_state = new_thread_state(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -2734,10 +2723,7 @@ mod tests { let thread_state = new_thread_state(); let thread_watch_manager = ThreadWatchManager::new(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3207,10 +3193,7 @@ mod tests { } let thread_watch_manager = ThreadWatchManager::new(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3323,10 +3306,7 @@ mod tests { .await; assert_eq!(thread_watch_manager.running_turn_count().await, 1); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3413,10 +3393,7 @@ mod tests { .start_thread(codex_core::StartThreadOptions::new(config)) .await?; let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3482,10 +3459,7 @@ mod tests { let conversation_id = ThreadId::new(); let event_turn_id = "complete1".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3605,10 +3579,7 @@ mod tests { ) .await; let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3660,10 +3631,7 @@ mod tests { ) .await; let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3705,10 +3673,7 @@ mod tests { #[tokio::test] async fn test_handle_turn_plan_update_emits_notification_for_v2() -> Result<()> { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3755,10 +3720,7 @@ mod tests { let conversation_id = ThreadId::new(); let turn_id = "turn-123".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3851,10 +3813,7 @@ mod tests { let conversation_id = ThreadId::new(); let turn_id = "turn-456".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -3887,10 +3846,7 @@ mod tests { let thread_state = new_thread_state(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], @@ -4008,10 +3964,7 @@ mod tests { #[tokio::test] async fn test_handle_turn_diff_emits_v2_notification() -> Result<()> { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let outgoing = ThreadScopedOutgoingMessageSender::new( outgoing, vec![ConnectionId(1)], diff --git a/codex-rs/app-server/src/codex_home_metrics.rs b/codex-rs/app-server/src/codex_home_metrics.rs deleted file mode 100644 index 9bc90050..00000000 --- a/codex-rs/app-server/src/codex_home_metrics.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Measures local session storage once at standalone app-server startup. -//! -//! The background scan only visits sessions and archived_sessions under CODEX_HOME. -//! It sums regular-file lengths without reading file contents or following symlinks. -//! Incomplete scans emit no samples, and shutdown cancels the scan. -//! The compression tag reflects the effective startup config, not compression completion. - -use codex_core::config::Config; -use codex_features::Feature; -use codex_otel::MetricsClient; -use codex_rollout::ARCHIVED_SESSIONS_SUBDIR; -use codex_rollout::SESSIONS_SUBDIR; -use std::io; -use std::path::Path; -use tokio::task::JoinHandle; -use tokio_util::sync::CancellationToken; - -const SIZE_BYTES_METRIC: &str = "codex.app_server.codex_home.size_bytes"; -// Bucket sizes range from 1 MiB through 1 TiB; larger directories use the overflow bucket. -const SIZE_BYTES_BOUNDARIES: &[f64] = &[ - 1_048_576.0, - 10_485_760.0, - 104_857_600.0, - 1_073_741_824.0, - 10_737_418_240.0, - 107_374_182_400.0, - 1_099_511_627_776.0, -]; - -pub(crate) fn spawn( - config: &Config, - metrics: MetricsClient, - shutdown: CancellationToken, -) -> JoinHandle<()> { - let codex_home = config.codex_home.to_path_buf(); - let compression_enabled = config - .features - .enabled(Feature::LocalThreadStoreCompression) - .to_string(); - tokio::task::spawn_blocking(move || { - let sizes = match directory_sizes(&codex_home, &shutdown) { - Ok(sizes) => sizes, - Err(error) => { - tracing::debug!(error_kind = ?error.kind(), "Skipping CODEX_HOME size metrics"); - return; - } - }; - for (directory, bytes) in [ - (SESSIONS_SUBDIR, sizes.sessions), - (ARCHIVED_SESSIONS_SUBDIR, sizes.archived_sessions), - ] { - let _ = metrics.histogram_with_boundaries( - SIZE_BYTES_METRIC, - i64::try_from(bytes).unwrap_or(i64::MAX), - SIZE_BYTES_BOUNDARIES, - &[ - ("directory", directory), - ("compression_enabled", compression_enabled.as_str()), - ], - ); - } - }) -} - -#[derive(Debug, Default, PartialEq, Eq)] -struct DirectorySizes { - sessions: u64, - archived_sessions: u64, -} - -fn directory_sizes(codex_home: &Path, shutdown: &CancellationToken) -> io::Result { - let sessions = codex_home.join(SESSIONS_SUBDIR); - let archived_sessions = codex_home.join(ARCHIVED_SESSIONS_SUBDIR); - let mut sizes = DirectorySizes::default(); - let mut pending = Vec::new(); - for directory in [&sessions, &archived_sessions] { - if shutdown.is_cancelled() { - return Err(io::ErrorKind::Interrupted.into()); - } - // Inspect the roots without following symlinks, just like entries below them. - let metadata = match std::fs::symlink_metadata(directory) { - Ok(metadata) => metadata, - Err(error) if error.kind() == io::ErrorKind::NotFound => continue, - Err(error) => return Err(error), - }; - if metadata.is_dir() { - pending.push(directory.to_path_buf()); - } - } - while let Some(directory) = pending.pop() { - if shutdown.is_cancelled() { - return Err(io::ErrorKind::Interrupted.into()); - } - for entry in std::fs::read_dir(directory)? { - if shutdown.is_cancelled() { - return Err(io::ErrorKind::Interrupted.into()); - } - let entry = entry?; - // DirEntry::metadata does not follow symbolic links. - let metadata = entry.metadata()?; - let path = entry.path(); - if metadata.is_dir() { - pending.push(path); - } else if metadata.is_file() { - let bytes = metadata.len(); - if path.starts_with(&sessions) { - sizes.sessions = sizes.sessions.saturating_add(bytes); - } else if path.starts_with(&archived_sessions) { - sizes.archived_sessions = sizes.archived_sessions.saturating_add(bytes); - } - } - } - } - Ok(sizes) -} diff --git a/codex-rs/app-server/src/command_exec.rs b/codex-rs/app-server/src/command_exec.rs index c71aff3d..8d2bbdcd 100644 --- a/codex-rs/app-server/src/command_exec.rs +++ b/codex-rs/app-server/src/command_exec.rs @@ -730,10 +730,7 @@ mod tests { let manager = CommandExecManager::default(); let err = manager .start(StartCommandExecParams { - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), request_id: ConnectionRequestId { connection_id: ConnectionId(1), request_id: codex_app_server_protocol::RequestId::Integer(42), @@ -769,10 +766,7 @@ mod tests { manager .start(StartCommandExecParams { - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), request_id: request_id.clone(), process_id: Some("proc-99".to_string()), exec_request: windows_sandbox_exec_request(), @@ -819,10 +813,7 @@ mod tests { manager .start(StartCommandExecParams { - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), request_id: request_id.clone(), process_id: Some("proc-100".to_string()), exec_request: ExecRequest::new( @@ -909,10 +900,7 @@ mod tests { manager .start(StartCommandExecParams { - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), request_id: request_id.clone(), process_id: Some("proc-101".to_string()), exec_request: ExecRequest::new( diff --git a/codex-rs/app-server/src/config_manager_service_tests.rs b/codex-rs/app-server/src/config_manager_service_tests.rs index ea1ce912..62df226e 100644 --- a/codex-rs/app-server/src/config_manager_service_tests.rs +++ b/codex-rs/app-server/src/config_manager_service_tests.rs @@ -9,7 +9,6 @@ use codex_app_server_protocol::ConfigLayerSource as ApiConfigLayerSource; use codex_config::CloudConfigBundleLoader; use codex_config::LoaderOverrides; use codex_config::test_support::CloudConfigBundleFixture; -use codex_config::types::OtelExporterKind; use codex_http_client::HttpClientFactory; use codex_http_client::OutboundProxyPolicy; use codex_utils_absolute_path::AbsolutePathBuf; @@ -1907,13 +1906,15 @@ tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#, for (key_path, managed) in [ ("otel", true), ("otel.log_user_prompt", true), - ("otel.log_agent_responses", true), - ("otel.log_guardian_assessments", true), - ("otel.exporter.otlp-http.endpoint", true), - ("otel.trace_exporter.otlp-grpc.endpoint", true), - ("otel.metrics_exporter.otlp-http.headers", true), - ("otel.span_attributes.\"service.name\"", true), - ("otel.tracestate.managed.tenant", true), + // Legacy exporter/metadata requirements are ignored, so they no longer + // lock the corresponding user keys. + ("otel.log_agent_responses", false), + ("otel.log_guardian_assessments", false), + ("otel.exporter.otlp-http.endpoint", false), + ("otel.trace_exporter.otlp-grpc.endpoint", false), + ("otel.metrics_exporter.otlp-http.headers", false), + ("otel.span_attributes.\"service.name\"", false), + ("otel.tracestate.managed.tenant", false), ("otel.environment", false), ("otel.tool_result.max_bytes", true), ("otel.span_attributes.\"service.version\"", false), @@ -2006,7 +2007,7 @@ enabled = false } #[tokio::test] -async fn read_projects_managed_otel_values_and_preserves_unmanaged_settings() { +async fn read_projects_managed_otel_values_and_ignores_legacy_exporter_keys() { let tmp = tempdir().expect("tempdir"); std::fs::write( tmp.path().join(CONFIG_TOML_FILE), @@ -2049,28 +2050,15 @@ tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#, "tool_result": { "max_bytes": 1234 }, "log_sse_deltas": null, "log_user_prompt": false, - "log_agent_responses": null, - "log_guardian_assessments": null, - "environment": "user", - "exporter": "none", - "trace_exporter": null, - "metrics_exporter": null, - "span_attributes": { - "service.name": "managed-service", - "service.version": "user-version", - }, - "tracestate": { - "managed": { "tenant": "enterprise", "region": "us" }, - "local": { "tenant": "preserved" }, - "empty": { "tenant": "also-preserved" }, - }, }), ); for (path, user_owned) in [ ("otel.log_user_prompt", false), - ("otel.exporter", false), - ("otel.span_attributes.service.name", false), - ("otel.tracestate.managed.tenant", false), + // Legacy exporter/metadata keys are ignored, so managed values for them + // do not take ownership of the user's (equally ignored) entries. + ("otel.exporter", true), + ("otel.span_attributes.service.name", true), + ("otel.tracestate.managed.tenant", true), ("otel.tracestate.managed.region", true), ("otel.environment", true), ("otel.tool_result.max_bytes", true), @@ -2306,7 +2294,7 @@ async fn write_value_reports_managed_override() { } #[tokio::test] -async fn write_overrides_redact_managed_otel_exporter_headers() { +async fn read_redacts_legacy_managed_otel_exporter_headers() { let tmp = tempdir().expect("tempdir"); let user_path = tmp.path().join(CONFIG_TOML_FILE); std::fs::write(&user_path, "").expect("write user config"); @@ -2327,112 +2315,6 @@ span_attributes = { "service.name" = "managed-service" }"#, LoaderOverrides::with_managed_config_path_for_tests(managed_path), CloudConfigBundleLoader::default(), ); - let exporter = serde_json::json!({ - "otlp-http": { - "endpoint": "https://collector.example", - "headers": { "Authorization": "[redacted]", "x.api.key": "[redacted]" }, - "protocol": "json" - } - }); - let otel = serde_json::json!({ - "environment": "managed", - "exporter": exporter.clone(), - "trace_exporter": { - "otlp-grpc": { - "endpoint": "https://trace.example", - "headers": { "Authorization": "[redacted]" } - } - }, - "metrics_exporter": { - "otlp-http": { - "endpoint": "https://metrics.example", - "protocol": "json", - "headers": { "Authorization": "[redacted]" } - } - }, - "span_attributes": { "service.name": "managed-service" } - }); - - for (key_path, expected) in [ - ("otel", otel.clone()), - ("otel.exporter", exporter.clone()), - ("otel.exporter.otlp-http", exporter["otlp-http"].clone()), - ( - "otel.exporter.otlp-http.headers", - exporter["otlp-http"]["headers"].clone(), - ), - ( - "otel.exporter.otlp-http.headers.Authorization", - serde_json::json!("[redacted]"), - ), - ( - "otel.exporter.otlp-http.headers.\"x.api.key\"", - serde_json::json!("[redacted]"), - ), - ( - "otel.exporter.otlp-http.endpoint", - serde_json::json!("https://collector.example"), - ), - ( - "otel.exporter.otlp-http.protocol", - serde_json::json!("json"), - ), - ("otel.trace_exporter", otel["trace_exporter"].clone()), - ("otel.metrics_exporter", otel["metrics_exporter"].clone()), - ( - "otel.metrics_exporter.otlp-http.headers.Authorization", - serde_json::json!("[redacted]"), - ), - ("otel.environment", serde_json::json!("managed")), - ( - "otel.span_attributes.\"service.name\"", - serde_json::json!("managed-service"), - ), - ] { - let response = service - .write_value(ConfigValueWriteParams { - file_path: None, - key_path: key_path.to_string(), - value: serde_json::Value::Null, - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect("no-op config clear should succeed"); - assert_eq!(response.status, WriteStatus::OkOverridden, "{key_path}"); - assert_eq!( - response - .overridden_metadata - .expect("managed override") - .effective_value, - expected, - "{key_path}" - ); - assert_eq!(std::fs::read_to_string(&user_path).unwrap(), ""); - } - - let response = service - .batch_write(ConfigBatchWriteParams { - edits: vec![codex_app_server_protocol::ConfigEdit { - key_path: "otel.exporter.otlp-http.headers.Authorization".to_string(), - value: serde_json::Value::Null, - merge_strategy: MergeStrategy::Replace, - }], - file_path: None, - expected_version: None, - reload_user_config: false, - }) - .await - .expect("no-op batch clear should succeed"); - assert_eq!(response.status, WriteStatus::OkOverridden); - assert_eq!( - response - .overridden_metadata - .expect("managed batch override") - .effective_value, - serde_json::json!("[redacted]") - ); - assert_eq!(std::fs::read_to_string(&user_path).unwrap(), ""); let read = service .read(ConfigReadParams { @@ -2441,16 +2323,25 @@ span_attributes = { "service.name" = "managed-service" }"#, }) .await .expect("read public config"); - let mut effective_exporter = exporter.clone(); - effective_exporter["otlp-http"]["tls"] = serde_json::Value::Null; + // Exporters were removed, so the legacy keys never reach the effective config. assert_eq!( read.config.additional["otel"]["exporter"], - effective_exporter + serde_json::Value::Null ); + assert_eq!( + read.config.additional["otel"]["trace_exporter"], + serde_json::Value::Null + ); + assert_eq!( + read.config.additional["otel"]["metrics_exporter"], + serde_json::Value::Null + ); + // The raw managed layer is still reported, with exporter headers redacted. let managed_layer = read .layers + .as_ref() .expect("config layers") - .into_iter() + .iter() .find(|layer| { matches!( layer.name, @@ -2458,23 +2349,26 @@ span_attributes = { "service.name" = "managed-service" }"#, ) }) .expect("legacy managed layer"); - assert_eq!(managed_layer.config["otel"]["exporter"], exporter); - - let runtime = service - .load_latest_config(/*fallback_cwd*/ None) - .await - .expect("load runtime config"); - let OtelExporterKind::OtlpHttp { headers, .. } = runtime.otel.exporter else { - panic!("unexpected runtime exporter"); - }; assert_eq!( - headers.get("Authorization").map(|value| value.as_str()), - Some("admin-secret") - ); - assert_eq!( - headers.get("x.api.key").map(|value| value.as_str()), - Some("dotted-secret") + managed_layer.config["otel"]["exporter"], + serde_json::json!({ + "otlp-http": { + "endpoint": "https://collector.example", + "headers": { "Authorization": "[redacted]", "x.api.key": "[redacted]" }, + "protocol": "json" + } + }) ); + let serialized = serde_json::to_string(&read).expect("serialize config read"); + for secret in [ + "admin-secret", + "dotted-secret", + "trace-secret", + "metrics-secret", + ] { + assert!(!serialized.contains(secret), "{secret} leaked"); + } + assert_eq!(std::fs::read_to_string(&user_path).unwrap(), ""); } /// Legacy managed feature toggles own their normalized enabled origin and override metadata. diff --git a/codex-rs/app-server/src/extensions.rs b/codex-rs/app-server/src/extensions.rs index 20bba426..42a64e8e 100644 --- a/codex-rs/app-server/src/extensions.rs +++ b/codex-rs/app-server/src/extensions.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use std::sync::Weak; use std::time::Duration; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ThreadGoal; use codex_app_server_protocol::ThreadGoalUpdatedNotification; @@ -35,7 +34,6 @@ pub(crate) struct ThreadExtensionDependencies { pub(crate) event_sink: Arc, pub(crate) auth_manager: Arc, pub(crate) state_db: Option, - pub(crate) analytics_events_client: AnalyticsEventsClient, pub(crate) thread_manager: Weak, pub(crate) goal_service: Arc, pub(crate) environment_manager: Arc, @@ -55,7 +53,6 @@ pub(crate) fn thread_extensions( event_sink, auth_manager, state_db, - analytics_events_client, thread_manager, goal_service, environment_manager, @@ -83,7 +80,6 @@ pub(crate) fn thread_extensions( codex_goal_extension::install_with_backend( &mut builder, state_db, - analytics_events_client, codex_otel::global(), thread_manager.clone(), goal_service, @@ -322,10 +318,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_uses_listener_fifo_for_goal_updates_warnings_and_clears() { let (outgoing_tx, _outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_state_manager = ThreadStateManager::new(); let thread_id = ThreadId::default(); let (listener_command_tx, mut listener_command_rx) = mpsc::unbounded_channel(); @@ -375,10 +368,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_truncates_warning_before_listener_enqueue() { let (outgoing_tx, _outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_state_manager = ThreadStateManager::new(); let thread_id = ThreadId::default(); let (listener_command_tx, mut listener_command_rx) = mpsc::unbounded_channel(); @@ -404,10 +394,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_targets_subscriber_without_listener() { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_id = ThreadId::new(); let subscribed_connection = ConnectionId(1); let unrelated_connection = ConnectionId(2); @@ -463,10 +450,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_waits_for_subscriber_without_listener() { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_id = ThreadId::new(); let subscribed_connection = ConnectionId(1); let thread_state_manager = ThreadStateManager::new(); @@ -519,10 +503,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_targets_subscriber_after_listener_closes() { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_id = ThreadId::new(); let subscribed_connection = ConnectionId(1); let thread_state_manager = ThreadStateManager::new(); @@ -578,10 +559,7 @@ mod tests { #[tokio::test] async fn app_server_event_sink_drops_warning_with_invalid_thread_id() { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let sink = app_server_extension_event_sink(outgoing, ThreadStateManager::new()); sink.emit_warning(ExtensionWarning { diff --git a/codex-rs/app-server/src/external_agent_migration/processor.rs b/codex-rs/app-server/src/external_agent_migration/processor.rs index 8fe3cbd6..4121d611 100644 --- a/codex-rs/app-server/src/external_agent_migration/processor.rs +++ b/codex-rs/app-server/src/external_agent_migration/processor.rs @@ -8,9 +8,6 @@ use crate::error_code::invalid_request; use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; use crate::request_processors::ConfigRequestProcessor; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::ExternalAgentConfigImportCompletedInput; -use codex_analytics::ExternalAgentConfigImportFailureInput; use codex_app_server_protocol::ExternalAgentConfigDetectParams; use codex_app_server_protocol::ExternalAgentConfigDetectResponse; use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification; @@ -69,7 +66,6 @@ pub(crate) struct ExternalAgentConfigRequestProcessor { config_manager: ConfigManager, config_processor: ConfigRequestProcessor, state_db: Option, - analytics_events_client: AnalyticsEventsClient, } pub(crate) struct ExternalAgentConfigRequestProcessorArgs { @@ -79,7 +75,6 @@ pub(crate) struct ExternalAgentConfigRequestProcessorArgs { pub(crate) config_manager: ConfigManager, pub(crate) config_processor: ConfigRequestProcessor, pub(crate) state_db: Option, - pub(crate) analytics_events_client: AnalyticsEventsClient, pub(crate) arg0_paths: Arg0DispatchPaths, pub(crate) codex_home: PathBuf, } @@ -93,14 +88,12 @@ impl ExternalAgentConfigRequestProcessor { config_manager, config_processor, state_db, - analytics_events_client, arg0_paths, codex_home, } = args; let migration_service = ExternalAgentConfigService::new( codex_home.clone(), thread_manager.auth_manager(), - analytics_events_client.clone(), state_db.clone(), ); let session_importer = ExternalAgentSessionImporter::new( @@ -119,7 +112,6 @@ impl ExternalAgentConfigRequestProcessor { config_manager, config_processor, state_db, - analytics_events_client, } } @@ -199,7 +191,6 @@ impl ExternalAgentConfigRequestProcessor { )); } let import_id = Uuid::new_v4().to_string(); - let analytics_source = params.source.clone().unwrap_or_default(); let provider_id = params.provider_id.clone(); let migration_service = self .migration_service @@ -250,9 +241,7 @@ impl ExternalAgentConfigRequestProcessor { send_completed_import_notification( &self.outgoing, self.state_db.as_ref(), - &self.analytics_events_client, import_id, - analytics_source, provider_id, &completed_item_results, ) @@ -263,7 +252,6 @@ impl ExternalAgentConfigRequestProcessor { let session_importer = self.session_importer.clone(); let outgoing = Arc::clone(&self.outgoing); let state_db = self.state_db.clone(); - let analytics_events_client = self.analytics_events_client.clone(); let thread_manager = Arc::clone(&self.thread_manager); let session_metadata_mode = migration_service.session_metadata_mode(); let plugin_migration_service = migration_service; @@ -348,9 +336,7 @@ impl ExternalAgentConfigRequestProcessor { send_completed_import_notification( &outgoing, state_db.as_ref(), - &analytics_events_client, import_id, - analytics_source, provider_id, &completed_item_results, ) @@ -555,20 +541,12 @@ async fn send_import_progress( async fn send_completed_import_notification( outgoing: &OutgoingMessageSender, state_db: Option<&StateDbHandle>, - analytics_events_client: &AnalyticsEventsClient, import_id: String, - analytics_source: String, provider_id: Option, item_results: &[CoreImportItemResult], ) { let notification = completed_notification(import_id, item_results); log_completed_import_failures(¬ification); - track_completed_import_notification( - analytics_events_client, - &analytics_source, - provider_id.as_deref().unwrap_or_default(), - ¬ification, - ); if let Some(state_db) = state_db && let Err(err) = record_completed_import_notification(state_db, provider_id.as_deref(), ¬ification) @@ -605,40 +583,6 @@ fn log_completed_import_failures(notification: &ExternalAgentConfigImportComplet } } -fn track_completed_import_notification( - analytics_events_client: &AnalyticsEventsClient, - analytics_source: &str, - provider_id: &str, - notification: &ExternalAgentConfigImportCompletedNotification, -) { - for type_result in ¬ification.item_type_results { - let item_type = analytics_migration_item_type(type_result.item_type).to_string(); - analytics_events_client.track_external_agent_config_import_completed( - ExternalAgentConfigImportCompletedInput { - import_id: notification.import_id.clone(), - source: analytics_source.to_string(), - provider_id: provider_id.to_string(), - item_type: item_type.clone(), - success_count: type_result.successes.len(), - failed_count: type_result.failures.len(), - }, - ); - for failure in &type_result.failures { - analytics_events_client.track_external_agent_config_import_failure( - ExternalAgentConfigImportFailureInput { - import_id: notification.import_id.clone(), - source: analytics_source.to_string(), - provider_id: provider_id.to_string(), - item_type: item_type.clone(), - failure_stage: failure.failure_stage.clone(), - error_type: import_failure_error_type(failure), - sub_error_type: failure.sub_error_type.clone(), - }, - ); - } - } -} - fn import_failure_error_type(failure: &ProtocolImportFailure) -> String { failure .error_type @@ -646,21 +590,6 @@ fn import_failure_error_type(failure: &ProtocolImportFailure) -> String { .unwrap_or_else(|| failure.failure_stage.clone()) } -fn analytics_migration_item_type(item_type: ExternalAgentConfigMigrationItemType) -> &'static str { - match item_type { - ExternalAgentConfigMigrationItemType::AgentsMd => "AGENTS_MD", - ExternalAgentConfigMigrationItemType::Config => "CONFIG", - ExternalAgentConfigMigrationItemType::Skills => "SKILLS", - ExternalAgentConfigMigrationItemType::Plugins => "PLUGINS", - ExternalAgentConfigMigrationItemType::McpServerConfig => "MCP_SERVER_CONFIG", - ExternalAgentConfigMigrationItemType::Subagents => "SUBAGENTS", - ExternalAgentConfigMigrationItemType::Hooks => "HOOKS", - ExternalAgentConfigMigrationItemType::Commands => "COMMANDS", - ExternalAgentConfigMigrationItemType::Memory => "MEMORY", - ExternalAgentConfigMigrationItemType::Sessions => "SESSIONS", - } -} - async fn record_completed_import_notification( state_db: &StateDbHandle, provider_id: Option<&str>, diff --git a/codex-rs/app-server/src/fs_watch.rs b/codex-rs/app-server/src/fs_watch.rs index 405b0560..ac31f343 100644 --- a/codex-rs/app-server/src/fs_watch.rs +++ b/codex-rs/app-server/src/fs_watch.rs @@ -194,10 +194,7 @@ mod tests { const OUTGOING_BUFFER: usize = 1; let (tx, _rx) = mpsc::channel(OUTGOING_BUFFER); FsWatchManager::new_with_file_watcher( - Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )), + Arc::new(OutgoingMessageSender::new(tx)), Arc::new(FileWatcher::noop()), ) } diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 0b1859f1..d3eb2e0d 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -50,7 +50,6 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; -use crate::analytics_utils::analytics_events_client_from_config; use crate::config_manager::ConfigManager; use crate::error_code::OVERLOADED_ERROR_CODE; use crate::error_code::internal_error; @@ -68,7 +67,6 @@ use crate::transport::CHANNEL_CAPACITY; use crate::transport::OutboundConnectionState; use crate::transport::route_outgoing_envelope; pub use bootstrap::EmbeddedNetworkPolicy; -use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::AgentMessageDelivery; use codex_app_server_protocol::ClientNotification; use codex_app_server_protocol::ClientRequest; @@ -104,8 +102,8 @@ mod bootstrap; const IN_PROCESS_CONNECTION_ID: ConnectionId = ConnectionId(0); const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); -// Covers both bounded runtime drains plus the analytics client's 25-second best-effort flush. -const SHUTDOWN_ACK_TIMEOUT: Duration = Duration::from_secs(35); +// Covers both bounded runtime drains with some margin. +const SHUTDOWN_ACK_TIMEOUT: Duration = Duration::from_secs(15); /// Default bounded channel capacity for in-process runtime queues. pub const DEFAULT_IN_PROCESS_CHANNEL_CAPACITY: usize = CHANNEL_CAPACITY; @@ -465,17 +463,10 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult IoResult IoResult IoResult done_tx, - _ => panic!("expected in-process shutdown request"), - }; - tokio::time::sleep(SHUTDOWN_TIMEOUT + SHUTDOWN_TIMEOUT + Duration::from_secs(24)).await; - runtime_completed.store(true, Ordering::Release); - let _ = done_tx.send(()); - }); - let client = InProcessClientHandle { - client: InProcessClientSender { client_tx }, - event_rx, - runtime_handle, - _test_codex_home: None, - }; - - client - .shutdown() - .await - .expect("in-process runtime should shutdown cleanly"); - assert!(completed.load(Ordering::Acquire)); - } - #[test] fn guaranteed_delivery_helpers_cover_required_server_notifications() { assert!(server_notification_requires_delivery( diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 882e3b9b..84be5c06 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -23,7 +23,6 @@ use std::sync::Arc; use std::sync::RwLock; use std::sync::atomic::AtomicBool; -use crate::analytics_utils::analytics_events_client_from_config; use crate::config_manager::ConfigManager; use crate::connection_cleanup::ConnectionCleanupTasks; use crate::message_processor::MessageProcessor; @@ -48,7 +47,6 @@ use crate::transport::start_control_socket_acceptor; use crate::transport::start_remote_control; use crate::transport::start_stdio_connection; use crate::transport::start_websocket_acceptor; -use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::ServerNotification; @@ -98,14 +96,12 @@ fn is_unsupported_untrusted_approval_policy_error(err: &std::io::Error) -> bool pub use codex_agent_message_board_host::delete_agent_message_boards; pub use codex_agent_message_board_host::install_agent_message_board; -mod analytics_utils; mod app_server_tracing; mod attestation; mod auth_mode; mod bespoke_event_handling; #[doc(hidden)] mod code_mode_host; -mod codex_home_metrics; mod command_exec; mod config_layer; mod startup_config; @@ -140,7 +136,6 @@ mod models; mod models_refresh_worker; mod notification_media; mod otel_config; -mod otel_reloader; mod outgoing_message; mod plugin_config_reload; mod request_processors; @@ -167,7 +162,6 @@ pub use crate::transport::take_remote_control_disabled_env; pub use crate::transport::verified_local_daemon_socket; const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT"; -const OTEL_SERVICE_NAME: &str = "codex-app-server"; #[cfg(debug_assertions)] const TEST_USER_CONFIG_FILE_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE"; @@ -452,14 +446,12 @@ pub async fn run_main( cli_config_overrides: CliConfigOverrides, loader_overrides: LoaderOverrides, strict_config: bool, - default_analytics_enabled: bool, ) -> IoResult<()> { run_main_with_transport_options( arg0_paths, cli_config_overrides, loader_overrides, strict_config, - default_analytics_enabled, AppServerTransport::Stdio, SessionSource::VSCode, WebsocketAuthSettings::default(), @@ -513,7 +505,6 @@ pub async fn run_main_with_transport_options( cli_config_overrides: CliConfigOverrides, loader_overrides: LoaderOverrides, strict_config: bool, - default_analytics_enabled: bool, transport: AppServerTransport, session_source: SessionSource, auth: WebsocketAuthSettings, @@ -649,20 +640,6 @@ pub async fn run_main_with_transport_options( .map(Arc::new) .map_err(std::io::Error::other)?; - let otel = codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - Some(OTEL_SERVICE_NAME), - default_analytics_enabled, - ) - .map_err(|e| { - std::io::Error::new( - ErrorKind::InvalidData, - format!("error loading otel config: {e}"), - ) - })?; - codex_core::otel_init::record_process_start(otel.as_ref(), OTEL_SERVICE_NAME); - codex_core::otel_init::install_sqlite_telemetry(otel.as_ref(), OTEL_SERVICE_NAME); let unix_socket_startup_lock = match &transport { AppServerTransport::UnixSocket { .. } => { let startup_lock_path = app_server_startup_lock_path(&codex_home)?; @@ -721,15 +698,7 @@ pub async fn run_main_with_transport_options( .features .enabled(Feature::RuntimeAgentInstances) .then(codex_runtime_agent_instance::RuntimeAuthSlot::default); - let analytics_events_client = analytics_events_client_from_config( - Arc::clone(&auth_manager), - &config, - runtime_auth_slot.clone(), - ); - let outgoing_message_sender = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - analytics_events_client.clone(), - )); + let outgoing_message_sender = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let feedback = CodexFeedback::new(); // Install a simple subscriber so `tracing` output is visible. Users can @@ -765,13 +734,11 @@ pub async fn run_main_with_transport_options( let log_db_layer = log_db .clone() .map(|layer| layer.with_filter(log_db::default_filter())); - let (otel_layers, otel_logger_reload_handle) = otel_reloader::layers(otel.as_ref()); let _ = tracing_subscriber::registry() .with(stderr_fmt) .with(feedback_layer) .with(feedback_metadata_layer) .with(log_db_layer) - .with(otel_layers) .try_init(); #[cfg(unix)] if let Some(Err(err)) = nofile_limit_result { @@ -937,20 +904,6 @@ pub async fn run_main_with_transport_options( } transport_accept_handles.push(remote_control_accept_handle); - // Only the standalone server measures its local home, not embedded/cloud runtimes. - if let Some(metrics) = otel.as_ref().and_then(codex_otel::OtelProvider::metrics) { - codex_home_metrics::spawn(&config, metrics.clone(), transport_shutdown_token.clone()); - } - - let otel_reloader_handle = otel_reloader::spawn( - otel, - otel_logger_reload_handle, - config_manager.clone(), - Arc::clone(&auth_manager), - default_analytics_enabled, - transport_shutdown_token.clone(), - ); - let outbound_handle = tokio::spawn(async move { let mut outbound_connections = HashMap::::new(); loop { @@ -1021,7 +974,6 @@ pub async fn run_main_with_transport_options( let mut processor = MessageProcessor::new(MessageProcessorArgs { cloud_skill_provider, outgoing: outgoing_message_sender, - analytics_events_client, arg0_paths, config: Arc::new(config), startup_cwd, @@ -1040,7 +992,6 @@ pub async fn run_main_with_transport_options( runtime_auth_slot, installation_id, code_mode_session_provider, - rpc_transport: analytics_rpc_transport(&transport), remote_control_handle: Some(remote_control_handle.clone()), plugin_startup_tasks: matches!( runtime_options.plugin_startup_tasks, @@ -1412,7 +1363,6 @@ pub async fn run_main_with_transport_options( let _ = outbound_handle.await; transport_shutdown_token.cancel(); - let _ = otel_reloader_handle.await; for handle in transport_accept_handles { let _ = handle.await; } @@ -1580,15 +1530,6 @@ fn loader_overrides_with_test_user_config_file( Ok(loader_overrides) } -fn analytics_rpc_transport(transport: &AppServerTransport) -> AppServerRpcTransport { - match transport { - AppServerTransport::Stdio => AppServerRpcTransport::Stdio, - AppServerTransport::UnixSocket { .. } - | AppServerTransport::WebSocket { .. } - | AppServerTransport::Off => AppServerRpcTransport::Websocket, - } -} - #[cfg(test)] #[path = "lib_tests.rs"] mod tests; diff --git a/codex-rs/app-server/src/log_write_warning_tests.rs b/codex-rs/app-server/src/log_write_warning_tests.rs index cbccc8d6..0f5bafac 100644 --- a/codex-rs/app-server/src/log_write_warning_tests.rs +++ b/codex-rs/app-server/src/log_write_warning_tests.rs @@ -1,7 +1,6 @@ use super::*; use crate::outgoing_message::OutgoingEnvelope; use crate::outgoing_message::OutgoingMessage; -use codex_analytics::AnalyticsEventsClient; use codex_core::config::ConfigBuilder; use codex_feedback::CodexFeedback; use codex_state::LogWriteFailureReporter; @@ -20,10 +19,7 @@ async fn log_write_warning_is_broadcast_once() -> anyhow::Result<()> { config.feedback_enabled = feedback_enabled; let feedback = CodexFeedback::new(); let (tx, mut rx) = mpsc::channel(/*buffer*/ 4); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config); reporter.report_failure("SQLite flush failed"); let OutgoingEnvelope::Broadcast { @@ -69,10 +65,7 @@ async fn log_write_warning_keeps_feedback_when_sender_is_gone() -> anyhow::Resul .await?; let feedback = CodexFeedback::new(); let (tx, mut rx) = mpsc::channel(/*buffer*/ 4); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config); drop(outgoing); reporter.report_failure("SQLite flush failed"); @@ -113,10 +106,7 @@ async fn log_write_warning_reports_failed_sqlite_flush() -> anyhow::Result<()> { ) .await?; let (tx, mut rx) = mpsc::channel(/*buffer*/ 4); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let reporter = LogWriteWarningReporter::new(feedback.clone(), &outgoing, &config); let initial_reporter: Arc = if attach_after_failure { Arc::new(feedback.clone()) diff --git a/codex-rs/app-server/src/main.rs b/codex-rs/app-server/src/main.rs index f87d0ca0..23e24a5e 100644 --- a/codex-rs/app-server/src/main.rs +++ b/codex-rs/app-server/src/main.rs @@ -118,7 +118,6 @@ fn main() -> anyhow::Result<()> { config_overrides, loader_overrides, strict_config, - /*default_analytics_enabled*/ false, transport, session_source, auth, diff --git a/codex-rs/app-server/src/mcp_refresh.rs b/codex-rs/app-server/src/mcp_refresh.rs index 64325f25..2b0ba4ea 100644 --- a/codex-rs/app-server/src/mcp_refresh.rs +++ b/codex-rs/app-server/src/mcp_refresh.rs @@ -555,7 +555,6 @@ enabled = false event_sink: Arc::new(NoopExtensionEventSink), auth_manager: auth_manager.clone(), state_db: Some(state_db.clone()), - analytics_events_client: codex_analytics::AnalyticsEventsClient::disabled(), thread_manager: thread_manager.clone(), goal_service: Arc::new(codex_goal_extension::GoalService::new()), environment_manager: Arc::clone(&environment_manager), @@ -567,7 +566,6 @@ enabled = false Arc::new(CodexHomeUserInstructionsProvider::new( good_config.codex_home.clone(), )), - /*analytics_events_client*/ None, codex_core::passthrough_image_store(), Arc::clone(&thread_store), codex_core::local_agent_graph_store_from_state_db(Some(&state_db)), diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 119b6457..6779e7cb 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -60,8 +60,6 @@ use crate::thread_state::ConnectionCapabilities; use crate::thread_state::ThreadStateManager; use crate::transport::AppServerTransport; use crate::transport::RemoteControlHandle; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::ClientNotification; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::ClientResponsePayload; @@ -258,7 +256,6 @@ impl ConnectionSessionState { pub(crate) struct MessageProcessorArgs { pub(crate) cloud_skill_provider: Option>, pub(crate) outgoing: Arc, - pub(crate) analytics_events_client: AnalyticsEventsClient, pub(crate) arg0_paths: Arg0DispatchPaths, pub(crate) config: Arc, /// Original project context, retained even when startup falls back to defaults. @@ -276,7 +273,6 @@ pub(crate) struct MessageProcessorArgs { pub(crate) user_verification: Arc, pub(crate) installation_id: String, pub(crate) code_mode_session_provider: Option>, - pub(crate) rpc_transport: AppServerRpcTransport, pub(crate) remote_control_handle: Option, /// `None` skips startup tasks; otherwise preserve the initial config-loading path. pub(crate) plugin_startup_tasks: Option, @@ -289,7 +285,6 @@ impl MessageProcessor { let MessageProcessorArgs { cloud_skill_provider, outgoing, - analytics_events_client, arg0_paths, config, startup_cwd, @@ -306,7 +301,6 @@ impl MessageProcessor { user_verification, installation_id, code_mode_session_provider, - rpc_transport, remote_control_handle, plugin_startup_tasks, } = args; @@ -390,7 +384,6 @@ impl MessageProcessor { event_sink: Arc::clone(&extension_event_sink), auth_manager: auth_manager.clone(), state_db: state_db.clone(), - analytics_events_client: analytics_events_client.clone(), thread_manager: thread_manager.clone(), goal_service: Arc::clone(&goal_service), environment_manager: Arc::clone(&environment_manager_for_extensions), @@ -403,7 +396,6 @@ impl MessageProcessor { Arc::new(CodexHomeUserInstructionsProvider::new( config.codex_home.clone(), )), - Some(analytics_events_client.clone()), codex_core::passthrough_image_store(), Arc::clone(&thread_store), codex_core::local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -424,7 +416,7 @@ impl MessageProcessor { }); let runtime_auth = thread_manager.runtime_auth_manager(); if let (Some(slot), Some(runtime)) = (runtime_auth_slot, &runtime_auth) { - // Analytics starts before the harness. Bind its requests to the harness registration. + // Bind runtime auth requests to the harness registration. slot.get_or_init(|| Arc::clone(runtime)); } let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new( @@ -434,9 +426,6 @@ impl MessageProcessor { Arc::clone(&thread_manager), )); let models_refresh_worker = crate::models_refresh_worker::spawn(&model_catalog); - thread_manager - .plugins_manager() - .set_analytics_events_client(analytics_events_client.clone()); let skills_watcher = SkillsWatcher::new( thread_manager.skills_service(), &config.codex_home, @@ -453,7 +442,6 @@ impl MessageProcessor { config_manager.clone(), thread_manager.clone(), Arc::clone(&model_catalog), - analytics_events_client.clone(), ); let on_effective_plugins_changed = crate::effective_plugin_change::effective_plugins_changed_callback( @@ -513,7 +501,6 @@ impl MessageProcessor { auth_manager.clone(), Arc::clone(&thread_manager), outgoing.clone(), - analytics_events_client.clone(), config_manager.clone(), on_effective_plugins_changed, ); @@ -562,7 +549,6 @@ impl MessageProcessor { let turn_processor = TurnRequestProcessor::new( Arc::clone(&thread_manager), outgoing.clone(), - analytics_events_client.clone(), Arc::clone(&config), config_manager.clone(), pending_thread_unloads, @@ -593,9 +579,7 @@ impl MessageProcessor { let initialize_processor = InitializeRequestProcessor::new( gateway_login_control, outgoing.clone(), - analytics_events_client.clone(), Arc::clone(&config), - rpc_transport, Arc::clone(&user_verification), ); let external_agent_config_processor = @@ -606,7 +590,6 @@ impl MessageProcessor { config_manager: config_manager.clone(), config_processor: config_processor.clone(), state_db, - analytics_events_client, arg0_paths, codex_home: config.codex_home.to_path_buf(), }); @@ -1025,11 +1008,6 @@ impl MessageProcessor { return Err(invalid_request(experimental_required_message(reason))); } let connection_id = connection_request_id.connection_id; - self.initialize_processor.track_initialized_request( - connection_id, - connection_request_id.request_id.clone(), - &codex_request, - ); let (turn_admission, recheck_turn_admission) = match &codex_request { ClientRequest::ThreadStart { .. } @@ -1681,9 +1659,9 @@ impl MessageProcessor { self.plugin_processor.plugin_share_delete(params).await } // ChatGPT apps/connectors are not available in aKode. - ClientRequest::AppsRead { .. } => Err(method_not_found( - "ChatGPT apps are not available in aKode", - )), + ClientRequest::AppsRead { .. } => { + Err(method_not_found("ChatGPT apps are not available in aKode")) + } ClientRequest::AppsList { .. } => Ok(Some( codex_app_server_protocol::AppsListResponse { data: Vec::new(), @@ -1691,11 +1669,9 @@ impl MessageProcessor { } .into(), )), - ClientRequest::AppsInstalled { .. } => { - Ok(Some( - codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(), - )) - } + ClientRequest::AppsInstalled { .. } => Ok(Some( + codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(), + )), ClientRequest::SkillsConfigWrite { params, .. } => { self.catalog_processor.skills_config_write(params).await } @@ -1999,9 +1975,6 @@ impl MessageProcessor { .process_resize_pty(request_id.clone(), params) .await } - ClientRequest::FeedbackUpload { params, .. } => { - self.feedback_processor.feedback_upload(params).await - } ClientRequest::FeedbackSave { params, .. } => { self.feedback_processor.feedback_save(params).await } diff --git a/codex-rs/app-server/src/message_processor_tracing_tests.rs b/codex-rs/app-server/src/message_processor_tracing_tests.rs index 9f85ed0b..bdd2d5b7 100644 --- a/codex-rs/app-server/src/message_processor_tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor_tracing_tests.rs @@ -1,7 +1,6 @@ use super::ConnectionSessionState; use super::MessageProcessor; use super::MessageProcessorArgs; -use crate::analytics_utils::analytics_events_client_from_config; use crate::config_manager::ConfigManager; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::OutgoingMessageSender; @@ -10,7 +9,6 @@ use crate::transport::AppServerTransport; use anyhow::Result; use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::write_mock_responses_config_toml; -use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::InitializeCapabilities; @@ -254,19 +252,10 @@ pub(super) async fn build_test_processor( Arg0DispatchPaths::default(), Arc::new(codex_config::NoopThreadConfigLoader), ); - let analytics_events_client = analytics_events_client_from_config( - Arc::clone(&auth_manager), - config.as_ref(), - /*runtime_auth_slot*/ None, - ); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - analytics_events_client.clone(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { cloud_skill_provider: None, outgoing, - analytics_events_client, arg0_paths: Arg0DispatchPaths::default(), startup_cwd: Some(config.cwd.to_path_buf()), config, @@ -285,7 +274,6 @@ pub(super) async fn build_test_processor( runtime_auth_slot: None, installation_id: "11111111-1111-4111-8111-111111111111".to_string(), code_mode_session_provider: None, - rpc_transport: AppServerRpcTransport::Stdio, remote_control_handle: None, plugin_startup_tasks: Some(PluginStartupConfig::Current), })); diff --git a/codex-rs/app-server/src/message_processor_workspace_routing_tests.rs b/codex-rs/app-server/src/message_processor_workspace_routing_tests.rs index 179b7989..72207a22 100644 --- a/codex-rs/app-server/src/message_processor_workspace_routing_tests.rs +++ b/codex-rs/app-server/src/message_processor_workspace_routing_tests.rs @@ -58,15 +58,10 @@ async fn background_routing_call_sites_skip_config(api_key: Option<&str>) -> any loader, ); let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16); - let analytics_events_client = AnalyticsEventsClient::disabled(); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - analytics_events_client.clone(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { cloud_skill_provider: None, outgoing, - analytics_events_client, arg0_paths: Arg0DispatchPaths::default(), startup_cwd: Some(config.cwd.to_path_buf()), config, @@ -85,7 +80,6 @@ async fn background_routing_call_sites_skip_config(api_key: Option<&str>) -> any runtime_auth_slot: None, installation_id: "11111111-1111-4111-8111-111111111111".to_string(), code_mode_session_provider: None, - rpc_transport: AppServerRpcTransport::Stdio, remote_control_handle: None, // Isolate routing from unrelated plugin startup configuration loads. plugin_startup_tasks: None, diff --git a/codex-rs/app-server/src/models_refresh_worker_tests.rs b/codex-rs/app-server/src/models_refresh_worker_tests.rs index 7355b343..df70d496 100644 --- a/codex-rs/app-server/src/models_refresh_worker_tests.rs +++ b/codex-rs/app-server/src/models_refresh_worker_tests.rs @@ -52,7 +52,6 @@ fn test_thread_manager( Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), codex_extension_api::empty_extension_registry(), Arc::new(codex_core::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, codex_core::passthrough_image_store(), codex_core::ThreadStoreBuilder::from_config(config, /*state_db*/ None).build(), /*agent_graph_store*/ None, diff --git a/codex-rs/app-server/src/otel_config.rs b/codex-rs/app-server/src/otel_config.rs index f9a19150..0d30f729 100644 --- a/codex-rs/app-server/src/otel_config.rs +++ b/codex-rs/app-server/src/otel_config.rs @@ -1,17 +1,12 @@ -//! Maps OTEL requirements and masks exporter credentials in app-server responses. +//! Maps local-logging OTEL requirements and masks legacy exporter credentials in +//! app-server responses. Telemetry exporters were removed; legacy exporter keys can +//! still appear in user config layers, so their header values stay redacted. -use codex_app_server_protocol::OtelExporter; -use codex_app_server_protocol::OtelHttpProtocol; use codex_app_server_protocol::OtelRequirements; -use codex_app_server_protocol::OtelTlsConfig; use codex_app_server_protocol::OtelToolResultLogConfig; use codex_app_server_protocol::SerdeRedactedString; use codex_config::OtelRequirementsToml; -use codex_config::types::OtelExporterKind; -use codex_config::types::OtelHttpProtocol as CoreOtelHttpProtocol; -use codex_config::types::OtelTlsConfig as CoreOtelTlsConfig; use serde_json::Value as JsonValue; -use std::collections::HashMap; pub(crate) fn map_otel_requirements_to_api(otel: OtelRequirementsToml) -> OtelRequirements { OtelRequirements { @@ -20,58 +15,6 @@ pub(crate) fn map_otel_requirements_to_api(otel: OtelRequirementsToml) -> OtelRe }), log_sse_deltas: otel.log_sse_deltas, log_user_prompt: otel.log_user_prompt, - log_agent_responses: otel.log_agent_responses, - log_guardian_assessments: otel.log_guardian_assessments, - environment: otel.environment, - exporter: otel.exporter.map(map_otel_exporter_to_api), - trace_exporter: otel.trace_exporter.map(map_otel_exporter_to_api), - metrics_exporter: otel.metrics_exporter.map(map_otel_exporter_to_api), - span_attributes: otel.span_attributes, - tracestate: otel.tracestate, - } -} - -fn map_otel_exporter_to_api(exporter: OtelExporterKind) -> OtelExporter { - let response_headers = |headers: HashMap| { - headers - .into_iter() - .map(|(name, value)| (name, SerdeRedactedString::from(value))) - .collect() - }; - match exporter { - OtelExporterKind::None => OtelExporter::None, - OtelExporterKind::Statsig => OtelExporter::Statsig, - OtelExporterKind::OtlpHttp { - endpoint, - headers, - protocol, - tls, - } => OtelExporter::OtlpHttp { - endpoint, - headers: response_headers(headers), - protocol: match protocol { - CoreOtelHttpProtocol::Binary => OtelHttpProtocol::Binary, - CoreOtelHttpProtocol::Json => OtelHttpProtocol::Json, - }, - tls: tls.map(map_otel_tls_to_api), - }, - OtelExporterKind::OtlpGrpc { - endpoint, - headers, - tls, - } => OtelExporter::OtlpGrpc { - endpoint, - headers: response_headers(headers), - tls: tls.map(map_otel_tls_to_api), - }, - } -} - -fn map_otel_tls_to_api(tls: CoreOtelTlsConfig) -> OtelTlsConfig { - OtelTlsConfig { - ca_certificate: tls.ca_certificate.map(Into::into), - client_certificate: tls.client_certificate.map(Into::into), - client_private_key: tls.client_private_key.map(Into::into), } } diff --git a/codex-rs/app-server/src/otel_reloader.rs b/codex-rs/app-server/src/otel_reloader.rs deleted file mode 100644 index 4ad302fc..00000000 --- a/codex-rs/app-server/src/otel_reloader.rs +++ /dev/null @@ -1,113 +0,0 @@ -use crate::OTEL_SERVICE_NAME; -use crate::config_manager::ConfigManager; -use codex_login::AuthManager; -use codex_otel::OtelProvider; -use std::sync::Arc; -use std::time::Duration; -use tokio::task::JoinHandle; -use tokio_util::sync::CancellationToken; -use tracing::Subscriber; -use tracing::info; -use tracing::warn; -use tracing_subscriber::Layer; -use tracing_subscriber::registry::LookupSpan; -use tracing_subscriber::reload; - -type OtelExportLayer = Option + Send + Sync + 'static>>; -type OtelReloadLayers = ( - Vec + Send + Sync + 'static>>, - reload::Handle, S>, -); - -pub(crate) fn layers(provider: Option<&OtelProvider>) -> OtelReloadLayers -where - S: Subscriber + for<'span> LookupSpan<'span> + Send + Sync + 'static, -{ - let logger_export_layer: OtelExportLayer = provider - .and_then(OtelProvider::logger_export_layer) - .map(Layer::boxed); - let (logger_layer, logger_handle) = reload::Layer::new(logger_export_layer); - - let layers: Vec + Send + Sync + 'static>> = vec![ - logger_layer - .with_filter(tracing_subscriber::filter::filter_fn( - OtelProvider::log_export_filter, - )) - .boxed(), - // The subscriber graph is fixed after startup. Keep the global tracer - // bridge installed even when tracing starts disabled so an account - // switch can install a trace exporter later. - OtelProvider::reloadable_tracing_layer(OTEL_SERVICE_NAME).boxed(), - ]; - (layers, logger_handle) -} - -pub(crate) fn spawn( - mut provider: Option, - logger_reload_handle: reload::Handle, S>, - config_manager: ConfigManager, - auth_manager: Arc, - default_analytics_enabled: bool, - shutdown_token: CancellationToken, -) -> JoinHandle<()> -where - S: Subscriber + for<'span> LookupSpan<'span> + Send + Sync + 'static, -{ - let mut auth_changes = auth_manager.auth_change_receiver(); - - tokio::spawn(async move { - loop { - tokio::select! { - _ = shutdown_token.cancelled() => break, - changed = auth_changes.changed() => { - if changed.is_err() { - break; - } - - // Account handlers install the new cloud loader after publishing auth changes. - tokio::time::sleep(Duration::from_millis(/*millis*/ 50)).await; - - let config = match config_manager.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - warn!(%error, "failed to reload telemetry config after account change"); - continue; - } - }; - let next_provider = match codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - Some(OTEL_SERVICE_NAME), - default_analytics_enabled, - ) { - Ok(provider) => provider, - Err(error) => { - warn!(%error, "failed to rebuild telemetry exporters after account change"); - continue; - } - }; - if let Err(error) = logger_reload_handle.reload( - next_provider - .as_ref() - .and_then(OtelProvider::logger_export_layer) - .map(Layer::boxed), - ) { - warn!(%error, "failed to install telemetry exporters after account change"); - continue; - } - if let Some(previous_provider) = std::mem::replace(&mut provider, next_provider) { - drop(tokio::task::spawn_blocking(move || previous_provider.shutdown())); - } - info!( - event.name = "codex.app_server.otel_reloaded", - "reloaded telemetry exporters after account change" - ); - } - } - } - - if let Some(provider) = provider { - let _ = tokio::task::spawn_blocking(move || provider.shutdown()).await; - } - }) -} diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index e1a0151e..c43da523 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -7,7 +7,6 @@ use std::sync::atomic::Ordering; use std::time::SystemTime; use std::time::UNIX_EPOCH; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ClientResponsePayload; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::RequestId; @@ -17,13 +16,11 @@ use codex_app_server_protocol::ServerNotificationEnvelope; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::ServerRequestResolvedNotification; -use codex_app_server_protocol::ServerResponse; use codex_diagnostics::Gauge; use codex_diagnostics::GaugeGuard; use codex_otel::span_w3c_trace_context; use codex_protocol::ThreadId; use codex_protocol::protocol::W3cTraceContext; -use codex_protocol::request_permissions::RequestPermissionsResponse; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; @@ -146,7 +143,6 @@ pub(crate) struct OutgoingMessageSender { /// We keep them here because this is where responses, errors, and /// disconnect cleanup all get handled. request_contexts: Mutex>, - analytics_events_client: AnalyticsEventsClient, } #[derive(Clone)] @@ -193,30 +189,7 @@ impl ThreadScopedOutgoingMessageSender { .await } - pub(crate) fn track_effective_permissions_approval_response( - &self, - request_id: RequestId, - response: RequestPermissionsResponse, - ) { - self.outgoing - .analytics_events_client - .track_effective_permissions_approval_response( - now_unix_timestamp_ms(), - request_id, - response, - ); - } - - pub(crate) fn track_realtime_session_updated(&self, realtime_session_id: String) { - self.outgoing - .analytics_events_client - .track_realtime_session_updated(self.thread_id.to_string(), realtime_session_id); - } - pub(crate) async fn send_server_notification(&self, notification: ServerNotification) { - self.outgoing - .analytics_events_client - .track_notification(¬ification); if self.connection_ids.is_empty() { return; } @@ -266,10 +239,7 @@ impl ThreadScopedOutgoingMessageSender { } impl OutgoingMessageSender { - pub(crate) fn new( - sender: mpsc::Sender, - analytics_events_client: AnalyticsEventsClient, - ) -> Self { + pub(crate) fn new(sender: mpsc::Sender) -> Self { Self { verification_auth: OnceLock::new(), verification_connections: Mutex::new(HashSet::new()), @@ -279,7 +249,6 @@ impl OutgoingMessageSender { sender, request_id_to_callback: Mutex::new(HashMap::new()), request_contexts: Mutex::new(HashMap::new()), - analytics_events_client, } } @@ -502,9 +471,6 @@ impl OutgoingMessageSender { { send_error = Some(err); break; - } else { - self.analytics_events_client - .track_server_request(connection_id.0, request.clone()); } } match send_error { @@ -570,15 +536,10 @@ impl OutgoingMessageSender { match entry { Some((id, entry)) => { - let completed_at_ms = now_unix_timestamp_ms(); if entry.verification_owner.is_none() && let Ok(response) = entry.request.response_from_result(result.clone()) { tracing::info!("<- response: {response:?}"); - if !matches!(response, ServerResponse::PermissionsRequestApproval { .. }) { - self.analytics_events_client - .track_server_response(completed_at_ms, response); - } } if entry.callback.send(Ok(result)).is_err() { warn!("could not notify callback for {id:?}: receiver dropped"); @@ -602,8 +563,6 @@ impl OutgoingMessageSender { Some((id, entry)) => { // Don't log error messages or data because they may contain credentials. warn!(code = error.code, "client responded with error for {id:?}"); - self.analytics_events_client - .track_server_request_aborted(now_unix_timestamp_ms(), id.clone()); if entry.callback.send(Err(error)).is_err() { warn!("could not notify callback for {id:?}: receiver dropped"); } @@ -615,14 +574,7 @@ impl OutgoingMessageSender { } pub(crate) async fn cancel_request(&self, id: &RequestId) -> bool { - let entry = self.take_request_callback(id).await; - if let Some((request_id, _entry)) = entry { - self.analytics_events_client - .track_server_request_aborted(now_unix_timestamp_ms(), request_id); - true - } else { - false - } + self.take_request_callback(id).await.is_some() } pub(crate) async fn cancel_all_requests(&self, error: Option) { @@ -635,8 +587,6 @@ impl OutgoingMessageSender { }; for entry in entries { - self.analytics_events_client - .track_server_request_aborted(now_unix_timestamp_ms(), entry.request.id().clone()); if let Some(error) = error.as_ref() && entry.callback.send(Err(error.clone())).is_err() { @@ -725,8 +675,6 @@ impl OutgoingMessageSender { }; for entry in entries { - self.analytics_events_client - .track_server_request_aborted(now_unix_timestamp_ms(), entry.request.id().clone()); if let Some(error) = error.as_ref() && entry.callback.send(Err(error.clone())).is_err() { @@ -740,19 +688,7 @@ impl OutgoingMessageSender { where T: Into, { - self.send_response_as_inner(request_id, response.into(), /*thread_originator*/ None) - .await; - } - - pub(crate) async fn send_response_with_thread_originator( - &self, - request_id: ConnectionRequestId, - response: T, - thread_originator: String, - ) where - T: Into, - { - self.send_response_as_inner(request_id, response.into(), Some(thread_originator)) + self.send_response_as_inner(request_id, response.into()) .await; } @@ -761,8 +697,7 @@ impl OutgoingMessageSender { request_id: ConnectionRequestId, response: ClientResponsePayload, ) { - self.send_response_as_inner(request_id, response, /*thread_originator*/ None) - .await; + self.send_response_as_inner(request_id, response).await; } /// Revalidates a sensitive result after reserving queue capacity, with no @@ -780,17 +715,10 @@ impl OutgoingMessageSender { return; }; let message = match check() { - Ok(()) => { - self.analytics_events_client.track_response( - request_id.connection_id.0, - request_id.request_id.clone(), - &response, - ); - OutgoingMessage::Response(OutgoingResponse { - id: request_id.request_id, - result: Box::new(response), - }) - } + Ok(()) => OutgoingMessage::Response(OutgoingResponse { + id: request_id.request_id, + result: Box::new(response), + }), Err(error) => OutgoingMessage::Error(OutgoingError { id: request_id.request_id, error, @@ -807,28 +735,8 @@ impl OutgoingMessageSender { &self, request_id: ConnectionRequestId, response: ClientResponsePayload, - thread_originator: Option, ) { let connection_id = request_id.connection_id; - let request_id_for_analytics = request_id.request_id.clone(); - match thread_originator { - Some(thread_originator) => { - self.analytics_events_client - .track_response_with_thread_originator( - connection_id.0, - request_id_for_analytics, - &response, - thread_originator, - ); - } - None => { - self.analytics_events_client.track_response( - connection_id.0, - request_id_for_analytics, - &response, - ); - } - } let response = Box::new(response); let request_context = self.take_request_context(&request_id).await; let outgoing_message = OutgoingMessage::Response(OutgoingResponse { @@ -845,15 +753,6 @@ impl OutgoingMessageSender { } pub(crate) async fn send_server_notification(&self, notification: ServerNotification) { - if matches!( - notification, - ServerNotification::ThreadArchived(_) - | ServerNotification::ThreadClosed(_) - | ServerNotification::ThreadUnarchived(_) - ) { - self.analytics_events_client - .track_notification(¬ification); - } self.send_server_notification_to_connections(&[], notification) .await; } @@ -1369,8 +1268,7 @@ mod tests { #[tokio::test] async fn send_response_routes_to_target_connection() { let (tx, mut rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let request_id = ConnectionRequestId { connection_id: ConnectionId(42), request_id: RequestId::Integer(7), @@ -1413,8 +1311,7 @@ mod tests { #[tokio::test] async fn send_response_clears_registered_request_context() { let (tx, _rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let request_id = ConnectionRequestId { connection_id: ConnectionId(42), request_id: RequestId::Integer(7), @@ -1445,8 +1342,7 @@ mod tests { #[tokio::test] async fn send_error_routes_to_target_connection() { let (tx, mut rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let request_id = ConnectionRequestId { connection_id: ConnectionId(9), request_id: RequestId::Integer(3), @@ -1486,8 +1382,7 @@ mod tests { vec![ConnectionId(1), ConnectionId(2)], ] { let (tx, mut rx) = mpsc::channel::(2); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let notification = ServerNotification::ConfigWarning(ConfigWarningNotification { summary: "test".to_string(), details: None, @@ -1542,8 +1437,7 @@ mod tests { #[tokio::test] async fn send_server_notification_to_connection_and_wait_tracks_write_completion() { let (tx, mut rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let send_task = tokio::spawn(async move { outgoing .send_server_notification_to_connection_and_wait( @@ -1594,8 +1488,7 @@ mod tests { #[tokio::test] async fn connection_closed_clears_registered_request_contexts() { let (tx, _rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let closed_connection_request = ConnectionRequestId { connection_id: ConnectionId(9), request_id: RequestId::Integer(3), @@ -1631,8 +1524,7 @@ mod tests { #[tokio::test] async fn notify_client_error_forwards_error_to_waiter() { let (tx, _rx) = mpsc::channel::(4); - let outgoing = - OutgoingMessageSender::new(tx, codex_analytics::AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let (request_id, wait_for_result) = outgoing .send_request(ServerRequestPayload::ApplyPatchApproval( @@ -1662,10 +1554,7 @@ mod tests { #[tokio::test] async fn pending_requests_for_thread_returns_thread_requests_in_request_id_order() { let (tx, _rx) = mpsc::channel::(8); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let thread_id = ThreadId::new(); let thread_outgoing = ThreadScopedOutgoingMessageSender::new( outgoing.clone(), @@ -1726,10 +1615,7 @@ mod tests { #[tokio::test] async fn cancel_requests_for_thread_cancels_all_thread_requests() { let (tx, _rx) = mpsc::channel::(8); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); let thread_id = ThreadId::new(); let thread_outgoing = ThreadScopedOutgoingMessageSender::new( outgoing.clone(), diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 76cc71b2..4a4dded9 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -15,10 +15,6 @@ use crate::thread_status::ThreadWatchManager; use crate::thread_status::resolve_thread_status; use chrono::Duration as ChronoDuration; use chrono::SecondsFormat; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::AnalyticsJsonRpcError; -use codex_analytics::InputError; -use codex_analytics::TurnSteerRequestError; use codex_app_server_protocol::Account; use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AccountUpdatedNotification; @@ -33,7 +29,6 @@ use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::ClientResponsePayload; use codex_app_server_protocol::CodexErrorInfo; use codex_app_server_protocol::CollaborationModeListParams; @@ -61,8 +56,7 @@ use codex_app_server_protocol::ExperimentalFeature as ApiExperimentalFeature; use codex_app_server_protocol::ExperimentalFeatureListParams; use codex_app_server_protocol::ExperimentalFeatureListResponse; use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatureStage; -use codex_app_server_protocol::FeedbackUploadParams; -use codex_app_server_protocol::FeedbackUploadResponse; +use codex_app_server_protocol::FeedbackReportParams; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAccountResponse; use codex_app_server_protocol::GetAuthStatusParams; @@ -354,7 +348,7 @@ use codex_features::Feature; use codex_features::Stage; use codex_feedback::CodexFeedback; use codex_feedback::FeedbackAttachmentPath; -use codex_feedback::FeedbackUploadOptions; +use codex_feedback::FeedbackSaveOptions; use codex_git_utils::git_diff_to_remote; use codex_git_utils::resolve_root_git_project_for_trust; use codex_login::AuthManager; diff --git a/codex-rs/app-server/src/request_processors/account_processor/workspace_routing_tests.rs b/codex-rs/app-server/src/request_processors/account_processor/workspace_routing_tests.rs index 187084e2..ed495c66 100644 --- a/codex-rs/app-server/src/request_processors/account_processor/workspace_routing_tests.rs +++ b/codex-rs/app-server/src/request_processors/account_processor/workspace_routing_tests.rs @@ -94,10 +94,7 @@ async fn background_routing_skips_config_until_chatgpt_sign_in( ), ); let (sender, _receiver) = tokio::sync::mpsc::channel(16); - let outgoing = Arc::new(OutgoingMessageSender::new( - sender, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(sender)); let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new( manager.clone(), Some(config.cwd.to_path_buf()), diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index ddf39d97..f5bb30fe 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -9,7 +9,6 @@ use crate::model_catalog::ModelCatalog; use crate::otel_config::map_otel_requirements_to_api; use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::AllowDenyRequirement; use codex_app_server_protocol::AutoReviewRequirements; use codex_app_server_protocol::BrowserUseAccessApprovalLifetime; @@ -57,7 +56,6 @@ use codex_features::Feature; use codex_features::canonical_feature_for_key; use codex_features::feature_for_key; use codex_model_provider::create_model_provider; -use codex_plugin::PluginId; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::WebSearchMode; use serde_json::json; @@ -89,7 +87,6 @@ pub(crate) struct ConfigRequestProcessor { config_manager: ConfigManager, thread_manager: Arc, model_catalog: Arc, - analytics_events_client: AnalyticsEventsClient, } impl ConfigRequestProcessor { @@ -98,14 +95,12 @@ impl ConfigRequestProcessor { config_manager: ConfigManager, thread_manager: Arc, model_catalog: Arc, - analytics_events_client: AnalyticsEventsClient, ) -> Self { Self { outgoing, config_manager, thread_manager, model_catalog, - analytics_events_client, } } @@ -283,35 +278,20 @@ impl ConfigRequestProcessor { &self, params: ConfigValueWriteParams, ) -> Result { - let pending_changes = codex_core_plugins::toggles::collect_plugin_enabled_candidates( - [(¶ms.key_path, ¶ms.value)].into_iter(), - ); - let response = self - .config_manager + self.config_manager .write_value(params) .await - .map_err(map_error)?; - self.emit_plugin_toggle_events(pending_changes).await; - Ok(response) + .map_err(map_error) } async fn batch_write_inner( &self, params: ConfigBatchWriteParams, ) -> Result { - let pending_changes = codex_core_plugins::toggles::collect_plugin_enabled_candidates( - params - .edits - .iter() - .map(|edit| (&edit.key_path, &edit.value)), - ); - let response = self - .config_manager + self.config_manager .batch_write(params) .await - .map_err(map_error)?; - self.emit_plugin_toggle_events(pending_changes).await; - Ok(response) + .map_err(map_error) } async fn set_experimental_feature_enablement( @@ -367,26 +347,6 @@ impl ConfigRequestProcessor { Ok(ExperimentalFeatureEnablementSetResponse { enablement }) } - - async fn emit_plugin_toggle_events( - &self, - pending_changes: std::collections::BTreeMap, - ) { - let plugins_manager = self.thread_manager.plugins_manager(); - for (plugin_id, enabled) in pending_changes { - let Ok(plugin_id) = PluginId::parse(&plugin_id) else { - continue; - }; - let metadata = plugins_manager - .telemetry_metadata_for_installed_plugin(&plugin_id) - .await; - if enabled { - self.analytics_events_client.track_plugin_enabled(metadata); - } else { - self.analytics_events_client.track_plugin_disabled(metadata); - } - } - } } pub(super) async fn reload_user_config( diff --git a/codex-rs/app-server/src/request_processors/feedback_doctor_report.rs b/codex-rs/app-server/src/request_processors/feedback_doctor_report.rs index b01e490b..4648075a 100644 --- a/codex-rs/app-server/src/request_processors/feedback_doctor_report.rs +++ b/codex-rs/app-server/src/request_processors/feedback_doctor_report.rs @@ -2,7 +2,7 @@ //! //! Feedback upload should never depend on doctor succeeding. This module runs //! the configured Codex executable as a subprocess, accepts only valid JSON from -//! `codex doctor --json --feedback`, derives a small set of Sentry tags, and otherwise +//! `codex doctor --json --feedback`, derives a small set of report tags, and otherwise //! skips the attachment with a warning. Keeping the report generation out of the //! app-server process avoids sharing doctor internals across crates while still //! using the CLI's JSON report format with bounded database scans. @@ -29,7 +29,7 @@ const MAX_DOCTOR_TAG_VALUE_LEN: usize = 256; pub(crate) struct DoctorFeedbackReport { /// JSON support report to upload as `codex-doctor-report.json`. pub(crate) attachment: FeedbackAttachment, - /// Low-cardinality Sentry tags derived from the report status and check ids. + /// Low-cardinality report tags derived from the report status and check ids. pub(crate) tags: BTreeMap, } diff --git a/codex-rs/app-server/src/request_processors/feedback_processor.rs b/codex-rs/app-server/src/request_processors/feedback_processor.rs index 297a405b..c8b31182 100644 --- a/codex-rs/app-server/src/request_processors/feedback_processor.rs +++ b/codex-rs/app-server/src/request_processors/feedback_processor.rs @@ -21,6 +21,11 @@ use sha2::Sha256; use std::path::Path; use tokio::sync::Semaphore; +struct SavedFeedback { + thread_id: String, + prompt_hash: Option, +} + #[derive(Clone)] pub(crate) struct FeedbackRequestProcessor { auth_manager: Arc, @@ -29,7 +34,7 @@ pub(crate) struct FeedbackRequestProcessor { feedback: CodexFeedback, log_db: Option, state_db: Option, - uploads: Arc, + saves: Arc, } impl FeedbackRequestProcessor { @@ -48,24 +53,10 @@ impl FeedbackRequestProcessor { feedback, log_db, state_db, - uploads: Arc::new(Semaphore::new(/*permits*/ 3)), + saves: Arc::new(Semaphore::new(/*permits*/ 3)), } } - pub(crate) async fn feedback_upload( - &self, - params: FeedbackUploadParams, - ) -> Result, JSONRPCErrorError> { - if !self.config.feedback_enabled { - return Err(invalid_request( - "sending feedback is disabled by configuration", - )); - } - self.feedback_response(params, /*save_path*/ None) - .await - .map(|response| Some(response.into())) - } - pub(crate) async fn feedback_save( &self, params: FeedbackSaveParams, @@ -78,9 +69,7 @@ impl FeedbackRequestProcessor { let save_path = AbsolutePathBuf::try_from(params.save_path) .map_err(|error| invalid_request(format!("invalid feedback savePath: {error}")))?; let saved_path = LegacyAppPathString::from_abs_path(&save_path); - let response = self - .feedback_response(params.feedback, Some(save_path)) - .await?; + let response = self.feedback_response(params.feedback, save_path).await?; Ok(Some( FeedbackSaveResponse { saved_path, @@ -93,22 +82,22 @@ impl FeedbackRequestProcessor { async fn feedback_response( &self, - params: FeedbackUploadParams, - save_path: Option, - ) -> Result { + params: FeedbackReportParams, + save_path: AbsolutePathBuf, + ) -> Result { let permit = self - .uploads + .saves .clone() .try_acquire_owned() .map_err(|_| JSONRPCErrorError { code: OVERLOADED_ERROR_CODE, message: - "Three feedback uploads are already in progress; try again after one finishes" + "Three feedback saves are already in progress; try again after one finishes" .to_string(), data: None, })?; - let FeedbackUploadParams { + let FeedbackReportParams { classification, reason, thread_id, @@ -116,7 +105,7 @@ impl FeedbackRequestProcessor { extra_log_files, tags, } = params; - let mut upload_tags = tags.unwrap_or_default(); + let mut report_tags = tags.unwrap_or_default(); let conversation_id = match thread_id.as_deref() { Some(thread_id) => match ThreadId::from_string(thread_id) { @@ -126,23 +115,22 @@ impl FeedbackRequestProcessor { None => None, }; - let http_client_factory = self.config.http_client_factory(); let auth = self.auth_manager.auth_cached(); let turn_metadata = if let Some(conversation_id) = conversation_id && let Some(rollout_path) = self - .resolve_rollout_path(conversation_id, self.state_db.as_ref(), save_path.as_ref()) + .resolve_rollout_path(conversation_id, self.state_db.as_ref()) .await? { feedback_turn_metadata_from_rollout( &rollout_path, - upload_tags.get("turn_id").map(String::as_str), + report_tags.get("turn_id").map(String::as_str), ) .await } else { None }; - apply_feedback_turn_metadata(&mut upload_tags, turn_metadata); - let prompt_hash = upload_tags.get("prompt_hash").cloned(); + apply_feedback_turn_metadata(&mut report_tags, turn_metadata); + let prompt_hash = report_tags.get("prompt_hash").cloned(); if let Some(chatgpt_user_id) = auth .as_ref() @@ -230,11 +218,7 @@ impl FeedbackRequestProcessor { .flat_map(|index| &mut index.threads) { if let Some(rollout_path) = self - .resolve_rollout_path( - thread.thread_id, - state_db_ctx.as_ref(), - save_path.as_ref(), - ) + .resolve_rollout_path(thread.thread_id, state_db_ctx.as_ref()) .await? && seen_attachment_paths.insert(rollout_path.clone()) { @@ -259,10 +243,7 @@ impl FeedbackRequestProcessor { }); } } - if let Some(mut index) = feedback_index { - if save_path.is_some() { - index.rollout_archive_filename = None; - } + if let Some(index) = feedback_index { match index.attachment() { Ok(attachment) => extra_attachments.insert(0, attachment), Err(err) => warn!("failed to serialize feedback thread index: {err}"), @@ -309,7 +290,7 @@ impl FeedbackRequestProcessor { { extra_attachments.push(doctor_report.attachment); for (key, value) in doctor_report.tags { - upload_tags.entry(key).or_insert(value); + report_tags.entry(key).or_insert(value); } } extra_attachments.extend( @@ -322,23 +303,17 @@ impl FeedbackRequestProcessor { } let session_source = self.thread_manager.session_source(); - let runtime_handle = tokio::runtime::Handle::current(); let codex_home = self.config.codex_home.clone(); - let operation = if save_path.is_some() { - "save" - } else { - "upload" - }; - let upload_result = tokio::task::spawn_blocking(move || { - // Cancelling the RPC waiter must not release a still-running upload's slot. + let save_result = tokio::task::spawn_blocking(move || { + // Cancelling the RPC waiter must not release a still-running save's slot. let _permit = permit; if include_logs { extra_attachments .extend(codex_feedback::daemon_log_attachments(codex_home.as_path())); } - let tags = (!upload_tags.is_empty()).then_some(&upload_tags); - let options = FeedbackUploadOptions { + let tags = (!report_tags.is_empty()).then_some(&report_tags); + let options = FeedbackSaveOptions { classification: &classification, reason: reason.as_deref(), tags, @@ -348,27 +323,21 @@ impl FeedbackRequestProcessor { session_source: Some(session_source), logs_override: sqlite_feedback_logs, }; - match save_path { - Some(path) => snapshot.save_feedback(options, path.as_path()), - None => { - runtime_handle.block_on(snapshot.upload_feedback(options, &http_client_factory)) - } - } + snapshot.save_feedback(options, save_path.as_path()) }) .await; - let upload_result = match upload_result { + let save_result = match save_result { Ok(result) => result, Err(join_err) => { return Err(internal_error(format!( - "failed to {operation} feedback: {join_err}" + "failed to save feedback: {join_err}" ))); } }; - upload_result - .map_err(|err| internal_error(format!("failed to {operation} feedback: {err:#}")))?; - Ok(FeedbackUploadResponse { + save_result.map_err(|err| internal_error(format!("failed to save feedback: {err:#}")))?; + Ok(SavedFeedback { thread_id, prompt_hash, }) @@ -378,19 +347,13 @@ impl FeedbackRequestProcessor { &self, conversation_id: ThreadId, state_db_ctx: Option<&StateDbHandle>, - save_path: Option<&AbsolutePathBuf>, ) -> Result, JSONRPCErrorError> { if let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await { - if save_path.is_some() { - // Explicit extraLogFiles are collected separately and remain strict, even - // when they name this same not-yet-materialized automatic rollout. - return conversation.feedback_rollout_path().await.map_err(|error| { - internal_error(format!("failed to select feedback rollout: {error}")) - }); - } - if let Some(rollout_path) = conversation.rollout_path() { - return Ok(Some(rollout_path)); - } + // Explicit extraLogFiles are collected separately and remain strict, even + // when they name this same not-yet-materialized automatic rollout. + return conversation.feedback_rollout_path().await.map_err(|error| { + internal_error(format!("failed to select feedback rollout: {error}")) + }); } let Some(state_db_ctx) = state_db_ctx else { @@ -441,13 +404,13 @@ struct FeedbackTurnMetadata { } fn apply_feedback_turn_metadata( - upload_tags: &mut BTreeMap, + report_tags: &mut BTreeMap, turn_metadata: Option, ) { // These are reserved tags derived from the persisted rollout rather than // accepted from the feedback request. - upload_tags.remove("prompt_hash"); - upload_tags.remove("prompt_version"); + report_tags.remove("prompt_hash"); + report_tags.remove("prompt_version"); if let Some(FeedbackTurnMetadata { model, @@ -455,10 +418,10 @@ fn apply_feedback_turn_metadata( prompt_hash, }) = turn_metadata { - upload_tags.insert("model".to_string(), model); - upload_tags.insert("effort".to_string(), format!("{effort:?}")); + report_tags.insert("model".to_string(), model); + report_tags.insert("effort".to_string(), format!("{effort:?}")); if let Some(prompt_hash) = prompt_hash { - upload_tags.insert("prompt_hash".to_string(), prompt_hash); + report_tags.insert("prompt_hash".to_string(), prompt_hash); } } } @@ -649,7 +612,7 @@ mod tests { #[test] fn feedback_tags_drop_unverified_client_prompt_tags() { - let mut upload_tags = BTreeMap::from([ + let mut report_tags = BTreeMap::from([ ("custom".to_string(), "preserved".to_string()), ( "prompt_hash".to_string(), @@ -658,23 +621,23 @@ mod tests { ("prompt_version".to_string(), "client-prompt-v1".to_string()), ]); - apply_feedback_turn_metadata(&mut upload_tags, /*turn_metadata*/ None); + apply_feedback_turn_metadata(&mut report_tags, /*turn_metadata*/ None); assert_eq!( - upload_tags, + report_tags, BTreeMap::from([("custom".to_string(), "preserved".to_string())]) ); } #[test] fn feedback_tags_drop_client_prompt_hash_when_rollout_has_no_hash() { - let mut upload_tags = BTreeMap::from([( + let mut report_tags = BTreeMap::from([( "prompt_hash".to_string(), "unverified-client-hash".to_string(), )]); apply_feedback_turn_metadata( - &mut upload_tags, + &mut report_tags, Some(FeedbackTurnMetadata { model: "reported-model".to_string(), effort: Some(ReasoningEffort::High), @@ -683,7 +646,7 @@ mod tests { ); assert_eq!( - upload_tags, + report_tags, BTreeMap::from([ ("effort".to_string(), "Some(High)".to_string()), ("model".to_string(), "reported-model".to_string()), @@ -693,13 +656,13 @@ mod tests { #[test] fn feedback_tags_replace_client_prompt_hash_with_rollout_hash() { - let mut upload_tags = BTreeMap::from([( + let mut report_tags = BTreeMap::from([( "prompt_hash".to_string(), "unverified-client-hash".to_string(), )]); apply_feedback_turn_metadata( - &mut upload_tags, + &mut report_tags, Some(FeedbackTurnMetadata { model: "reported-model".to_string(), effort: Some(ReasoningEffort::High), @@ -708,7 +671,7 @@ mod tests { ); assert_eq!( - upload_tags, + report_tags, BTreeMap::from([ ("effort".to_string(), "Some(High)".to_string()), ("model".to_string(), "reported-model".to_string()), @@ -721,17 +684,17 @@ mod tests { async fn feedback_tags_do_not_trust_the_prompt_version_from_the_reported_rollout() { let (_tempdir, rollout_path) = feedback_rollout(&[("turn-1", "synthetic-model", Some(ReasoningEffort::High))]); - let mut upload_tags = BTreeMap::from([( + let mut report_tags = BTreeMap::from([( "prompt_version".to_string(), "unverified-client-prompt".to_string(), )]); let turn_metadata = feedback_turn_metadata_from_rollout(&rollout_path, Some("turn-1")).await; - apply_feedback_turn_metadata(&mut upload_tags, turn_metadata); + apply_feedback_turn_metadata(&mut report_tags, turn_metadata); assert_eq!( - upload_tags, + report_tags, BTreeMap::from([ ("effort".to_string(), "Some(High)".to_string()), ("model".to_string(), "synthetic-model".to_string()), diff --git a/codex-rs/app-server/src/request_processors/feedback_thread_index.rs b/codex-rs/app-server/src/request_processors/feedback_thread_index.rs index b3ec6e88..56f347e5 100644 --- a/codex-rs/app-server/src/request_processors/feedback_thread_index.rs +++ b/codex-rs/app-server/src/request_processors/feedback_thread_index.rs @@ -1,6 +1,6 @@ //! Selects a bounded set of spawned descendants and directly attached threads for feedback, //! preserving the reported thread and prioritizing children with retained failed reviews. -//! Filenames identify selected archive entries or fallback attachments. Delivery is best effort. +//! Filenames identify the rollout entries saved in the local feedback archive. use codex_feedback::FeedbackAttachment; use codex_feedback::GuardianReviewFailures; @@ -14,7 +14,6 @@ const MAX_LISTED_OMISSIONS: usize = 64; #[derive(Serialize)] pub(super) struct FeedbackThreadIndex { - pub(super) rollout_archive_filename: Option<&'static str>, pub threads: Vec, retained_failure_thread_ids: Vec, omitted_thread_ids: Vec, @@ -58,7 +57,6 @@ impl FeedbackThreadIndex { .take(MAX_LISTED_OMISSIONS) .collect::>(); Self { - rollout_archive_filename: Some("rollouts.tar.gz"), threads: thread_ids .into_iter() .map(|thread_id| FeedbackThread { @@ -71,7 +69,7 @@ impl FeedbackThreadIndex { unlisted_omitted_thread_count: omitted_count - omitted_thread_ids.len(), omitted_thread_ids, process_discarded_review_records: failures.process_discarded_records, - notes: "Selection only, not an upload receipt. Null filenames mean no path was available. \ + notes: "Selection only. Null filenames mean no path was available. \ Omitted threads exceeded the rollout thread limit; their retained reviews are \ still in auto-review-failures.jsonl. Review evidence is persisted and bounded; \ missing evidence does not imply no denial. The discarded-record count covers \ diff --git a/codex-rs/app-server/src/request_processors/feedback_thread_index_tests.rs b/codex-rs/app-server/src/request_processors/feedback_thread_index_tests.rs index 075bc69b..af5df192 100644 --- a/codex-rs/app-server/src/request_processors/feedback_thread_index_tests.rs +++ b/codex-rs/app-server/src/request_processors/feedback_thread_index_tests.rs @@ -28,7 +28,6 @@ fn old_failed_child_precedes_new_children_and_index_explains_selection() -> anyh assert_eq!( serde_json::from_slice::(&attachment.buffer)?, json!({ - "rollout_archive_filename": "rollouts.tar.gz", "threads": selected.into_iter().map(|i| json!({ "thread_id": ids[i], "rollout_filename": match i { diff --git a/codex-rs/app-server/src/request_processors/initialize_processor.rs b/codex-rs/app-server/src/request_processors/initialize_processor.rs index f6b282e7..efff5648 100644 --- a/codex-rs/app-server/src/request_processors/initialize_processor.rs +++ b/codex-rs/app-server/src/request_processors/initialize_processor.rs @@ -2,7 +2,6 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use axum::http::HeaderValue; -use codex_analytics::AppServerRpcTransport; use codex_login::default_client::SetOriginatorError; use codex_login::default_client::USER_AGENT_SUFFIX; use codex_login::default_client::get_codex_user_agent; @@ -23,9 +22,7 @@ pub(crate) struct InitializeRequestProcessor { gateway_login_control: Arc, gateway_login_initialized: Arc>, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config: Arc, - rpc_transport: AppServerRpcTransport, user_verification: Arc, } @@ -34,18 +31,14 @@ impl InitializeRequestProcessor { pub(crate) fn new( gateway_login_control: Arc, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config: Arc, - rpc_transport: AppServerRpcTransport, user_verification: Arc, ) -> Self { Self { gateway_login_control, gateway_login_initialized: Arc::new(std::sync::OnceLock::new()), outgoing, - analytics_events_client, config, - rpc_transport, user_verification, } } @@ -75,7 +68,6 @@ impl InitializeRequestProcessor { // shared thread when another connected client did not opt into // experimental API). Proposed direction is instance-global first-write-wins // with initialize-time mismatch rejection. - let analytics_initialize_params = params.clone(); let capabilities = params.capabilities.unwrap_or_default(); let experimental_api_enabled = capabilities.experimental_api; let request_attestation = capabilities.request_attestation; @@ -184,12 +176,6 @@ impl InitializeRequestProcessor { } } } - self.analytics_events_client.track_initialize( - connection_id.0, - analytics_initialize_params, - originator, - self.rpc_transport, - ); set_default_client_residency_requirement(self.config.enforce_residency.value()); if mutates_global_identity && let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() { *suffix = Some(user_agent_suffix); @@ -230,14 +216,4 @@ impl InitializeRequestProcessor { Ok(false) } - - pub(crate) fn track_initialized_request( - &self, - connection_id: ConnectionId, - request_id: RequestId, - request: &ClientRequest, - ) { - self.analytics_events_client - .track_request(connection_id.0, request_id, request); - } } diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index 62ca5e2b..d7cd7224 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -3,7 +3,6 @@ use super::*; use crate::error_code::internal_error; use crate::error_code::invalid_request; use crate::error_code::method_not_found; -use codex_analytics::PluginInstallSource; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginSharePrincipalRole; use codex_config::types::McpServerConfig; @@ -34,7 +33,6 @@ use codex_mcp::oauth_login_support; use codex_mcp::resolve_oauth_callback; use codex_mcp::should_retry_without_scopes; use codex_plugin::PluginId; -use codex_plugin::PluginTelemetryMetadata; use codex_protocol::auth::AuthMode as DomainAuthMode; use codex_rmcp_client::McpOAuthClientRegistration; use codex_rmcp_client::OAuthDiscoveryTimeout; @@ -60,7 +58,6 @@ pub(crate) struct PluginRequestProcessor { auth_manager: Arc, thread_manager: Arc, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config_manager: ConfigManager, on_effective_plugins_changed: Arc, @@ -326,7 +323,6 @@ impl PluginRequestProcessor { auth_manager: Arc, thread_manager: Arc, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config_manager: ConfigManager, on_effective_plugins_changed: Arc< dyn Fn(codex_core_plugins::EffectivePluginsChange) + Send + Sync, @@ -336,7 +332,6 @@ impl PluginRequestProcessor { auth_manager, thread_manager, outgoing, - analytics_events_client, config_manager, on_effective_plugins_changed, } @@ -1363,7 +1358,7 @@ impl PluginRequestProcessor { .as_ref() .map(|id| id.marketplace_name.as_str()) .unwrap_or(&remote_marketplace_name); - self.track_plugin_install_failed_for_remote_plugin( + self.log_remote_plugin_install_failure( &remote_plugin_id, marketplace, err.plugin_id.as_ref(), @@ -1378,17 +1373,6 @@ impl PluginRequestProcessor { let remote_detail = installation.detail; let result = installation.installed; - let plugin_metadata = self - .thread_manager - .plugins_manager() - .telemetry_metadata_for_installed_plugin_with_remote_id( - &result.plugin_id, - &remote_plugin_id, - ) - .await; - self.analytics_events_client - .track_plugin_installed(plugin_metadata); - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { Ok(mut reloaded_config) => { // Keep the policy captured with this installation's auth snapshot. @@ -1476,11 +1460,11 @@ impl PluginRequestProcessor { }) } - fn track_plugin_install_failed_for_remote_plugin( + fn log_remote_plugin_install_failure( &self, remote_plugin_id: &str, marketplace_name: &str, - plugin_id: Option<&PluginId>, + _plugin_id: Option<&PluginId>, error_type: &'static str, sub_error_type: Option, error_message: String, @@ -1493,23 +1477,6 @@ impl PluginRequestProcessor { error = %error_message, "remote plugin install failed" ); - let plugin = if let Some(plugin_id) = plugin_id { - self.thread_manager - .plugins_manager() - .telemetry_metadata_for_plugin_id_with_remote_id(plugin_id, remote_plugin_id) - } else { - PluginTelemetryMetadata { - plugin_id: None, - remote_plugin_id: Some(remote_plugin_id.to_string()), - capability_summary: None, - } - }; - self.analytics_events_client.track_plugin_install_failed( - plugin, - PluginInstallSource::Manual, - error_type.to_string(), - sub_error_type, - ); } /// ChatGPT apps never need auth in aKode: the hosted apps MCP server is never used. @@ -1784,8 +1751,6 @@ impl PluginRequestProcessor { ) .await .map_err(remote_plugin_operation_error_to_jsonrpc)?; - self.analytics_events_client - .track_plugin_uninstalled(outcome.telemetry); if outcome.effective_plugins_changed { self.on_effective_plugins_changed().await; } diff --git a/codex-rs/app-server/src/request_processors/process_exec_processor_tests.rs b/codex-rs/app-server/src/request_processors/process_exec_processor_tests.rs index 0b694b1d..206ab982 100644 --- a/codex-rs/app-server/src/request_processors/process_exec_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/process_exec_processor_tests.rs @@ -4,7 +4,6 @@ use super::*; use crate::outgoing_message::OutgoingEnvelope; use crate::outgoing_message::OutgoingMessage; -use codex_analytics::AnalyticsEventsClient; use pretty_assertions::assert_eq; fn start_collector( @@ -22,10 +21,7 @@ fn start_collector( output_rx, reader: None, process_exited, - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), stream: ProcessOutputStream::Stdout, stream_output: true, output_bytes_cap: None, @@ -128,10 +124,7 @@ async fn timed_out_stderr_closes_while_stdout_is_still_open() { output_rx: child.stderr_rx, reader: child.session.stderr_reader(), process_exited: process_exited.clone(), - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), stream: ProcessOutputStream::Stderr, stream_output: false, output_bytes_cap: Some(3), @@ -189,10 +182,7 @@ async fn windows_terminal_reports_exit_before_closing_the_console() { let (_control_tx, control_rx) = mpsc::channel(1); let (tx, mut notifications) = mpsc::channel(1); let process = tokio::spawn(run_process(RunProcessParams { - outgoing: Arc::new(OutgoingMessageSender::new( - tx, - AnalyticsEventsClient::disabled(), - )), + outgoing: Arc::new(OutgoingMessageSender::new(tx)), request_id: ConnectionRequestId { connection_id: ConnectionId(1), request_id: codex_app_server_protocol::RequestId::Integer(1), diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 70c292b4..f4027a12 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -1212,7 +1212,6 @@ pub(super) async fn handle_pending_thread_resume_request( workspace_roots, reasoning_effort, collaboration_mode, - originator, .. } = config_snapshot; let instruction_sources = pending.instruction_sources; @@ -1241,9 +1240,7 @@ pub(super) async fn handle_pending_thread_resume_request( turns_backwards_cursor, items_backwards_cursor, }; - outgoing - .send_response_with_thread_originator(request_id, response, originator) - .await; + outgoing.send_response(request_id, response).await; // Warm metadata-only resumes skip history reconstruction. Cold paginated children can // replay usage using attribution captured before the listener was attached. if let Some(token_usage_turn_id) = token_usage_turn_id { diff --git a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs index 116a0adc..3e069027 100644 --- a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs @@ -15,7 +15,6 @@ use crate::thread_state::PendingNetworkApproval; use crate::thread_state::resolve_server_request_on_thread_listener; use anyhow::Context; use anyhow::Result; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ClientResponsePayload; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadResumeParams; @@ -54,10 +53,7 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers( let config_manager = ConfigManager::without_managed_config_for_tests(config.codex_home.to_path_buf()); let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_state_manager = ThreadStateManager::new(); let thread_watch_manager = ThreadWatchManager::new_with_outgoing(outgoing.clone()); let skills_watcher = SkillsWatcher::new( diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index ce6eb92f..7f158b93 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1752,7 +1752,6 @@ impl ThreadRequestProcessor { let cwd = config_snapshot.cwd().clone(); let active_permission_profile = thread_response_active_permission_profile(config_snapshot.active_permission_profile); - let thread_originator = config_snapshot.originator.clone(); let response = ThreadStartResponse { thread: thread.clone(), @@ -1773,7 +1772,7 @@ impl ThreadRequestProcessor { let notif = thread_started_notification(thread); listener_task_context .outgoing - .send_response_with_thread_originator(request_id, response, thread_originator) + .send_response(request_id, response) .instrument(tracing::info_span!( "app_server.thread_start.send_response", otel.name = "app_server.thread_start.send_response", @@ -4577,7 +4576,6 @@ impl ThreadRequestProcessor { } } - let thread_originator = config_snapshot.originator.clone(); let response = ThreadResumeResponse { thread, disabled_plugin_ids: config_snapshot.disabled_plugin_ids, @@ -4600,9 +4598,7 @@ impl ThreadRequestProcessor { }; let connection_id = request_id.connection_id; - self.outgoing - .send_response_with_thread_originator(request_id, response, thread_originator) - .await; + self.outgoing.send_response(request_id, response).await; // `excludeTurns` is explicitly the cheap resume path, so avoid // rebuilding history only to attribute a replayed usage update. if let Some(token_usage_turn_id) = token_usage_turn_id { @@ -5946,7 +5942,6 @@ impl ThreadRequestProcessor { let sandbox = config_snapshot.sandbox_policy().into(); let active_permission_profile = thread_response_active_permission_profile(config_snapshot.active_permission_profile); - let thread_originator = config_snapshot.originator.clone(); let response = ThreadForkResponse { thread: thread.clone(), disabled_plugin_ids: config_snapshot.disabled_plugin_ids, @@ -5966,9 +5961,7 @@ impl ThreadRequestProcessor { let notif = thread_started_notification(thread); let connection_id = request_id.connection_id; - self.outgoing - .send_response_with_thread_originator(request_id, response, thread_originator) - .await; + self.outgoing.send_response(request_id, response).await; // `excludeTurns` is the cheap fork path, so skip restored usage replay // instead of rebuilding history only to attribute a historical update. if let Some(token_usage_turn_id) = token_usage_turn_id { diff --git a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs index 0da72526..56aeef46 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs @@ -1138,10 +1138,7 @@ mod thread_processor_behavior_tests { let connection_id = ConnectionId(7); let (outgoing_tx, mut outgoing_rx) = tokio::sync::mpsc::channel(8); - let outgoing = Arc::new(OutgoingMessageSender::new( - outgoing_tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let thread_outgoing = ThreadScopedOutgoingMessageSender::new( outgoing.clone(), vec![connection_id], diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index 8967cafd..51f4dd3f 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -82,7 +82,6 @@ fn validate_response_item_image_urls(items: &[ResponseItem]) -> Result<(), JSONR pub(crate) struct TurnRequestProcessor { thread_manager: Arc, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config: Arc, config_manager: ConfigManager, pending_thread_unloads: PendingThreadUnloads, @@ -139,7 +138,6 @@ impl TurnRequestProcessor { pub(crate) fn new( thread_manager: Arc, outgoing: Arc, - analytics_events_client: AnalyticsEventsClient, config: Arc, config_manager: ConfigManager, pending_thread_unloads: PendingThreadUnloads, @@ -150,7 +148,6 @@ impl TurnRequestProcessor { Self { thread_manager, outgoing, - analytics_events_client, config, config_manager, pending_thread_unloads, @@ -305,11 +302,9 @@ impl TurnRequestProcessor { request_id: &ConnectionRequestId, params: TurnInterruptParams, ) -> Result, JSONRPCErrorError> { - let result = self.turn_interrupt_inner(request_id, params).await; - if let Err(error) = &result { - self.track_error_response(request_id, error, /*error_type*/ None); - } - result.map(|response| response.map(Into::into)) + self.turn_interrupt_inner(request_id, params) + .await + .map(|response| response.map(Into::into)) } pub(crate) async fn thread_realtime_start( @@ -400,20 +395,6 @@ impl TurnRequestProcessor { )) } - fn track_error_response( - &self, - request_id: &ConnectionRequestId, - error: &JSONRPCErrorError, - error_type: Option, - ) { - self.analytics_events_client.track_error_response( - request_id.connection_id.0, - request_id.request_id.clone(), - error.clone(), - error_type, - ); - } - async fn load_thread( &self, thread_id: &str, @@ -433,14 +414,10 @@ impl TurnRequestProcessor { async fn ensure_direct_input_allowed( &self, - request_id: &ConnectionRequestId, + _request_id: &ConnectionRequestId, thread: &CodexThread, ) -> Result<(), JSONRPCErrorError> { - ensure_direct_input_allowed(thread) - .await - .inspect_err(|error| { - self.track_error_response(request_id, error, /*error_type*/ None); - }) + ensure_direct_input_allowed(thread).await } fn normalize_collaboration_mode( @@ -544,12 +521,7 @@ impl TurnRequestProcessor { app_server_client_name: Option, app_server_client_version: Option, ) -> Result { - let (thread_id, thread) = - self.load_thread(¶ms.thread_id) - .await - .inspect_err(|error| { - self.track_error_response(&request_id, error, /*error_type*/ None); - })?; + let (thread_id, thread) = self.load_thread(¶ms.thread_id).await?; self.ensure_direct_input_allowed(&request_id, thread.as_ref()) .await?; self.config_manager @@ -588,11 +560,6 @@ impl TurnRequestProcessor { }); if actual_chars > MAX_USER_INPUT_TEXT_CHARS { let error = Self::input_too_large_error(actual_chars); - self.track_error_response( - &request_id, - &error, - Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), - ); return Err(error); } // Validate before changing the thread's live MCP policy. @@ -600,19 +567,13 @@ impl TurnRequestProcessor { additional_context .values() .try_for_each(CoreAdditionalContextEntry::validate) - .map_err(invalid_request) - .inspect_err(|error| { - self.track_error_response(&request_id, error, /*error_type*/ None); - })?; + .map_err(invalid_request)?; Self::set_app_server_client_info( thread.as_ref(), app_server_client_name, app_server_client_version, ) - .await - .inspect_err(|error| { - self.track_error_response(&request_id, error, /*error_type*/ None); - })?; + .await?; let runtime_workspace_roots = params .runtime_workspace_roots .map(resolve_runtime_workspace_roots); @@ -706,7 +667,6 @@ impl TurnRequestProcessor { CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()), _ => internal_error(format!("failed to submit turn input: {err}")), }; - self.track_error_response(&request_id, &error, /*error_type*/ None); error })?; let (turn_id, root_turn_id, started) = match submission { @@ -729,7 +689,6 @@ impl TurnRequestProcessor { } else { internal_error(format!("failed to submit turn input: {reason:?}")) }; - self.track_error_response(&request_id, &error, /*error_type*/ None); return Err(error); } }; @@ -1079,12 +1038,7 @@ impl TurnRequestProcessor { request_id: &ConnectionRequestId, params: TurnSteerParams, ) -> Result { - let (_, thread) = self - .load_thread(¶ms.thread_id) - .await - .inspect_err(|error| { - self.track_error_response(request_id, error, /*error_type*/ None); - })?; + let (_, thread) = self.load_thread(¶ms.thread_id).await?; self.ensure_direct_input_allowed(request_id, thread.as_ref()) .await?; self.config_manager @@ -1099,11 +1053,6 @@ impl TurnRequestProcessor { .record_request_turn_id(request_id, ¶ms.expected_turn_id) .await; if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { - self.track_error_response( - request_id, - &error, - Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), - ); return Err(error); } @@ -1131,40 +1080,30 @@ impl TurnRequestProcessor { CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()), _ => internal_error(format!("failed to steer turn: {err}")), }; - self.track_error_response(request_id, &error, /*error_type*/ None); error })?; let turn_id = match submission { SteerSubmission::Steered { turn_id } => turn_id, SteerSubmission::NotSubmitted { reason } => { - let (message, data, error_type) = match reason { + let (message, data) = match reason { NotSubmittedReason::ServerDraining => { return Err(crate::error_code::server_draining_error()); } - NotSubmittedReason::NoActiveTurn | NotSubmittedReason::NotIdle => ( - "no active turn to steer".to_string(), - None, - Some(AnalyticsJsonRpcError::TurnSteer( - TurnSteerRequestError::NoActiveTurn, - )), - ), + NotSubmittedReason::NoActiveTurn | NotSubmittedReason::NotIdle => { + ("no active turn to steer".to_string(), None) + } NotSubmittedReason::ExpectedTurnMismatch { expected, actual } => ( format!("expected active turn id `{expected}` but found `{actual}`"), None, - Some(AnalyticsJsonRpcError::TurnSteer( - TurnSteerRequestError::ExpectedTurnMismatch, - )), ), NotSubmittedReason::ActiveTurnNotSteerable { turn_kind } => { - let (message, turn_steer_error) = match turn_kind { - codex_protocol::protocol::NonSteerableTurnKind::Review => ( - "cannot steer a review turn".to_string(), - TurnSteerRequestError::NonSteerableReview, - ), - codex_protocol::protocol::NonSteerableTurnKind::Compact => ( - "cannot steer a compact turn".to_string(), - TurnSteerRequestError::NonSteerableCompact, - ), + let message = match turn_kind { + codex_protocol::protocol::NonSteerableTurnKind::Review => { + "cannot steer a review turn".to_string() + } + codex_protocol::protocol::NonSteerableTurnKind::Compact => { + "cannot steer a compact turn".to_string() + } }; let error = TurnError { misalignment: None, @@ -1184,35 +1123,21 @@ impl TurnRequestProcessor { None } }; - ( - message, - data, - Some(AnalyticsJsonRpcError::TurnSteer(turn_steer_error)), - ) + (message, data) } - NotSubmittedReason::EmptyInput => ( - "input must not be empty".to_string(), - None, - Some(AnalyticsJsonRpcError::Input(InputError::Empty)), - ), + NotSubmittedReason::EmptyInput => ("input must not be empty".to_string(), None), NotSubmittedReason::ActiveTurnOutputSchemaMismatch => ( "active turn uses a different output schema".to_string(), None, - None, ), NotSubmittedReason::PendingTriggerTurn | NotSubmittedReason::PlanMode - | NotSubmittedReason::Superseded => ( - "no active turn to steer".to_string(), - None, - Some(AnalyticsJsonRpcError::TurnSteer( - TurnSteerRequestError::NoActiveTurn, - )), - ), + | NotSubmittedReason::Superseded => { + ("no active turn to steer".to_string(), None) + } }; let mut error = invalid_request(message); error.data = data; - self.track_error_response(request_id, &error, error_type); return Err(error); } }; diff --git a/codex-rs/app-server/src/thread_sample_cancel_context_tests.rs b/codex-rs/app-server/src/thread_sample_cancel_context_tests.rs index c757acf5..51937922 100644 --- a/codex-rs/app-server/src/thread_sample_cancel_context_tests.rs +++ b/codex-rs/app-server/src/thread_sample_cancel_context_tests.rs @@ -6,7 +6,7 @@ use pretty_assertions::assert_eq; #[tokio::test] async fn thread_sample_cancel_only_signals_matching_request_contexts() { let (tx, _rx) = mpsc::channel(/*buffer*/ 1); - let outgoing = OutgoingMessageSender::new(tx, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); for method in [ "thread/sample", "thread/sample/cancel", diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index a9a4cefd..717d28d1 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -743,7 +743,6 @@ mod tests { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(8); let manager = ThreadWatchManager::new_with_outgoing(Arc::new(OutgoingMessageSender::new( outgoing_tx, - codex_analytics::AnalyticsEventsClient::disabled(), ))); manager.upsert_thread(INTERACTIVE_THREAD_ID).await; @@ -781,7 +780,6 @@ mod tests { let (outgoing_tx, mut outgoing_rx) = mpsc::channel(8); let manager = ThreadWatchManager::new_with_outgoing(Arc::new(OutgoingMessageSender::new( outgoing_tx, - codex_analytics::AnalyticsEventsClient::disabled(), ))); manager.upsert_thread_silently(INTERACTIVE_THREAD_ID).await; diff --git a/codex-rs/app-server/src/user_verification_cancel_context_tests.rs b/codex-rs/app-server/src/user_verification_cancel_context_tests.rs index 0b571e2f..6238504f 100644 --- a/codex-rs/app-server/src/user_verification_cancel_context_tests.rs +++ b/codex-rs/app-server/src/user_verification_cancel_context_tests.rs @@ -9,7 +9,7 @@ use pretty_assertions::assert_eq; #[tokio::test] async fn user_verification_cancel_only_signals_matching_native_request_contexts() { let (tx, _rx) = mpsc::channel(/*buffer*/ 1); - let outgoing = OutgoingMessageSender::new(tx, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); for method in [ "userVerification/status", "userVerification/enroll", @@ -65,7 +65,7 @@ async fn user_verification_cancel_only_signals_matching_native_request_contexts( async fn user_verification_cancel_remains_effective_until_proof_enqueue_and_cleans_up() { for close_receiver in [false, true] { let (tx, mut rx) = mpsc::channel(/*buffer*/ 1); - let outgoing = OutgoingMessageSender::new(tx, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(tx); let target = ConnectionRequestId { connection_id: ConnectionId(1), request_id: RequestId::String("verify".into()), diff --git a/codex-rs/app-server/src/user_verification_ownership_tests.rs b/codex-rs/app-server/src/user_verification_ownership_tests.rs index 21986879..983d6430 100644 --- a/codex-rs/app-server/src/user_verification_ownership_tests.rs +++ b/codex-rs/app-server/src/user_verification_ownership_tests.rs @@ -29,7 +29,7 @@ fn request(thread_id: ThreadId) -> ServerRequestPayload { #[tokio::test] async fn verification_is_delivered_to_one_owner_and_other_connections_cannot_resolve_it() { let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); outgoing .enable_user_verification_connection(ConnectionId(1)) .await; @@ -83,7 +83,7 @@ async fn verification_is_delivered_to_one_owner_and_other_connections_cannot_res #[tokio::test] async fn verification_cancels_when_its_owner_disconnects() { let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); outgoing .enable_user_verification_connection(ConnectionId(1)) .await; @@ -118,7 +118,7 @@ async fn verification_cancels_when_its_owner_disconnects() { #[tokio::test] async fn verification_disconnect_during_registration_leaves_no_callback_or_request() { let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); outgoing .enable_user_verification_connection(ConnectionId(1)) .await; @@ -159,7 +159,7 @@ async fn verification_disconnect_during_registration_leaves_no_callback_or_reque #[tokio::test] async fn verification_without_a_connected_app_has_no_pending_callback() { let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); outgoing .enable_user_verification_connection(ConnectionId(1)) .await; @@ -207,10 +207,7 @@ async fn auth_changes_cancel_user_verification() { let home = tempfile::tempdir().unwrap(); let auth = auth_manager(home.path()).await; let (sender, mut messages) = mpsc::channel(4); - let outgoing = Arc::new(OutgoingMessageSender::new( - sender, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(sender)); outgoing.watch_user_verification_auth(Arc::clone(&auth)); outgoing .enable_user_verification_connection(ConnectionId(1)) @@ -241,7 +238,7 @@ async fn account_switch_back_rejects_proof_before_the_auth_watcher_runs() { let home = tempfile::tempdir().unwrap(); let auth = auth_manager(home.path()).await; let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); // Leave the watcher stopped to exercise response validation before a coalesced notification. assert!(outgoing.verification_auth.set(Arc::clone(&auth)).is_ok()); outgoing @@ -272,7 +269,7 @@ async fn account_switch_during_eligibility_lock_wait_does_not_reassign_verificat let home = tempfile::tempdir().unwrap(); let auth = auth_manager(home.path()).await; let (sender, mut messages) = mpsc::channel(4); - let outgoing = OutgoingMessageSender::new(sender, AnalyticsEventsClient::disabled()); + let outgoing = OutgoingMessageSender::new(sender); assert!(outgoing.verification_auth.set(Arc::clone(&auth)).is_ok()); outgoing .enable_user_verification_connection(ConnectionId(1)) diff --git a/codex-rs/app-server/src/user_verification_test_support.rs b/codex-rs/app-server/src/user_verification_test_support.rs index ab2c292f..3619b26b 100644 --- a/codex-rs/app-server/src/user_verification_test_support.rs +++ b/codex-rs/app-server/src/user_verification_test_support.rs @@ -16,8 +16,6 @@ use app_test_support::ChatGptAuthFixture; use app_test_support::write_chatgpt_auth; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::AppServerRpcTransport; use codex_arg0::Arg0DispatchPaths; use codex_config::CloudConfigBundleLoader; use codex_config::LoaderOverrides; @@ -149,14 +147,10 @@ impl Harness { Arc::new(codex_config::NoopThreadConfigLoader), ); let (sender, messages) = mpsc::channel(/*buffer*/ 16); - let outgoing = Arc::new(OutgoingMessageSender::new( - sender, - AnalyticsEventsClient::disabled(), - )); + let outgoing = Arc::new(OutgoingMessageSender::new(sender)); let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { cloud_skill_provider: None, outgoing: Arc::clone(&outgoing), - analytics_events_client: AnalyticsEventsClient::disabled(), arg0_paths: Arg0DispatchPaths::default(), startup_cwd: Some(config.cwd.to_path_buf()), config, @@ -173,13 +167,6 @@ impl Harness { runtime_auth_slot: None, installation_id: "11111111-1111-4111-8111-111111111111".into(), code_mode_session_provider: None, - rpc_transport: match origin { - ConnectionOrigin::InProcess => AppServerRpcTransport::InProcess, - ConnectionOrigin::Stdio | ConnectionOrigin::RemoteControl => { - AppServerRpcTransport::Stdio - } - ConnectionOrigin::WebSocket => AppServerRpcTransport::Websocket, - }, remote_control_handle: None, plugin_startup_tasks: None, })); diff --git a/codex-rs/app-server/tests/common/analytics_server.rs b/codex-rs/app-server/tests/common/analytics_server.rs deleted file mode 100644 index 75b8df60..00000000 --- a/codex-rs/app-server/tests/common/analytics_server.rs +++ /dev/null @@ -1,16 +0,0 @@ -use anyhow::Result; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -pub async fn start_analytics_events_server() -> Result { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - Ok(server) -} diff --git a/codex-rs/app-server/tests/common/auth_fixtures.rs b/codex-rs/app-server/tests/common/auth_fixtures.rs index 825745e1..ca92af2b 100644 --- a/codex-rs/app-server/tests/common/auth_fixtures.rs +++ b/codex-rs/app-server/tests/common/auth_fixtures.rs @@ -35,6 +35,21 @@ pub async fn mount_workspace_routing(server: &wiremock::MockServer) { .await; } +/// Signs `codex_home` into a fake ChatGPT account (`account-123` / `user-123`) whose +/// workspace routing check is served by `server`. +pub async fn mount_chatgpt_account(server: &wiremock::MockServer, codex_home: &Path) -> Result<()> { + write_chatgpt_auth( + codex_home, + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + mount_workspace_routing(server).await; + Ok(()) +} + /// Builder for writing a fake ChatGPT auth.json in tests. #[derive(Debug, Clone)] pub struct ChatGptAuthFixture { diff --git a/codex-rs/app-server/tests/common/lib.rs b/codex-rs/app-server/tests/common/lib.rs index f7ebde51..9b3a339c 100644 --- a/codex-rs/app-server/tests/common/lib.rs +++ b/codex-rs/app-server/tests/common/lib.rs @@ -1,6 +1,5 @@ #![allow(clippy::expect_used)] -mod analytics_server; mod auth_fixtures; mod config; mod json_logging; @@ -12,10 +11,10 @@ mod rollout; mod rpc_delay; mod test_app_server; -pub use analytics_server::start_analytics_events_server; pub use auth_fixtures::ChatGptAuthFixture; pub use auth_fixtures::ChatGptIdTokenClaims; pub use auth_fixtures::encode_id_token; +pub use auth_fixtures::mount_chatgpt_account; pub use auth_fixtures::mount_workspace_routing; pub use auth_fixtures::write_chatgpt_auth; use codex_app_server_protocol::JSONRPCResponse; diff --git a/codex-rs/app-server/tests/suite/logging.rs b/codex-rs/app-server/tests/suite/logging.rs index 348d6a87..59d6b6ea 100644 --- a/codex-rs/app-server/tests/suite/logging.rs +++ b/codex-rs/app-server/tests/suite/logging.rs @@ -39,14 +39,7 @@ use core_test_support::skip_if_wine_exec; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; -use std::collections::BTreeMap; use tempfile::TempDir; -use test_case::test_case; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use tokio::net::TcpListener; -use tokio::net::TcpStream; -use tokio::sync::watch; use tokio::time::Duration; use tokio::time::timeout; use wiremock::Mock; @@ -440,308 +433,6 @@ fn standalone_app_server_emits_json_info_events() -> Result<()> { Ok(()) } -#[tokio::test] -async fn sqlite_log_metrics_exports_do_not_create_log_cycles() -> Result<()> { - let quiet_period = codex_state::log_db::LogSinkQueueConfig::default().flush_interval - + Duration::from_millis(600); - let export_timeout = quiet_period * 3; - - for status in [200, 500] { - let collector = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/v1/metrics")) - .respond_with(ResponseTemplate::new(status)) - .mount(&collector) - .await; - - let codex_home = TempDir::new()?; - let endpoint = format!("{}/v1/metrics", collector.uri()); - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "[analytics]\nenabled = true\n\n[otel.metrics_exporter.otlp-http]\nendpoint = {endpoint:?}\nprotocol = \"json\"\n" - ), - )?; - - let _app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[ - ("OTEL_METRIC_EXPORT_INTERVAL", Some("200")), - ( - codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR, - Some("1"), - ), - ]) - .build_initialized_with_timeout(export_timeout) - .await?; - - let exports = timeout(export_timeout, async { - loop { - let requests = collector.received_requests().await.unwrap_or_default(); - if requests.iter().any(|request| { - String::from_utf8_lossy(&request.body).contains(codex_state::LOG_WRITE_METRIC) - }) { - break requests.len(); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - - let requests = timeout(export_timeout, async { - let mut observed_exports = exports; - loop { - tokio::time::sleep(quiet_period).await; - let requests = collector.received_requests().await.unwrap_or_default(); - if requests.len() == observed_exports { - break requests; - } - observed_exports = requests.len(); - } - }) - .await - .with_context(|| { - format!("OTLP HTTP {status} exports did not stop after the application became idle") - })?; - - let expected_metrics = [ - (codex_state::LOG_WRITE_METRIC, "sum"), - (codex_state::LOG_WRITE_DURATION_METRIC, "histogram"), - (codex_state::LOG_WRITE_BYTES_METRIC, "histogram"), - (codex_state::LOG_WRITE_ENTRIES_METRIC, "histogram"), - (codex_state::LOG_WRITE_MAX_ENTRY_BYTES_METRIC, "histogram"), - ]; - let payloads = requests - .iter() - .map(|request| serde_json::from_slice::(&request.body)) - .collect::>>()?; - let mut observed_metrics = BTreeMap::<&str, (u64, f64)>::new(); - for (name, kind) in expected_metrics { - let points = payloads - .iter() - .flat_map(|payload| payload["resourceMetrics"].as_array().into_iter().flatten()) - .flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten()) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .filter(|metric| metric["name"].as_str() == Some(name)) - .flat_map(|metric| metric[kind]["dataPoints"].as_array().into_iter().flatten()) - .collect::>(); - assert!( - !points.is_empty(), - "metric {name} must reach the collector as a {kind}" - ); - - for point in points { - let attributes: BTreeMap<&str, &str> = point["attributes"] - .as_array() - .context("metric data points must include attributes")? - .iter() - .filter_map(|attribute| { - Some(( - attribute["key"].as_str()?, - attribute["value"]["stringValue"].as_str()?, - )) - }) - .collect(); - assert_eq!( - attributes, - BTreeMap::from([ - ("error", "none"), - ("originator", "codex-app-server"), - ("status", "success"), - ]), - "metric {name} must preserve its production dimensions" - ); - - let count_field = if kind == "sum" { "asInt" } else { "count" }; - let count = point[count_field] - .as_u64() - .or_else(|| point[count_field].as_str()?.parse().ok()) - .with_context(|| format!("metric {name} must include a valid {count_field}"))?; - let value = if kind == "sum" { - count as f64 - } else { - point["sum"] - .as_f64() - .with_context(|| format!("metric {name} must include its sample sum"))? - }; - let observed = observed_metrics.entry(name).or_default(); - observed.0 += count; - observed.1 += value; - - if matches!( - name, - codex_state::LOG_WRITE_BYTES_METRIC - | codex_state::LOG_WRITE_MAX_ENTRY_BYTES_METRIC - ) { - let bounds = point["explicitBounds"] - .as_array() - .context("byte histograms must export explicit bucket bounds")?; - assert_eq!(bounds.first().and_then(Value::as_f64), Some(128.0)); - assert_eq!(bounds.last().and_then(Value::as_f64), Some(16_777_216.0)); - } - } - } - - let write_count = observed_metrics[codex_state::LOG_WRITE_METRIC].0; - assert!(write_count > 0, "at least one SQLite batch must be written"); - for (name, _) in expected_metrics { - assert_eq!( - observed_metrics[name].0, write_count, - "metric {name} must record exactly one sample per SQLite write" - ); - } - - let state = codex_state::StateRuntime::init( - load_default_config_for_test(&codex_home).await.sqlite, - "test-provider".to_string(), - ) - .await?; - let persisted_logs = state.query_logs(&codex_state::LogQuery::default()).await?; - assert_eq!( - observed_metrics[codex_state::LOG_WRITE_ENTRIES_METRIC].1, - persisted_logs.len() as f64, - "exported batch sizes must equal the number of persisted SQLite log rows" - ); - assert!( - observed_metrics[codex_state::LOG_WRITE_BYTES_METRIC].1 - >= observed_metrics[codex_state::LOG_WRITE_MAX_ENTRY_BYTES_METRIC].1, - "each batch's largest entry cannot exceed the total batch size" - ); - } - - Ok(()) -} - -/// Exporting SQLite metrics must eventually stop producing new SQLite metrics, -/// including when the collector uses HTTP/2 or rejects the gRPC request. -#[test_case("0"; "success")] -#[test_case("14"; "unavailable")] -#[tokio::test] -async fn sqlite_log_metrics_grpc_exports_do_not_create_log_cycles(grpc_status: &str) -> Result<()> { - let quiet_period = codex_state::log_db::LogSinkQueueConfig::default().flush_interval - + Duration::from_millis(600); - let export_timeout = quiet_period * 3; - let (export_count, mut exports) = watch::channel(/*init*/ 0_usize); - let (ping_ack_count, mut ping_acknowledgements) = watch::channel(/*init*/ 0_usize); - let collector = MockServer::builder() - .disable_request_recording() - .start() - .await; - // An uncompressed gRPC frame containing an empty ExportMetricsServiceResponse. - // Tonic also accepts grpc-status in the initial response headers. - let response = ResponseTemplate::new(/*s*/ 200) - .set_body_raw(vec![0; 5], "application/grpc") - .insert_header("grpc-status", grpc_status); - Mock::given(method("POST")) - .and(path( - "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", - )) - .respond_with(move |request: &wiremock::Request| { - let metric_name = codex_state::LOG_WRITE_METRIC.as_bytes(); - if request - .body - .windows(metric_name.len()) - .any(|bytes| bytes == metric_name) - { - export_count.send_modify(|count| *count += 1); - } - response.clone() - }) - .mount(&collector) - .await; - - let proxy = TcpListener::bind("127.0.0.1:0").await?; - let endpoint = format!("http://{}", proxy.local_addr()?); - let collector_address = *collector.address(); - let _proxy = tokio::spawn(async move { - let (downstream, _) = proxy.accept().await?; - let upstream = TcpStream::connect(collector_address).await?; - let (mut downstream_reader, mut downstream_writer) = downstream.into_split(); - let (mut upstream_reader, mut upstream_writer) = upstream.into_split(); - - let requests = tokio::io::copy(&mut downstream_reader, &mut upstream_writer); - let responses = async move { - loop { - let mut header = [0; 9]; - if upstream_reader.read_exact(&mut header).await.is_err() { - break; - } - let length = (usize::from(header[0]) << 16) - | (usize::from(header[1]) << 8) - | usize::from(header[2]); - let mut payload = vec![0; length]; - upstream_reader.read_exact(&mut payload).await?; - downstream_writer.write_all(&header).await?; - downstream_writer.write_all(&payload).await?; - - if header[3] == 0 { - // A valid but unsolicited HTTP/2 PING ACK makes h2 emit a - // warning from its separate connection-driving task. - downstream_writer - .write_all(&[0, 0, 8, 6, 1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8]) - .await?; - ping_ack_count.send_modify(|count| *count += 1); - } - } - Ok::<(), std::io::Error>(()) - }; - - tokio::try_join!(requests, responses)?; - Ok::<(), std::io::Error>(()) - }); - - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "[analytics]\nenabled = true\n\n[otel.metrics_exporter.otlp-grpc]\nendpoint = {endpoint:?}\n" - ), - )?; - let _app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[ - ("OTEL_METRIC_EXPORT_INTERVAL", Some("200")), - ( - codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR, - Some("1"), - ), - ]) - .build_initialized_with_timeout(export_timeout) - .await?; - - timeout(export_timeout, exports.wait_for(|count| *count > 0)) - .await - .context("collector never received a SQLite log-write metric")??; - timeout( - export_timeout, - ping_acknowledgements.wait_for(|count| *count > 0), - ) - .await - .context("collector response never produced an unsolicited HTTP/2 PING acknowledgment")??; - let first_count = *exports.borrow_and_update(); - - // Allow delayed startup batches, but require silence longer than one SQLite - // flush interval plus one metric-export interval. Do not retain request bodies - // or keep resetting the overall deadline when a broken exporter feeds itself. - let quiescence = timeout(export_timeout, async { - loop { - match timeout(quiet_period, exports.changed()).await { - Err(_) => return Ok::<(), watch::error::RecvError>(()), - Ok(result) => result?, - } - } - }) - .await; - let final_count = *exports.borrow(); - quiescence.with_context(|| { - format!( - "OTLP gRPC status {grpc_status} did not become idle: SQLite log-write exports increased from {first_count} to {final_count}" - ) - })??; - - Ok(()) -} - #[tokio::test] async fn app_server_emits_structured_tool_call_timing_event() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index c8bb9ecc..006f8709 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -2289,7 +2289,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()> }, )?; write_models_cache(codex_home.path()).await?; - let collector = super::auth_storage_originator::configure_collector(codex_home.path()).await?; mock_device_code_usercode(&mock_server, /*interval_seconds*/ 0).await; mock_device_code_token_success(&mock_server).await; @@ -2308,7 +2307,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()> .without_auto_env() .with_env_overrides(&[ ("OPENAI_API_KEY", None), - ("OTEL_METRIC_EXPORT_INTERVAL", Some("200")), (LOGIN_ISSUER_ENV_VAR, Some(issuer.as_str())), ]) .build() @@ -2362,7 +2360,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()> codex_home.path().join("auth.json").exists(), "auth.json should be created when device code login succeeds" ); - super::auth_storage_originator::assert_saved_originators(&collector, &["codex_vscode"]).await?; Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs b/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs index 994bf5c3..fa1a795a 100644 --- a/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs @@ -420,8 +420,7 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> { .with_root_config(&format!( r#"cli_auth_credentials_store = "file" chatgpt_base_url = "{origin}/backend-api" -mcp_oauth_callback_port = {callback_port} -analytics = {{ enabled = false }}"# +mcp_oauth_callback_port = {callback_port}"# )) .with_provider_config("requires_openai_auth = true") .with_extra_config(&format!( @@ -1678,8 +1677,7 @@ async fn enterprise_login_setup_is_cancelled_by_account_changes() -> Result<()> .with_root_config(&format!( r#"cli_auth_credentials_store = "file" chatgpt_base_url = "{origin}/backend-api" -mcp_oauth_callback_port = {callback_port} -analytics = {{ enabled = false }}"# +mcp_oauth_callback_port = {callback_port}"# )) .with_provider_config("requires_openai_auth = true") .with_extra_config(&format!( diff --git a/codex-rs/app-server/tests/suite/v2/analytics.rs b/codex-rs/app-server/tests/suite/v2/analytics.rs deleted file mode 100644 index 1053a603..00000000 --- a/codex-rs/app-server/tests/suite/v2/analytics.rs +++ /dev/null @@ -1,1319 +0,0 @@ -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::DEFAULT_CLIENT_NAME; -use app_test_support::MockResponsesConfig; -use app_test_support::TestAppServer; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; -use codex_app_server_protocol::ApprovalsReviewer; -use codex_app_server_protocol::AskForApproval; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ItemCompletedNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SandboxPolicy; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::ThreadReadParams; -use codex_app_server_protocol::ThreadReadResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnSettingsUpdateParams; -use codex_app_server_protocol::TurnSettingsUpdateResponse; -use codex_app_server_protocol::TurnSettingsUpdateStatus; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; -use codex_config::types::AuthCredentialsStoreMode; -use codex_config::types::OtelExporterKind; -use codex_config::types::OtelHttpProtocol; -use codex_core::config::ConfigBuilder; -use codex_core_plugins::loader::curated_plugin_cache_version; -use codex_core_plugins::store::PluginStore; -use codex_features::Feature; -use codex_models_manager::bundled_models_response; -use codex_plugin::PluginId; -use codex_protocol::config_types::CollaborationMode; -use codex_protocol::config_types::ModeKind; -use codex_protocol::config_types::Settings; -use codex_protocol::models::MessagePhase; -use codex_protocol::openai_models::ModelsResponse; -use codex_protocol::openai_models::ReasoningEffort; -use core_test_support::responses; -use core_test_support::skip_if_no_network; -use core_test_support::skip_if_remote; -use core_test_support::skip_if_wine_exec; -use core_test_support::startup::STARTUP_TIMEOUT; -use core_test_support::startup::expect_startup; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::path_regex; - -const SERVICE_VERSION: &str = "0.0.0-test"; - -// Completion metadata follows its source message without entering later model requests. -#[test_case::test_case(ModeKind::Default; "normal")] -#[test_case::test_case(ModeKind::Plan; "plan")] -#[tokio::test] -async fn native_counts_follow_completed_messages_without_request_replay( - mode: ModeKind, -) -> Result<()> { - #[cfg(windows)] - const READ_TIMEOUT: Duration = Duration::from_secs(25); - #[cfg(not(windows))] - const READ_TIMEOUT: Duration = Duration::from_secs(10); - - let server = responses::start_mock_server().await; - let mut events = vec![responses::ev_response_created("response-1")]; - for (id, text, phase, count) in [ - ("partial", "Partial.", "partial_answer", 0), - ("final", "Done.", "final_answer", 23), - ] { - let mut added = responses::ev_message_item_added(id, ""); - added["item"]["phase"] = json!(phase); - let mut done = responses::ev_assistant_message(id, text); - done["item"]["phase"] = json!(phase); - done["item"]["internal_chat_message_metadata_passthrough"] = - json!({"content_token_count": count}); - events.extend([added, responses::ev_output_text_delta(text), done]); - } - events.push(responses::ev_completed("response-1")); - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()).write(codex_home.path())?; - let mut app = expect_startup( - TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized_with_timeout(STARTUP_TIMEOUT), - ) - .await; - let response_mock = responses::mount_sse_sequence( - &server, - vec![ - responses::sse(events), - responses::sse(vec![ - responses::ev_response_created("response-2"), - responses::ev_assistant_message("next", "Next."), - responses::ev_completed("response-2"), - ]), - ], - ) - .await; - let thread = app - .start_thread(ThreadStartParams { - model: Some("mock-model".into()), - ..Default::default() - }) - .await? - .thread; - timeout(READ_TIMEOUT, async { - for prompt in ["First turn", "Next turn"] { - let completed = app - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: prompt.into(), - text_elements: Vec::new(), - }], - collaboration_mode: Some(CollaborationMode { - mode, - settings: Settings { - model: "mock-model".into(), - reasoning_effort: None, - developer_instructions: None, - }, - }), - ..Default::default() - }) - .await?; - assert_eq!(completed.turn.status, TurnStatus::Completed); - } - let mut counts = Vec::new(); - while counts.len() < 2 { - let completed: ItemCompletedNotification = - app.read_notification("item/completed").await?; - if let ThreadItemPayload::AgentMessage { id, phase, .. } = completed.item.payload { - counts.push((id, phase, completed.content_token_count)); - } - } - assert_eq!( - counts, - vec![ - ("partial".into(), Some(MessagePhase::PartialAnswer), Some(0)), - ("final".into(), Some(MessagePhase::FinalAnswer), Some(23)), - ] - ); - app.shutdown_gracefully().await?; - anyhow::Ok(()) - }) - .await??; - let requests = response_mock.requests(); - assert_eq!(requests.len(), 2); - let assistant_input: Vec<_> = requests[1] - .inputs_of_type("message") - .into_iter() - .filter(|item| item["role"] == "assistant") - .map(|item| { - ( - item["content"][0]["text"].clone(), - item["internal_chat_message_metadata_passthrough"] - .get("content_token_count") - .cloned(), - ) - }) - .collect(); - assert_eq!( - assistant_input, - vec![(json!("Partial."), None), (json!("Done."), None)] - ); - Ok(()) -} - -#[tokio::test] -async fn usage_limit_window_reaches_turn_analytics() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - Mock::given(method("POST")) - .and(path_regex(".*/responses$")) - .respond_with(ResponseTemplate::new(429).set_body_json(json!({ - "error": { - "type": "usage_limit_reached", - "message": "usage limit reached", - "plan_type": "pro", - "limit_window_minutes": 300 - } - }))) - .expect(1) - .mount(&server) - .await; - - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) - .with_provider_config("supports_websockets = false") - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - let thread = app_server - .start_thread(ThreadStartParams::default()) - .await? - .thread; - let completed = app_server - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id, - input: vec![UserInput::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - - let event = wait_for_matching_analytics_event(&server, Duration::from_secs(30), |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == completed.turn.id - }) - .await?; - let params = &event["event_params"]; - assert_eq!( - json!([ - params["status"], - params["turn_error"], - params["codex_error_kind"], - params["usage_limit_window_minutes"], - ]), - json!(["failed", "usageLimitExceeded", "usage_limit_reached", 300]) - ); - - Ok(()) -} - -#[tokio::test] -async fn guardian_review_turns_and_tools_reach_analytics() -> Result<()> { - skip_if_no_network!(Ok(())); - const PRIVATE: &str = "guardian-private-content"; - const READ_TIMEOUT: Duration = Duration::from_secs(60); - let server = responses::start_mock_server().await; - let codex_home = TempDir::new()?; - mount_analytics_capture(&server, codex_home.path()).await?; - let catalog_path = codex_home.path().join("guardian-models.json"); - std::fs::write( - &catalog_path, - serde_json::to_vec(&bundled_models_response()?)?, - )?; - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!( - "chatgpt_base_url = \"{}\"\nmodel_catalog_json = {}", - server.uri(), - serde_json::to_string(&catalog_path)? - )) - .with_provider_config("supports_websockets = false") - .enable_feature(Feature::GuardianApproval) - .disable_feature(Feature::Apps) - .write(codex_home.path())?; - let parent_tool = |id: &str| { - responses::sse_response(responses::sse(vec![ - responses::ev_response_created(id), - responses::ev_function_call( - id, - "exec_command", - &json!({ - "cmd": format!("echo {id} > {id}.txt"), - "sandbox_permissions": "require_escalated", - "justification": "Exercise Guardian analytics", - }) - .to_string(), - ), - responses::ev_completed(id), - ])) - }; - let requests = responses::mount_response_sequence( - &server, - vec![ - parent_tool("parent-first"), - responses::sse_response(responses::sse(vec![ - responses::ev_response_created("guardian-first"), - responses::ev_web_search_call_added_partial("guardian-search", "in_progress"), - responses::ev_web_search_call_done("guardian-search", "completed", PRIVATE), - responses::ev_reasoning_item("guardian-reasoning", &[PRIVATE], &[PRIVATE]), - responses::ev_assistant_message( - "guardian-answer", - &json!({"outcome": "deny", "rationale": PRIVATE}).to_string(), - ), - responses::ev_completed("guardian-first"), - ])), - parent_tool("parent-second"), - responses::sse_response(responses::sse_failed( - "guardian-failed", - "invalid_prompt", - PRIVATE, - )), - parent_tool("parent-third"), - responses::sse_response(responses::sse(vec![responses::ev_response_created( - "guardian-pending", - )])) - .set_delay(READ_TIMEOUT), - ], - ) - .await; - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - // Basic Guardian command approvals require host-native paths. - .without_auto_env() - .build_initialized_with_timeout(READ_TIMEOUT) - .await?; - let ThreadStartResponse { thread, .. } = app_server - .request(|request_id| ClientRequest::ThreadStart { - request_id, - params: ThreadStartParams { - approval_policy: Some(AskForApproval::OnRequest), - approvals_reviewer: Some(ApprovalsReviewer::AutoReview), - ..Default::default() - }, - }) - .await?; - let request_id = app_server - .send_turn_start_request(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Review three commands".to_string(), - text_elements: Vec::new(), - }], - effort: Some(ReasoningEffort::High), - ..Default::default() - }) - .await?; - let TurnStartResponse { turn } = - timeout(READ_TIMEOUT, app_server.read_response(request_id)).await??; - let reviews = timeout(READ_TIMEOUT, async { - loop { - let reviews = requests - .requests() - .into_iter() - .map(|request| request.body_json()["client_metadata"].clone()) - .filter(|metadata| metadata["x-openai-subagent"] == "guardian") - .collect::>(); - if reviews.len() == 3 { - break reviews; - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - app_server - .interrupt_turn_and_wait_for_aborted(thread.id.clone(), turn.id, READ_TIMEOUT) - .await?; - wait_for_matching_analytics_event(&server, READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == reviews[2]["turn_id"] - }) - .await?; - timeout(READ_TIMEOUT, app_server.shutdown_gracefully()).await??; - let events = captured_analytics_events(&server).await; - assert!(!serde_json::to_string(&events)?.contains(PRIVATE)); - let parent_command = events - .iter() - .find(|event| { - event["event_type"] == "codex_command_execution_event" - && event["event_params"]["thread_id"] == thread.id - && event["event_params"]["item_id"] == "parent-first" - }) - .expect("denied parent command analytics"); - let params = &parent_command["event_params"]; - assert_eq!( - json!([params["model_slug"], params["reasoning_effort"]]), - json!(["mock-model", "high"]) - ); - let children = events - .iter() - .filter(|event| event["event_params"]["subagent_source"] == "guardian") - .collect::>(); - for event in &children { - let params = &event["event_params"]; - assert_eq!( - json!([ - params["thread_id"], - params["session_id"], - params["parent_thread_id"], - params["thread_source"] - ]), - json!([ - reviews[0]["thread_id"], - thread.session_id, - thread.id, - "guardian_review" - ]) - ); - } - let turns = children - .iter() - .filter(|event| event["event_type"] == "codex_turn_event") - .map(|event| { - let params = &event["event_params"]; - let started_at = params["started_at"].as_u64().expect("turn start time"); - let completed_at = params["completed_at"] - .as_u64() - .expect("turn completion time"); - assert!(started_at > 0 && completed_at >= started_at); - assert!(params["duration_ms"].is_u64()); - assert_eq!(params["guardian_v2_enabled"], false); - json!([ - params["turn_id"], - params["status"], - params["turn_error"], - params["total_tool_call_count"], - params["web_search_count"] - ]) - }) - .collect::>(); - assert_eq!( - turns, - vec![ - json!([reviews[0]["turn_id"], "completed", null, 1, 1]), - json!([reviews[1]["turn_id"], "failed", "other", 0, 0]), - json!([reviews[2]["turn_id"], "interrupted", null, 0, 0]), - ] - ); - let tools = children - .iter() - .filter(|event| event["event_type"] == "codex_web_search_event") - .collect::>(); - let [tool] = tools.as_slice() else { - anyhow::bail!( - "expected one Guardian web search event, got {}", - tools.len() - ); - }; - let params = &tool["event_params"]; - let started_at = params["started_at_ms"].as_u64().expect("tool start time"); - let completed_at = params["completed_at_ms"] - .as_u64() - .expect("tool completion time"); - assert!(started_at > 0 && completed_at >= started_at); - assert_eq!(params["duration_ms"], completed_at - started_at); - assert_eq!( - json!([ - params["turn_id"], - params["item_id"], - params["terminal_status"] - ]), - json!([reviews[0]["turn_id"], "guardian-search", "completed"]) - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn multi_agent_v2_tools_emit_collaborator_analytics() -> Result<()> { - const PARENT_PROMPT: &str = "exercise collaborator analytics"; - const READ_TIMEOUT: Duration = Duration::from_secs(30); - let calls = [ - ( - "spawn_agent", - json!({"task_name": "worker", "message": "PRIVATE_CHILD", "fork_turns": "none"}), - ), - ( - "send_message", - json!({"target": "worker", "message": "PRIVATE_MESSAGE"}), - ), - ( - "followup_task", - json!({"target": "worker", "message": "PRIVATE_FOLLOWUP"}), - ), - ("interrupt_agent", json!({"target": "worker"})), - ("list_agents", json!({})), - ( - "send_message", - json!({"target": "missing", "message": "PRIVATE_MESSAGE"}), - ), - ( - "followup_task", - json!({"target": "/root", "message": "PRIVATE_FOLLOWUP"}), - ), - ("interrupt_agent", json!({"target": "/root"})), - ("list_agents", json!({"unexpected": true})), - ("send_message", json!({})), - ]; - let server = responses::start_mock_server().await; - for (index, (tool, args)) in calls.iter().enumerate() { - let response_id = format!("parent-response-{index}"); - responses::mount_sse_once_match( - &server, - |request: &wiremock::Request| { - String::from_utf8_lossy(&request.body).contains(PARENT_PROMPT) - }, - responses::sse(vec![ - responses::ev_response_created(&response_id), - responses::ev_function_call_with_namespace( - &format!("call-{index}"), - "collaboration", - tool, - &args.to_string(), - ), - responses::ev_completed(&response_id), - ]), - ) - .await; - } - // Child turns and the final parent request only need an ordinary completion. - Mock::given(method("POST")) - .and(path_regex(".*/responses$")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_string(responses::sse(vec![responses::ev_completed( - "response-done", - )])), - ) - .with_priority(10) - .mount(&server) - .await; - - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .enable_feature(Feature::MultiAgentV2) - .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - let thread = app_server - .start_thread(ThreadStartParams::default()) - .await? - .thread; - let completed = app_server - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: PARENT_PROMPT.to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - let read: ThreadReadResponse = app_server - .request(|request_id| ClientRequest::ThreadRead { - request_id, - params: ThreadReadParams { - thread_id: thread.id.clone(), - include_turns: true, - }, - }) - .await?; - let items = &read - .thread - .turns - .iter() - .find(|turn| turn.id == completed.turn.id) - .expect("completed parent turn should be readable") - .items; - let child_thread_id = items - .iter() - .find_map(|item| match &item.payload { - ThreadItemPayload::SubAgentActivity { - id, - agent_thread_id, - .. - } if id == "call-0" => Some(agent_thread_id.clone()), - _ => None, - }) - .expect("spawn should retain its public activity item"); - assert!( - !items - .iter() - .any(|item| matches!(&item.payload, ThreadItemPayload::CollabAgentToolCall { .. })) - ); - let activity_ids = items - .iter() - .filter_map(|item| match &item.payload { - ThreadItemPayload::SubAgentActivity { id, .. } if id.starts_with("call-") => { - Some(id.as_str()) - } - _ => None, - }) - .collect::>(); - assert_eq!(activity_ids, vec!["call-0", "call-1", "call-2", "call-3"]); - - for (index, (tool, _)) in calls.iter().enumerate() { - let event = wait_for_matching_analytics_event(&server, READ_TIMEOUT, |event| { - event["event_type"] == "codex_collab_agent_tool_call_event" - && event["event_params"]["item_id"] == format!("call-{index}") - }) - .await?; - let params = &event["event_params"]; - let receivers = match index { - 0..=3 => vec![child_thread_id.clone()], - 6 | 7 => vec![thread.id.clone()], - _ => Vec::new(), - }; - assert_eq!( - json!({ - "tool": params["tool_name"], - "sender": params["sender_thread_id"], - "receivers": params["receiver_thread_ids"], - "receiverCount": params["receiver_thread_count"], - "turn": params["turn_id"], - "status": params["terminal_status"], - "origin": params["originating_response_id"], - "failure": params["failure_kind"], - "hasDuration": params["execution_duration_ms"].is_u64(), - }), - json!({ - "tool": tool, - "sender": thread.id, - "receivers": receivers, - "receiverCount": receivers.len(), - "turn": completed.turn.id, - "status": if index < 5 { "completed" } else { "failed" }, - "origin": format!("parent-response-{index}"), - "failure": if index < 5 { None } else { Some("tool_error") }, - "hasDuration": true, - }) - ); - assert_eq!(params["duration_ms"], params["execution_duration_ms"]); - assert!(!event.to_string().contains("PRIVATE_")); - } - let turn_event = wait_for_matching_analytics_event(&server, READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == completed.turn.id - }) - .await?; - assert_eq!( - json!({ - "total": turn_event["event_params"]["total_tool_call_count"], - "subagent": turn_event["event_params"]["subagent_tool_call_count"], - "dynamic": turn_event["event_params"]["dynamic_tool_call_count"], - }), - json!({"total": calls.len(), "subagent": calls.len(), "dynamic": 0}) - ); - - Ok(()) -} - -#[tokio::test] -async fn metrics_exporters_respect_analytics_preferences() -> Result<()> { - let codex_home = TempDir::new()?; - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await?; - for exporter in [ - OtelExporterKind::None, - OtelExporterKind::Statsig, - OtelExporterKind::OtlpHttp { - endpoint: "http://localhost:4318".to_string(), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - OtelExporterKind::OtlpGrpc { - endpoint: "http://localhost:4317".to_string(), - headers: HashMap::new(), - tls: None, - }, - ] { - config.otel.metrics_exporter = exporter; - for analytics_enabled in [None, Some(false), Some(true)] { - config.analytics_enabled = analytics_enabled; - for default_analytics_enabled in [false, true] { - let expected_metrics = match config.otel.metrics_exporter { - OtelExporterKind::None => false, - // The built-in exporter is disabled in debug builds even with consent. - OtelExporterKind::Statsig => { - !cfg!(debug_assertions) - && analytics_enabled.unwrap_or(default_analytics_enabled) - } - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true, - }; - let provider = codex_core::otel_init::build_provider( - &config, - SERVICE_VERSION, - Some("codex-app-server"), - default_analytics_enabled, - ) - .map_err(|err| anyhow::anyhow!(err.to_string()))?; - let metrics = provider.as_ref().and_then(|otel| otel.metrics()); - let metrics_enabled = metrics.is_some(); - // Exercise the nonempty export path that concurrent tests can - // trigger through process-global metrics. - let record_result = metrics - .map(|metrics| { - metrics.counter("codex.test.analytics_preferences", /*inc*/ 1, &[]) - }) - .transpose(); - if let Some(provider) = provider { - // Keep Tokio running while the gRPC exporter flushes; a - // synchronous drop can deadlock this current-thread runtime. - provider - .shutdown_with_timeout(Duration::from_secs(/*secs*/ 5)) - .await?; - } - record_result?; - assert_eq!( - metrics_enabled, expected_metrics, - "exporter={:?}, analytics={analytics_enabled:?}, default={default_analytics_enabled}", - config.otel.metrics_exporter, - ); - } - } - } - - Ok(()) -} - -pub(crate) async fn mount_analytics_capture(server: &MockServer, codex_home: &Path) -> Result<()> { - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(server) - .await; - - write_chatgpt_auth( - codex_home, - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - app_test_support::mount_workspace_routing(server).await; - Ok(()) -} - -pub(crate) async fn captured_analytics_events(server: &MockServer) -> Vec { - server - .received_requests() - .await - .unwrap_or_default() - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .flat_map(|request| { - let payload: Value = serde_json::from_slice(&request.body).expect("analytics payload"); - payload["events"] - .as_array() - .expect("analytics events") - .clone() - }) - .collect() -} - -pub(crate) async fn wait_for_analytics_payload( - server: &MockServer, - read_timeout: Duration, -) -> Result { - let body = timeout(read_timeout, async { - loop { - let Some(requests) = server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - if let Some(request) = requests.iter().find(|request| { - request.method == "POST" && request.url.path() == "/codex/analytics-events/events" - }) { - break request.body.clone(); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - serde_json::from_slice(&body).map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}")) -} - -pub(crate) async fn wait_for_analytics_event( - server: &MockServer, - read_timeout: Duration, - event_type: &str, -) -> Result { - wait_for_matching_analytics_event(server, read_timeout, |event| { - event["event_type"] == event_type - }) - .await -} - -pub(crate) async fn wait_for_goal_event( - server: &MockServer, - read_timeout: Duration, - event_kind: &str, - goal_status: &str, -) -> Result { - wait_for_matching_analytics_event(server, read_timeout, |event| { - event["event_type"] == "codex_goal_event" - && event["event_params"]["event_kind"] == event_kind - && event["event_params"]["goal_status"] == goal_status - }) - .await -} - -pub(crate) async fn wait_for_matching_analytics_event( - server: &MockServer, - read_timeout: Duration, - matches: impl Fn(&Value) -> bool, -) -> Result { - timeout(read_timeout, async { - loop { - let Some(requests) = server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - for request in &requests { - if request.method != "POST" - || !request - .url - .path() - .ends_with("/codex/analytics-events/events") - { - continue; - } - let payload: Value = serde_json::from_slice(&request.body) - .map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?; - let Some(events) = payload["events"].as_array() else { - continue; - }; - if let Some(event) = events.iter().find(|event| matches(event)) { - return Ok::(event.clone()); - } - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await? -} - -pub(crate) fn thread_initialized_event(payload: &Value) -> Result<&Value> { - let events = payload["events"] - .as_array() - .ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?; - events - .iter() - .find(|event| event["event_type"] == "codex_thread_initialized") - .ok_or_else(|| anyhow::anyhow!("codex_thread_initialized event should be present")) -} - -pub(crate) fn assert_basic_thread_initialized_event( - event: &Value, - thread_id: &str, - session_id: &str, - expected_product_client_id: &str, - expected_model: &str, - initialization_mode: &str, - expected_thread_source: &str, -) { - assert_eq!(event["event_params"]["thread_id"], thread_id); - assert_eq!(event["event_params"]["session_id"], session_id); - assert_eq!( - event["event_params"]["app_server_client"]["product_client_id"], - expected_product_client_id - ); - assert_eq!( - event["event_params"]["app_server_client"]["client_name"], - DEFAULT_CLIENT_NAME - ); - assert_eq!( - event["event_params"]["app_server_client"]["rpc_transport"], - "stdio" - ); - assert_eq!(event["event_params"]["model"], expected_model); - assert_eq!(event["event_params"]["ephemeral"], false); - assert_eq!( - event["event_params"]["thread_source"], - expected_thread_source - ); - assert_eq!( - event["event_params"]["subagent_source"], - serde_json::Value::Null - ); - assert_eq!( - event["event_params"]["parent_thread_id"], - serde_json::Value::Null - ); - assert_eq!( - event["event_params"]["initialization_mode"], - initialization_mode - ); - assert!(event["event_params"]["created_at"].as_u64().is_some()); -} - -const METRICS_PLUGIN_ID: &str = "sample@openai-curated"; -const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; - -fn write_curated_metrics_plugin(codex_home: &Path) -> Result { - let plugin_id = PluginId::parse(METRICS_PLUGIN_ID)?; - let plugin_root = PluginStore::new(codex_home.to_path_buf()).plugin_root( - &plugin_id, - &curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA), - ); - let script_path = plugin_root.join("scripts/run.sh"); - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::create_dir_all(script_path.parent().expect("script path has parent"))?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample","version":"0.1.0"}"#, - )?; - std::fs::write( - plugin_root.join("analytics.yaml"), - r#"version: 1 -operations: - scan: - path: ./scripts/run.sh - measurements: - findings: - dimensions: - severity: [high, low] - files_scanned: {} -"#, - )?; - std::fs::write( - &script_path, - r#"test -n "$CODEX_PLUGIN_METRICS_OUTPUT" -sleep "${1:-0.3}" -while [ -n "${2:-}" ] && [ ! -f "$2" ]; do sleep 0.01; done -printf '%s' '{"version":1,"measurements":[{"name":"findings","value":3,"dimensions":{"severity":"high"}},{"name":"files_scanned","value":17}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT" -"#, - )?; - - let curated_repo = codex_home.join(".tmp/plugins"); - std::fs::create_dir_all(curated_repo.join(".agents/plugins"))?; - std::fs::write( - curated_repo.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "openai-curated", - "plugins": [ - {"name": "sample", "source": {"source": "local", "path": "./plugins/sample"}} - ] -}"#, - )?; - std::fs::write( - codex_home.join(".tmp/plugins.sha"), - format!("{TEST_CURATED_PLUGIN_SHA}\n"), - )?; - Ok(script_path.into_path_buf()) -} - -async fn assert_plugin_measurement_analytics(remote: bool, background: bool) -> Result<()> { - skip_if_no_network!(Ok(())); - skip_if_remote!( - Ok(()), - "trusted plugin metrics fixture uses a local Codex home cache" - ); - skip_if_wine_exec!(Ok(()), "plugin metrics fixture is Unix-only"); - - let codex_home = TempDir::new()?; - let script_path = write_curated_metrics_plugin(codex_home.path())?.canonicalize()?; - let release_path = codex_home.path().join("release-command"); - let mut command = vec![ - "/bin/sh".to_string(), - script_path.to_string_lossy().into_owned(), - ]; - if background { - command.push("1.0".to_string()); - command.push(release_path.to_string_lossy().into_owned()); - } - let call_id = "curated-plugin-metrics"; - let arguments = serde_json::to_string(&json!({ - "cmd": shlex::try_join(command.iter().map(String::as_str))?, - "yield_time_ms": if background { 10 } else { 1_000 }, - }))?; - let command_response = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_function_call(call_id, "exec_command", &arguments), - responses::ev_completed("resp-1"), - ]); - let final_response = create_final_assistant_message_sse_response("done")?; - let pause_response = |id: &str| { - responses::sse(vec![ - responses::ev_response_created(id), - responses::ev_function_call( - id, - "request_user_input", - &json!({ - "questions": [{ - "id": "continue", "header": "Continue", "question": "Continue?", - "options": [ - {"label": "Yes", "description": "Continue the turn."}, - {"label": "No", "description": "Stop the turn."} - ] - }] - }) - .to_string(), - ), - responses::ev_completed(id), - ]) - }; - let mut response_sequence = vec![pause_response("before-command"), command_response]; - if background { - response_sequence.push(pause_response("after-launch")); - } - response_sequence.push(final_response); - let server = create_mock_responses_server_sequence(response_sequence).await; - - let analytics_server = responses::start_mock_server().await; - write_mock_responses_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &analytics_server.uri(), - )?; - let config_path = codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - let model = bundled_models_response()? - .models - .into_iter() - .find(|model| model.slug == "gpt-5.5") - .expect("bundled gpt-5.5 model"); - let models = [ - ("initial-model", ReasoningEffort::Low), - ("invoking-model", ReasoningEffort::High), - ] - .into_iter() - .map(|(slug, effort)| { - let mut model = model.clone(); - model.slug = slug.to_string(); - model.default_reasoning_level = Some(effort); - model - }) - .collect(); - let catalog_path = codex_home.path().join("measurement-models.json"); - std::fs::write( - &catalog_path, - serde_json::to_vec(&ModelsResponse { models })?, - )?; - let catalog_config = format!( - "model_catalog_json = {}", - serde_json::to_string(&catalog_path)? - ); - std::fs::write( - config_path, - format!( - r#"{catalog_config} -{config} -[features] -step_model_switching = true -default_mode_request_user_input = true -plugins = true -remote_plugin = false -unified_exec = true - -[plugins."{METRICS_PLUGIN_ID}"] -enabled = true -"#, - ), - )?; - mount_analytics_capture(&analytics_server, codex_home.path()).await?; - - let mut builder = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config(); - if remote { - builder = builder.with_exec_server_delay(Duration::ZERO); - } - let mut mcp = builder.build().await?; - if remote { - assert_eq!( - mcp.auto_env_params()?.environment_id, - codex_exec_server::REMOTE_ENVIRONMENT_ID - ); - } - timeout(Duration::from_secs(10), mcp.initialize()).await??; - let thread_request = mcp - .send_thread_start_request_with_auto_env(ThreadStartParams { - model: Some("initial-model".to_string()), - service_name: Some("codex_work_desktop".to_string()), - ..Default::default() - }) - .await?; - let thread_response: JSONRPCResponse = timeout( - Duration::from_secs(10), - mcp.read_stream_until_response_message(RequestId::Integer(thread_request)), - ) - .await??; - let ThreadStartResponse { thread, .. } = to_response(thread_response)?; - let thread_id = thread.id.clone(); - - let turn_request = mcp - .send_turn_start_request(TurnStartParams { - thread_id: thread.id, - input: vec![UserInput::Text { - text: "run the curated plugin metrics script".to_string(), - text_elements: Vec::new(), - }], - sandbox_policy: Some(SandboxPolicy::ReadOnly { - network_access: false, - }), - ..Default::default() - }) - .await?; - let turn_response = timeout( - Duration::from_secs(10), - mcp.read_stream_until_response_message(RequestId::Integer(turn_request)), - ) - .await??; - let turn_response: TurnStartResponse = to_response(turn_response)?; - for model in if background { - vec!["invoking-model", "initial-model"] - } else { - vec!["invoking-model"] - } { - let request = timeout( - Duration::from_secs(10), - mcp.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::ToolRequestUserInput { request_id, .. } = request else { - anyhow::bail!("expected request_user_input, received {request:?}"); - }; - let response: TurnSettingsUpdateResponse = mcp - .request(|request_id| ClientRequest::TurnSettingsUpdate { - request_id, - params: TurnSettingsUpdateParams { - thread_id: thread_id.clone(), - turn_id: turn_response.turn.id.clone(), - model: Some(model.to_string()), - ..Default::default() - }, - }) - .await?; - assert_eq!(response.status, TurnSettingsUpdateStatus::Applied); - mcp.send_response( - request_id, - json!({"answers": {"continue": {"answers": ["Yes"]}}}), - ) - .await?; - } - let completed_turn = timeout( - Duration::from_secs(10), - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; - let turn_id = completed_turn - .params - .as_ref() - .and_then(|params| params["turn"]["id"].as_str()) - .expect("completed turn id"); - - if background { - std::fs::write(release_path, "release")?; - } - - for measurement_name in ["findings", "files_scanned"] { - wait_for_matching_analytics_event(&analytics_server, Duration::from_secs(10), |event| { - event["event_type"] == "codex_plugin_measurement_event" - && event["event_params"]["item_id"] == call_id - && event["event_params"]["measurement_name"] == measurement_name - }) - .await?; - } - let command_event = - wait_for_matching_analytics_event(&analytics_server, Duration::from_secs(10), |event| { - event["event_type"] == "codex_command_execution_event" - && event["event_params"]["item_id"] == call_id - }) - .await?; - assert_eq!( - json!({ - "model_slug": command_event["event_params"]["model_slug"], - "sandbox_backend": command_event["event_params"]["sandbox_backend"], - "reasoning_effort": command_event["event_params"]["reasoning_effort"], - "plugin_id": command_event["event_params"]["plugin_id"], - "script_path": command_event["event_params"]["script_path"], - "item_id": command_event["event_params"]["item_id"], - "exit_code": command_event["event_params"]["exit_code"], - }), - json!({ - "model_slug": "invoking-model", - "sandbox_backend": if cfg!(target_os = "macos") { "seatbelt" } else { "seccomp" }, - "reasoning_effort": "high", - "plugin_id": METRICS_PLUGIN_ID, - "script_path": "scripts/run.sh", - "item_id": call_id, - "exit_code": 0, - }) - ); - let mut measurement_events = Vec::new(); - for request in analytics_server - .received_requests() - .await - .unwrap_or_default() - { - if request.method != "POST" || request.url.path() != "/codex/analytics-events/events" { - continue; - } - let payload: Value = serde_json::from_slice(&request.body)?; - let Some(events) = payload["events"].as_array() else { - continue; - }; - measurement_events.extend( - events - .iter() - .filter(|event| { - event["event_type"] == "codex_plugin_measurement_event" - && event["event_params"]["item_id"] == call_id - }) - .cloned(), - ); - } - measurement_events.sort_by(|left, right| { - left["event_params"]["measurement_name"] - .as_str() - .cmp(&right["event_params"]["measurement_name"].as_str()) - }); - assert_eq!(measurement_events.len(), 2); - let execution_id = measurement_events[0]["event_params"]["execution_id"] - .as_str() - .expect("measurement execution id"); - assert!(!execution_id.is_empty()); - assert_eq!( - measurement_events[1]["event_params"]["execution_id"].as_str(), - Some(execution_id) - ); - assert_eq!( - measurement_events - .iter() - .map(|event| json!({ - "plugin_id": event["event_params"]["plugin_id"], - "operation": event["event_params"]["operation"], - "measurement_name": event["event_params"]["measurement_name"], - "number_value": event["event_params"]["number_value"], - "dimensions": event["event_params"]["dimensions"], - "item_id": event["event_params"]["item_id"], - })) - .collect::>(), - vec![ - json!({ - "plugin_id": METRICS_PLUGIN_ID, - "operation": "scan", - "measurement_name": "files_scanned", - "number_value": 17.0, - "dimensions": null, - "item_id": call_id, - }), - json!({ - "plugin_id": METRICS_PLUGIN_ID, - "operation": "scan", - "measurement_name": "findings", - "number_value": 3.0, - "dimensions": {"severity": "high"}, - "item_id": call_id, - }), - ] - ); - for event in &measurement_events { - let event_params = event["event_params"] - .as_object() - .expect("measurement event params"); - let mut field_names = event_params.keys().map(String::as_str).collect::>(); - field_names.sort_unstable(); - assert_eq!( - field_names, - vec![ - "dimensions", - "execution_id", - "item_id", - "measurement_name", - "model_slug", - "number_value", - "operation", - "originator", - "plugin_id", - "reasoning_effort", - "thread_id", - "turn_id", - ] - ); - assert_eq!(event_params["thread_id"], thread_id); - assert_eq!(event_params["turn_id"], turn_id); - assert_eq!(event_params["originator"], "codex_work_desktop"); - assert_eq!(event_params["model_slug"], "invoking-model"); - assert_eq!(event_params["reasoning_effort"], "high"); - } - - Ok(()) -} - -#[cfg_attr(windows, ignore = "plugin metrics fixture is Unix-only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn unified_plugin_script_emits_measurement_analytics() -> Result<()> { - assert_plugin_measurement_analytics(/*remote*/ false, /*background*/ false).await -} - -#[cfg_attr(windows, ignore = "plugin metrics fixture is Unix-only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn remote_unified_plugin_script_emits_measurement_analytics() -> Result<()> { - assert_plugin_measurement_analytics(/*remote*/ true, /*background*/ false).await -} - -#[cfg_attr(windows, ignore = "plugin metrics fixture is Unix-only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn unified_background_plugin_script_emits_measurements_after_turn_completion() -> Result<()> { - assert_plugin_measurement_analytics(/*remote*/ false, /*background*/ true).await -} - -#[cfg_attr(windows, ignore = "plugin metrics fixture is Unix-only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn remote_unified_background_plugin_script_emits_measurements_after_turn_completion() --> Result<()> { - assert_plugin_measurement_analytics(/*remote*/ true, /*background*/ true).await -} diff --git a/codex-rs/app-server/tests/suite/v2/auth_storage_originator_tests.rs b/codex-rs/app-server/tests/suite/v2/auth_storage_originator_tests.rs deleted file mode 100644 index 86817d5f..00000000 --- a/codex-rs/app-server/tests/suite/v2/auth_storage_originator_tests.rs +++ /dev/null @@ -1,252 +0,0 @@ -//! Checks client attribution on exported storage metrics through the public RPC API. - -use super::connection_handling_websocket::connect_websocket; -use super::connection_handling_websocket::read_response_for_id; -use super::connection_handling_websocket::send_initialize_request; -use super::connection_handling_websocket::send_request; -use super::connection_handling_websocket::spawn_websocket_server; -use anyhow::Context; -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::MockResponsesConfig; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use app_test_support::write_models_cache; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnCompletedNotification; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; -use codex_login::AuthCredentialsStoreMode; -use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::collections::BTreeMap; -use std::io::Write; -use std::path::Path; -use std::time::Duration; -use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -pub(super) async fn configure_collector(codex_home: &Path) -> Result { - let collector = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/v1/metrics")) - .respond_with(ResponseTemplate::new(/*s*/ 200)) - .mount(&collector) - .await; - let endpoint = format!("{}/v1/metrics", collector.uri()); - let mut config = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(codex_home.join("config.toml"))?; - writeln!( - config, - "\n[analytics]\nenabled = true\n[otel.metrics_exporter.otlp-http]\nendpoint = {endpoint:?}\nprotocol = \"json\"" - )?; - Ok(collector) -} - -pub(super) async fn assert_saved_originators( - collector: &MockServer, - expected: &[&str], -) -> Result<()> { - let expected: BTreeMap<_, _> = expected - .iter() - .map(|value| (value.to_string(), 1_u64)) - .collect(); - let actual = tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async { - loop { - let mut actual = BTreeMap::::new(); - for request in collector.received_requests().await.unwrap_or_default() { - let body: Value = serde_json::from_slice(&request.body)?; - for resource in body["resourceMetrics"].as_array().into_iter().flatten() { - for scope in resource["scopeMetrics"].as_array().into_iter().flatten() { - for metric in scope["metrics"].as_array().into_iter().flatten() { - if metric["name"] != "codex.auth_storage.operation" { - continue; - } - for point in - metric["sum"]["dataPoints"].as_array().into_iter().flatten() - { - let tags: BTreeMap<_, _> = point["attributes"] - .as_array() - .into_iter() - .flatten() - .filter_map(|tag| { - Some(( - tag["key"].as_str()?, - tag["value"]["stringValue"].as_str()?, - )) - }) - .collect(); - if tags.get("credential_kind") == Some(&"codex") - && tags.get("operation") == Some(&"save") - { - let count = point["asInt"] - .as_u64() - .or_else(|| point["asInt"].as_str()?.parse().ok()) - .context("storage count must be an integer")?; - *actual - .entry( - tags.get("originator") - .unwrap_or(&"missing") - .to_string(), - ) - .or_default() += count; - } - } - } - } - } - } - if actual.values().sum::() >= expected.len() as u64 { - break Ok::<_, anyhow::Error>(actual); - } - tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await; - } - }) - .await??; - assert_eq!(actual, expected); - Ok(()) -} - -#[tokio::test] -async fn concurrent_connections_export_their_own_storage_originator() -> Result<()> { - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - "cli_auth_credentials_store = \"file\"\n", - )?; - let collector = configure_collector(codex_home.path()).await?; - let (_process, address) = spawn_websocket_server(codex_home.path()).await?; - let mut clients = Vec::new(); - for name in ["Codex Desktop", "codex_vscode", "private-client-name"] { - let mut client = connect_websocket(address).await?; - send_initialize_request(&mut client, /*id*/ 1, name).await?; - read_response_for_id(&mut client, /*id*/ 1).await?; - clients.push(client); - } - // All clients initialize before any storage request; a process-global identity fails this test. - for client in &mut clients { - send_request( - client, - "account/login/start", - /*id*/ 2, - Some(json!({"type": "apiKey", "apiKey": "sk-test-key"})), - ) - .await?; - } - for client in &mut clients { - let response = read_response_for_id(client, /*id*/ 2).await?; - assert_eq!(response.result, json!({"type": "apiKey"})); - } - assert_saved_originators(&collector, &["codex_desktop", "codex_vscode", "other"]).await -} - -#[tokio::test] -async fn turn_token_refresh_exports_thread_storage_originator() -> Result<()> { - let codex_home = TempDir::new()?; - let backend = MockServer::start().await; - MockResponsesConfig::new(&backend.uri()) - .with_root_config("cli_auth_credentials_store = \"file\"") - .with_provider_config("requires_openai_auth = true") - .write(codex_home.path())?; - write_models_cache(codex_home.path()).await?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("initial-access-token") - .account_id("account-123") - .chatgpt_user_id("user-123"), - AuthCredentialsStoreMode::File, - )?; - let collector = configure_collector(codex_home.path()).await?; - - Mock::given(method("POST")) - .and(path("/oauth/token")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "access_token": "refreshed-access-token", - "refresh_token": "refreshed-refresh-token", - }))) - .expect(/*r*/ 1) - .mount(&backend) - .await; - // Fresh credentials prevent startup refresh. The turn first reloads storage on 401, - // then refreshes and persists the tokens when the retry is also unauthorized. - let responses_mock = responses::mount_response_sequence( - &backend, - vec![ - ResponseTemplate::new(/*s*/ 401), - ResponseTemplate::new(/*s*/ 401), - responses::sse_response(responses::sse(vec![ - responses::ev_response_created("resp-turn"), - responses::ev_completed("resp-turn"), - ])), - ], - ) - .await; - let refresh_url = format!("{}/oauth/token", backend.uri()); - let mut server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[ - ("OPENAI_API_KEY", None), - ( - REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR, - Some(refresh_url.as_str()), - ), - ]) - .build() - .await?; - server - .initialize_with_client_info(ClientInfo { - name: "codex_vscode".to_string(), - title: None, - version: "0.1.0".to_string(), - }) - .await?; - let request = server - .send_thread_start_request_with_auto_env(ThreadStartParams::default()) - .await?; - let thread: ThreadStartResponse = server.read_response(request).await?; - let request = server - .send_turn_start_request(TurnStartParams { - thread_id: thread.thread.id, - input: vec![UserInput::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - let _: TurnStartResponse = server.read_response(request).await?; - let notification = server - .read_stream_until_notification_message("turn/completed") - .await?; - let completed: TurnCompletedNotification = - serde_json::from_value(notification.params.context("turn/completed params")?)?; - assert_eq!(completed.turn.status, TurnStatus::Completed); - assert_eq!( - responses_mock - .requests() - .iter() - .map(|request| request.header("authorization")) - .collect::>(), - vec![ - Some("Bearer initial-access-token".to_string()), - Some("Bearer initial-access-token".to_string()), - Some("Bearer refreshed-access-token".to_string()), - ] - ); - assert_saved_originators(&collector, &["codex_vscode"]).await?; - backend.verify().await; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/client_metadata.rs b/codex-rs/app-server/tests/suite/v2/client_metadata.rs index 76fe2548..54ec1aea 100644 --- a/codex-rs/app-server/tests/suite/v2/client_metadata.rs +++ b/codex-rs/app-server/tests/suite/v2/client_metadata.rs @@ -30,10 +30,6 @@ use std::collections::HashMap; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::captured_analytics_events; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_analytics_event; - // Bazel CI can spend tens of seconds starting app-server subprocesses or // processing turn RPCs under load. const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); @@ -341,7 +337,6 @@ async fn turn_start_sends_nested_subagent_lineage_after_cold_thread_resume_v2() .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) .with_provider_config("supports_websockets = false") .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let root_thread_id = CoreThreadId::new(); let root_thread_id_str = root_thread_id.to_string(); @@ -419,32 +414,7 @@ async fn turn_start_sends_nested_subagent_lineage_after_cold_thread_resume_v2() assert_eq!(metadata["turn_id"].as_str(), Some(turn.id.as_str())); assert!(metadata.get("forked_from_thread_id").is_none()); - let turn_event = - wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; - let params = &turn_event["event_params"]; - assert_eq!( - ( - params["total_tool_call_count"].as_u64(), - params["web_search_count"].as_u64() - ), - (Some(1), Some(1)) - ); timeout(DEFAULT_READ_TIMEOUT, mcp.shutdown_gracefully()).await??; - let events = captured_analytics_events(&server).await; - let count = |event_type: &str| { - events - .iter() - .filter(|event| { - event["event_type"] == event_type - && event["event_params"]["thread_id"] == thread.id - && event["event_params"]["turn_id"] == turn.id - }) - .count() - }; - assert_eq!( - (count("codex_turn_event"), count("codex_web_search_event")), - (1, 1) - ); Ok(()) } @@ -478,7 +448,6 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2( .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) .with_provider_config("supports_websockets = false") .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -602,15 +571,6 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2( first_metadata["misalignment_override"], ); - let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; - assert_eq!( - ( - event["event_params"]["turn_trigger"].as_str(), - event["event_params"]["codex_turn_source"].as_str(), - ), - (Some("user"), Some("steer-source")) - ); - Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/compaction.rs b/codex-rs/app-server/tests/suite/v2/compaction.rs index 784e6f92..7b732da0 100644 --- a/codex-rs/app-server/tests/suite/v2/compaction.rs +++ b/codex-rs/app-server/tests/suite/v2/compaction.rs @@ -44,10 +44,6 @@ use std::collections::BTreeMap; use tempfile::TempDir; use test_case::test_case; use tokio::time::timeout; -use wiremock::ResponseTemplate; - -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; // macOS and Windows Bazel CI can spend tens of seconds starting app-server // subprocesses or processing test RPCs under load. @@ -274,96 +270,6 @@ async fn prediction_context_failure_does_not_compact(reset_context: bool) -> Res Ok(()) } -#[test_case(CompactionRoute::Local, Some(300), 429, "usage_limit_reached"; "local five hour")] -#[test_case(CompactionRoute::Remote, Some(10_080), 429, "usage_limit_reached"; "remote weekly")] -#[test_case(CompactionRoute::Local, None, 429, "usage_limit_reached"; "missing window")] -#[test_case(CompactionRoute::Remote, Some(300), 400, "invalid_request"; "other error")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn compaction_error_window_reaches_analytics( - route: CompactionRoute, - window: Option, - status: u16, - expected_error: &str, -) -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let seed = responses::sse(vec![ - responses::ev_assistant_message("seed", "FIRST_REPLY"), - responses::ev_completed_with_tokens("seed", /*total_tokens*/ 120), - ]); - let mut error = json!({ - "type": if status == 429 { "usage_limit_reached" } else { "invalid_request_error" }, - "message": "request failed", - }); - if let Some(window) = window { - error["limit_window_minutes"] = json!(window); - } - let _requests = responses::mount_response_sequence( - &server, - vec![ - responses::sse_response(seed), - ResponseTemplate::new(status).set_body_json(json!({ "error": error })), - ], - ) - .await; - let codex_home = TempDir::new()?; - let mut config = compaction_config(&server.uri(), /*auto_compact_limit*/ 1_000_000) - .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())); - if let CompactionRoute::Remote = route { - config = config - .with_provider_name("OpenAI") - .with_provider_config("requires_openai_auth = true"); - } - config.write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - let thread_id = start_thread(&mut mcp).await?; - send_turn_and_wait(&mut mcp, &thread_id, "seed history").await?; - let compact_id = mcp - .send_thread_compact_start_request(ThreadCompactStartParams { - thread_id: thread_id.clone(), - }) - .await?; - let _: ThreadCompactStartResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(compact_id)).await??; - - let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_compaction_event" - && event["event_params"]["thread_id"] == thread_id - }) - .await?; - let params = &event["event_params"]; - let implementation = match route { - CompactionRoute::Local => "responses", - CompactionRoute::Remote => "responses_compaction_v2", - }; - let expected_window = if status == 429 { window } else { None }; - assert_eq!( - json!([ - params["implementation"], - params["phase"], - params["status"], - params["codex_error_kind"], - params["usage_limit_window_minutes"], - ]), - json!([ - implementation, - "standalone_turn", - "failed", - expected_error, - expected_window - ]) - ); - Ok(()) -} - #[test_case(CompactionRoute::Local; "local")] #[test_case(CompactionRoute::Remote; "streamed remote")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] 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 781b7a76..6fa2e019 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -600,118 +600,14 @@ async fn config_read_disables_guardian_v2_when_managed_config_requires_guardian_ } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn managed_otel_tracestate_merges_fields_and_protects_only_required_fields() -> Result<()> { - let codex_home = TempDir::new()?; - write_config( - &codex_home, - r#"[otel.tracestate.vendor] -tenant = "user" -region = "us" -"#, - )?; - std::fs::write( - codex_home.path().join("requirements.toml"), - "[otel.tracestate.vendor]\ntenant = \"enterprise\"\n", - )?; - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let read_id = app_server - .send_config_read_request(ConfigReadParams { - include_layers: false, - cwd: None, - }) - .await?; - let response: ConfigReadResponse = - timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(read_id)).await??; - assert_eq!( - response.config.additional["otel"]["tracestate"], - json!({ "vendor": { "tenant": "enterprise", "region": "us" } }), - ); - assert!( - !response - .origins - .contains_key("otel.tracestate.vendor.tenant") - ); - assert!( - response - .origins - .contains_key("otel.tracestate.vendor.region") - ); - - let write_id = app_server - .send_config_value_write_request(ConfigValueWriteParams { - file_path: None, - key_path: "otel.tracestate.vendor.region".to_string(), - value: json!("eu"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await?; - let _: ConfigWriteResponse = - timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(write_id)).await??; - - for key_path in [ - "otel.tracestate.vendor.tenant", - "otel.tracestate.vendor", - "otel.tracestate", - ] { - let write_id = app_server - .send_config_value_write_request(ConfigValueWriteParams { - file_path: None, - key_path: key_path.to_string(), - value: json!("user"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_error_message(RequestId::Integer(write_id)), - ) - .await??; - assert_eq!( - error - .error - .data - .as_ref() - .and_then(|data| data.get("config_write_error_code")), - Some(&json!("configRequirementReadonly")), - "{key_path}", - ); - } - let read_id = app_server - .send_config_read_request(ConfigReadParams { - include_layers: false, - cwd: None, - }) - .await?; - let response: ConfigReadResponse = - timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(read_id)).await??; - assert_eq!( - response.config.additional["otel"]["tracestate"], - json!({ "vendor": { "tenant": "enterprise", "region": "eu" } }), - ); - Ok(()) -} - -#[test_case::test_case("json", "none"; "json_and_disabled_metrics")] -#[test_case::test_case("binary", "statsig"; "binary_and_statsig_metrics")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn config_requirements_read_redacts_otel_exporter_headers( - protocol: &str, - metrics_exporter: &str, -) -> Result<()> { +async fn config_requirements_read_ignores_legacy_otel_exporters() -> Result<()> { let codex_home = TempDir::new()?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_auto_env() .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) .await?; - // Read policy without starting exporters or opening the example TLS files. + // Legacy exporter keys still parse but are ignored and never echoed back. std::fs::write( codex_home.path().join("requirements.toml"), r#"[otel] @@ -721,13 +617,11 @@ log_sse_deltas = false log_agent_responses = true log_guardian_assessments = false environment = "managed" -exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/logs", protocol = "$PROTOCOL", headers = { Authorization = "Bearer managed-token" }, tls = { ca-certificate = "ca.pem", client-certificate = "client.pem", client-private-key = "client-key.pem" } } } +exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/logs", protocol = "json", headers = { Authorization = "Bearer managed-token" }, tls = { ca-certificate = "ca.pem", client-certificate = "client.pem", client-private-key = "client-key.pem" } } } trace_exporter = { otlp-grpc = { endpoint = "http://127.0.0.1:4317", headers = { "x-api-key" = "managed-grpc-secret" }, tls = { ca-certificate = "ca.pem" } } } -metrics_exporter = "$METRICS_EXPORTER" +metrics_exporter = "statsig" span_attributes = { "service.name" = "managed-service" } -tracestate = { managed = { tenant = "enterprise" } }"# - .replace("$PROTOCOL", protocol) - .replace("$METRICS_EXPORTER", metrics_exporter), +tracestate = { managed = { tenant = "enterprise" } }"#, )?; let request_id = mcp.send_config_requirements_read_request().await?; let response: serde_json::Value = @@ -738,43 +632,12 @@ tracestate = { managed = { tenant = "enterprise" } }"# "tool_result": { "max_bytes": 1024 }, "log_user_prompt": false, "log_sse_deltas": false, - "log_agent_responses": true, - "log_guardian_assessments": false, - "environment": "managed", - "exporter": { - "otlp-http": { - "endpoint": "http://127.0.0.1:1/v1/logs", - "headers": { "Authorization": "[redacted]" }, - "protocol": protocol, - "tls": { - "ca-certificate": codex_home.path().join("ca.pem"), - "client-certificate": codex_home.path().join("client.pem"), - "client-private-key": codex_home.path().join("client-key.pem"), - }, - }, - }, - "trace_exporter": { - "otlp-grpc": { - "endpoint": "http://127.0.0.1:4317", - "headers": { "x-api-key": "[redacted]" }, - "tls": { - "ca-certificate": codex_home.path().join("ca.pem"), - "client-certificate": null, - "client-private-key": null, - }, - }, - }, - "metrics_exporter": metrics_exporter, - "span_attributes": { "service.name": "managed-service" }, - "tracestate": { "managed": { "tenant": "enterprise" } }, }) ); - // API clients must preserve certificate paths from servers on either OS. - let mut response = response; - response["requirements"]["otel"]["exporter"]["otlp-http"]["tls"]["ca-certificate"] = - json!(r"C:\certs\ca.pem"); - response["requirements"]["otel"]["trace_exporter"]["otlp-grpc"]["tls"]["ca-certificate"] = - json!("/etc/certs/ca.pem"); + let serialized = response.to_string(); + for secret in ["managed-token", "managed-grpc-secret", "managed-service"] { + assert!(!serialized.contains(secret), "response leaked {secret}"); + } let typed: ConfigRequirementsReadResponse = serde_json::from_value(response.clone())?; assert_eq!( serde_json::to_value( @@ -788,8 +651,7 @@ tracestate = { managed = { tenant = "enterprise" } }"# } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn config_read_redacts_otel_exporter_headers_from_effective_config_and_layers() -> Result<()> -{ +async fn config_read_drops_legacy_otel_exporters_and_redacts_their_layer_headers() -> Result<()> { let codex_home = TempDir::new()?; write_config( &codex_home, @@ -816,11 +678,7 @@ metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/metrics", p let response: ConfigReadResponse = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; let serialized = serde_json::to_string(&response)?; - let effective_otel = response - .config - .additional - .get("otel") - .expect("effective OTEL config"); + let effective_otel = response.config.additional.get("otel"); let layers = response.layers.as_ref().expect("included config layers"); let user_otel = layers .iter() @@ -846,7 +704,8 @@ metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/metrics", p ("metrics_exporter", "otlp-http", "metrics-secret"), ] { let expected = json!({ "Authorization": "[redacted]" }); - assert_eq!(effective_otel[field][transport]["headers"], expected); + // Exporters were removed, so the effective config no longer carries them. + assert_eq!(effective_otel.and_then(|otel| otel.get(field)), None); assert_eq!(user_otel[field][transport]["headers"], expected); assert!(!serialized.contains(secret), "response leaked {field}"); } diff --git a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs index fb0711c9..34422b52 100644 --- a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs +++ b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs @@ -579,8 +579,7 @@ pub(super) async fn spawn_websocket_server_with_args( .stdout(Stdio::null()) .stderr(Stdio::piped()) .env("CODEX_HOME", codex_home) - .env("RUST_LOG", "warn") - .env("OTEL_METRIC_EXPORT_INTERVAL", "200"); + .env("RUST_LOG", "warn"); let mut process = cmd .kill_on_drop(true) diff --git a/codex-rs/app-server/tests/suite/v2/critical_path_analytics_tests.rs b/codex-rs/app-server/tests/suite/v2/critical_path_analytics_tests.rs deleted file mode 100644 index e47dcdfb..00000000 --- a/codex-rs/app-server/tests/suite/v2/critical_path_analytics_tests.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! Verify Core capture reaches the existing analytics endpoint on terminal turns. - -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; -use anyhow::Result; -use app_test_support::MockResponsesConfig; -use app_test_support::TestAppServer; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::UserInput; -use codex_features::Feature; -use core_test_support::responses; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::BTreeMap; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path_regex; - -#[derive(Clone, Copy)] -enum Finish { - Complete, - Interrupt, -} - -#[derive(Clone, Copy)] -enum Capture { - Default, - Enabled, - Disabled, -} - -#[test_case::test_case(Finish::Complete, Capture::Default; "complete_default")] -#[test_case::test_case(Finish::Complete, Capture::Enabled; "complete_enabled")] -#[test_case::test_case(Finish::Complete, Capture::Disabled; "complete_disabled")] -#[test_case::test_case(Finish::Interrupt, Capture::Default; "interrupt_default")] -#[test_case::test_case(Finish::Interrupt, Capture::Enabled; "interrupt_enabled")] -#[test_case::test_case(Finish::Interrupt, Capture::Disabled; "interrupt_disabled")] -#[tokio::test] -async fn critical_path_reaches_turn_event(finish: Finish, capture: Capture) -> Result<()> { - skip_if_no_network!(Ok(())); - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("response-1"), - responses::ev_assistant_message("answer", "Done"), - responses::ev_completed("response-1"), - ]); - let mut response = ResponseTemplate::new(200).set_body_raw(body, "text/event-stream"); - if matches!(finish, Finish::Interrupt) { - response = response.set_delay(Duration::from_secs(60)); - } - Mock::given(method("POST")) - .and(path_regex(".*/responses$")) - .respond_with(response) - .mount(&server) - .await; - let codex_home = TempDir::new()?; - let mut features = BTreeMap::from([(Feature::RuntimeMetrics, true)]); - match capture { - Capture::Default => {} - Capture::Enabled => { - features.insert(Feature::CriticalPathTiming, true); - } - Capture::Disabled => { - features.insert(Feature::CriticalPathTiming, false); - } - } - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!("chatgpt_base_url = {:?}", server.uri())) - .with_provider_config("supports_websockets = false") - .with_features(&features) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - let mut app = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - let thread = app.start_thread(ThreadStartParams::default()).await?.thread; - let params = TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Hello".into(), - text_elements: Vec::new(), - }], - ..Default::default() - }; - let (turn_id, expected_status) = match finish { - Finish::Complete => { - let completed = app.start_turn_and_wait_for_completion(params).await?; - (completed.turn.id, "completed") - } - Finish::Interrupt => { - let started: TurnStartResponse = app - .request(|request_id| ClientRequest::TurnStart { request_id, params }) - .await?; - // Wait for sampling to begin before interrupting, without a timing-dependent sleep. - timeout(Duration::from_secs(10), async { - loop { - if server - .received_requests() - .await - .unwrap_or_default() - .iter() - .any(|r| r.url.path().ends_with("/responses")) - { - break; - } - tokio::task::yield_now().await; - } - }) - .await?; - app.interrupt_turn_and_wait_for_aborted( - thread.id.clone(), - started.turn.id.clone(), - Duration::from_secs(10), - ) - .await?; - (started.turn.id, "interrupted") - } - }; - let event = wait_for_matching_analytics_event(&server, Duration::from_secs(30), |event| { - event["event_type"] == "codex_turn_event" && event["event_params"]["turn_id"] == turn_id - }) - .await?; - let p = &event["event_params"]; - assert_eq!( - json!([p["thread_id"], p["status"]]), - json!([thread.id, expected_status]) - ); - let fields = [ - "critical_path_duration_ms", - "critical_path_sampling_ms", - "critical_path_compaction_ms", - "critical_path_auto_review_ms", - "critical_path_user_wait_ms", - "critical_path_tools_ms", - "critical_path_overhead_ms", - "critical_path_unknown_ms", - ]; - if matches!(capture, Capture::Enabled) { - assert_eq!(p["critical_path_status"], "complete"); - assert_eq!( - p.get("critical_path_auto_review_overhead_ms"), - Some(&json!(0)) - ); - let inference = p["critical_path_inference_ms"] - .as_u64() - .expect("inference duration"); - let phases = p["critical_path_sampling_ms"] - .as_u64() - .expect("sampling duration") - + p["critical_path_compaction_ms"] - .as_u64() - .expect("compaction duration"); - assert!(phases <= inference && inference - phases <= 1); - assert_eq!(p[fields[0]], p["duration_ms"]); - let total = p[fields[0]] - .as_u64() - .expect("complete capture has a numeric total"); - let sum: u64 = fields[1..] - .iter() - .map(|key| { - p[key] - .as_u64() - .expect("complete capture has numeric categories") - }) - .sum(); - assert!(sum <= total && total - sum <= 6); - assert_eq!( - json!([ - p["critical_path_user_wait_ms"], - p["critical_path_tools_ms"], - p["critical_path_auto_review_ms"], - p["critical_path_unknown_ms"], - ]), - json!([0, 0, 0, 0]) - ); - } else { - assert_eq!(p["critical_path_status"], "disabled"); - assert_eq!( - p.get("critical_path_auto_review_overhead_ms"), - Some(&serde_json::Value::Null) - ); - assert_eq!( - p.get("critical_path_inference_ms"), - Some(&serde_json::Value::Null) - ); - assert_eq!( - fields.map(|key| p.get(key)), - [Some(&serde_json::Value::Null); 8] - ); - } - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/executor_skills.rs b/codex-rs/app-server/tests/suite/v2/executor_skills.rs index 4e5ce64b..f5f57544 100644 --- a/codex-rs/app-server/tests/suite/v2/executor_skills.rs +++ b/codex-rs/app-server/tests/suite/v2/executor_skills.rs @@ -29,9 +29,6 @@ use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; - #[cfg(target_os = "macos")] const READ_TIMEOUT: Duration = Duration::from_secs(60); #[cfg(not(target_os = "macos"))] @@ -113,17 +110,11 @@ async fn exercise_executor_skill(scenario: ExecutorSkillScenario) -> Result<()> } else { ("never", "") }; - let analytics_config = if scenario == ExecutorSkillScenario::ExplicitOnly { - format!("chatgpt_base_url = \"{}\"", server.uri()) - } else { - String::new() - }; std::fs::write( codex_home.path().join("config.toml"), format!( r#" model = "mock-model" -{analytics_config} approval_policy = "{approval_policy}" {sandbox_config} model_provider = "mock_provider" @@ -143,9 +134,6 @@ stream_max_retries = 0 server.uri() ), )?; - if scenario == ExecutorSkillScenario::ExplicitOnly { - mount_analytics_capture(&server, codex_home.path()).await?; - } let local_skill_dir = codex_home.path().join("skills/local-deploy"); std::fs::create_dir_all(&local_skill_dir)?; std::fs::write( @@ -471,18 +459,6 @@ stream_max_retries = 0 app_server.read_stream_until_notification_message("turn/completed"), ) .await??; - if scenario == ExecutorSkillScenario::ExplicitOnly { - for invocation_type in ["explicit", "implicit"] { - let event = wait_for_matching_analytics_event(&server, READ_TIMEOUT, |event| { - event["event_type"] == "skill_invocation" - && event["event_params"]["invoke_type"] == invocation_type - }) - .await?; - assert_eq!(event["event_params"]["plugin_id"], authority_id); - assert_eq!(event["event_params"]["skill_scope"], "user"); - } - } - let requests = response_mock.requests(); let request = &requests[0]; if scenario == ExecutorSkillScenario::VisibleWithBudgetWarning { diff --git a/codex-rs/app-server/tests/suite/v2/external_agent_config.rs b/codex-rs/app-server/tests/suite/v2/external_agent_config.rs index 75463040..9c40a308 100644 --- a/codex-rs/app-server/tests/suite/v2/external_agent_config.rs +++ b/codex-rs/app-server/tests/suite/v2/external_agent_config.rs @@ -6,7 +6,6 @@ use app_test_support::ChatGptAuthFixture; use app_test_support::MockResponsesConfig; use app_test_support::TestAppServer; use app_test_support::create_mock_responses_server_repeating_assistant; -use app_test_support::start_analytics_events_server; use app_test_support::write_chatgpt_auth; #[cfg(unix)] use codex_app_server_protocol::ConfigReadParams; @@ -57,8 +56,6 @@ use tempfile::TempDir; use tokio::io::AsyncWriteExt; use tokio::time::timeout; -use super::analytics::wait_for_analytics_event; - const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); const SECONDARY_MIGRATION_SOURCE: &str = concat!("cur", "sor"); @@ -1325,18 +1322,10 @@ async fn external_agent_config_import_reports_failed_sync_import_in_completion() )?; std::fs::write(codex_home.path().join("config.toml"), "invalid = [")?; let home_dir = codex_home.path().display().to_string(); - let analytics_capture_file = codex_home.path().join("analytics-events.jsonl"); - let analytics_capture_file = analytics_capture_file.display().to_string(); let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_auto_env() - .with_env_overrides(&[ - ("HOME", Some(home_dir.as_str())), - ( - "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE", - Some(analytics_capture_file.as_str()), - ), - ]) + .with_env_overrides(&[("HOME", Some(home_dir.as_str()))]) .build_initialized_with_timeout(DEFAULT_TIMEOUT) .await?; @@ -1399,63 +1388,13 @@ async fn external_agent_config_import_reports_failed_sync_import_in_completion() assert!(commands_result.successes.is_empty()); assert!(commands_result.failures.is_empty()); - let events = timeout(DEFAULT_TIMEOUT, async { - loop { - let contents = match std::fs::read_to_string(&analytics_capture_file) { - Ok(contents) => contents, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - } - Err(err) => return Err(err.into()), - }; - let mut captured_events = Vec::new(); - for line in contents.lines() { - let payload: serde_json::Value = serde_json::from_str(line)?; - let Some(events) = payload["events"].as_array() else { - continue; - }; - captured_events.extend(events.iter().cloned()); - } - if captured_events.iter().any(|event| { - event["event_type"] == "codex_onboarding_external_agent_import_complete" - && event["event_params"]["type"] == "COMMANDS" - }) { - return Ok::, anyhow::Error>(captured_events); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await??; - let event = events - .iter() - .find(|event| { - event["event_type"] == "codex_onboarding_external_agent_import_failure" - && event["event_params"]["type"] == "CONFIG" - }) - .expect("config failure analytics event"); - let event_params = &event["event_params"]; - assert_eq!(event_params["import_id"], import_id); - assert_eq!(event_params["source"], "test_import"); - assert_eq!(event_params["provider_id"], "test-provider-42"); - assert_eq!(event_params["type"], "CONFIG"); - assert_eq!(event_params["failure_stage"], "import_request_failed"); - assert_eq!(event_params["error_type"], "invalid_existing_config"); - assert!(event_params.get("raw_errors").is_none()); - assert!(event_params.get("message").is_none()); - assert!(!events.iter().any(|event| { - event["event_type"] == "codex_onboarding_external_agent_import_failure" - && event["event_params"]["type"] == "COMMANDS" - })); - Ok(()) } #[tokio::test] -async fn external_agent_config_import_completed_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; +async fn external_agent_config_import_reports_missing_session_in_completion() -> Result<()> { let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; + std::fs::write(codex_home.path().join("config.toml"), "")?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") @@ -1518,46 +1457,13 @@ async fn external_agent_config_import_completed_tracks_analytics_event() -> Resu Some("session_not_detected") ); - let event = wait_for_analytics_event( - &analytics_server, - DEFAULT_TIMEOUT, - "codex_onboarding_external_agent_import_complete", - ) - .await?; - let event_params = &event["event_params"]; - assert_eq!(event_params["import_id"], serde_json::json!(import_id)); - assert_eq!(event_params["source"], "test_import"); - assert_eq!(event_params["provider_id"], "test-provider-42"); - assert_eq!(event_params["type"], "SESSIONS"); - assert_eq!(event_params["success_count"], 0); - assert_eq!(event_params["failed_count"], 1); - assert!(event_params.get("raw_errors").is_none()); - - let event = wait_for_analytics_event( - &analytics_server, - DEFAULT_TIMEOUT, - "codex_onboarding_external_agent_import_failure", - ) - .await?; - let event_params = &event["event_params"]; - assert_eq!(event_params["import_id"], serde_json::json!(import_id)); - assert_eq!(event_params["source"], "test_import"); - assert_eq!(event_params["provider_id"], "test-provider-42"); - assert_eq!(event_params["type"], "SESSIONS"); - assert_eq!(event_params["failure_stage"], "session_missing"); - assert_eq!(event_params["error_type"], "session_missing"); - assert_eq!(event_params["sub_error_type"], "session_not_detected"); - assert!(event_params.get("raw_errors").is_none()); - assert!(event_params.get("message").is_none()); - Ok(()) } #[tokio::test] async fn external_agent_config_import_reports_session_config_error_subtype() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; + std::fs::write(codex_home.path().join("config.toml"), "")?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") @@ -1636,33 +1542,13 @@ async fn external_agent_config_import_reports_session_config_error_subtype() -> Some("failed_to_load_session_config_invalid_data") ); - let event = wait_for_analytics_event( - &analytics_server, - DEFAULT_TIMEOUT, - "codex_onboarding_external_agent_import_failure", - ) - .await?; - let event_params = &event["event_params"]; - assert_eq!(event_params["import_id"], serde_json::json!(import_id)); - assert_eq!(event_params["source"], "test_import"); - assert_eq!(event_params["provider_id"], "test-provider-42"); - assert_eq!(event_params["type"], "SESSIONS"); - assert_eq!(event_params["failure_stage"], "session_persist"); - assert_eq!( - event_params["sub_error_type"], - "failed_to_load_session_config_invalid_data" - ); - assert!(event_params.get("raw_errors").is_none()); - assert!(event_params.get("message").is_none()); - Ok(()) } #[tokio::test] async fn external_agent_config_import_reinstalls_plugins_from_known_marketplaces() -> Result<()> { let codex_home = TempDir::new()?; - let analytics_server = start_analytics_events_server().await?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; + std::fs::write(codex_home.path().join("config.toml"), "")?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") @@ -1802,30 +1688,6 @@ async fn external_agent_config_import_reinstalls_plugins_from_known_marketplaces "plugin `missing` was not found in marketplace `debug`" ); - let event = wait_for_analytics_event( - &analytics_server, - DEFAULT_TIMEOUT, - "codex_plugin_install_failed", - ) - .await?; - let event_params = &event["event_params"]; - assert_eq!(event_params["plugin_id"], "missing@debug"); - assert_eq!(event_params["plugin_name"], "missing"); - assert_eq!(event_params["marketplace_name"], "debug"); - assert_eq!(event_params["source"], "external_agent_migration"); - assert_eq!(event_params["error_type"], "plugin_not_found"); - - let event = wait_for_analytics_event( - &analytics_server, - DEFAULT_TIMEOUT, - "codex_onboarding_external_agent_import_failure", - ) - .await?; - let event_params = &event["event_params"]; - assert_eq!(event_params["type"], "PLUGINS"); - assert_eq!(event_params["failure_stage"], "plugin_import"); - assert_eq!(event_params["error_type"], "plugin_not_found"); - let request_id = mcp .send_plugin_list_request(PluginListParams { cwds: None, @@ -2753,10 +2615,3 @@ async fn external_agent_config_import_compacts_huge_session_before_first_follow_ assert!(second.contains("LOCAL_SUMMARY")); Ok(()) } - -fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!("chatgpt_base_url = \"{base_url}\"\n"), - ) -} diff --git a/codex-rs/app-server/tests/suite/v2/feedback.rs b/codex-rs/app-server/tests/suite/v2/feedback.rs index 2bd92377..cc11ff2c 100644 --- a/codex-rs/app-server/tests/suite/v2/feedback.rs +++ b/codex-rs/app-server/tests/suite/v2/feedback.rs @@ -5,106 +5,18 @@ use app_test_support::TestAppServer; use codex_app_server_protocol::RequestId; use pretty_assertions::assert_eq; use serde_json::json; -use tokio::io::AsyncBufReadExt; -use tokio::io::AsyncWriteExt; -use tokio::io::BufReader; use tokio::net::TcpListener; use tokio::time::timeout; #[tokio::test] -async fn feedback_upload_limits_concurrency_and_releases_failed_uploads() -> Result<()> { - let proxy = TcpListener::bind("127.0.0.1:0").await?; - let proxy_uri = format!("http://{}", proxy.local_addr()?); - let mut app_server = TestAppServer::builder() - .with_env_overrides(&[ - ("HTTPS_PROXY", Some(proxy_uri.as_str())), - ("https_proxy", Some(proxy_uri.as_str())), - ("NO_PROXY", Some("")), - ("no_proxy", Some("")), - ]) - .build_initialized() - .await?; - - let mut pending = Vec::new(); - for _ in 0..3 { - let request_id = app_server - .send_raw_request( - "feedback/upload", - Some(json!({ "classification": "bug", "includeLogs": false })), - ) - .await?; - let (stream, _) = timeout(Duration::from_secs(/*secs*/ 15), proxy.accept()).await??; - let mut stream = BufReader::new(stream); - let mut request = String::new(); - timeout( - Duration::from_secs(/*secs*/ 15), - stream.read_line(&mut request), - ) - .await??; - assert!(request.starts_with("CONNECT ")); - pending.push((request_id, stream.into_inner())); - } - - let excess_id = app_server - .send_raw_request( - "feedback/upload", - Some(json!({ "classification": "bug", "includeLogs": false })), - ) - .await?; - let error = timeout( - Duration::from_secs(/*secs*/ 15), - app_server.read_stream_until_error_message(RequestId::Integer(excess_id)), - ) - .await??; - - assert_eq!(error.error.code, -32001); - - let unavailable = - b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; - for (request_id, mut stream) in pending { - stream.write_all(unavailable).await?; - stream.shutdown().await?; - let error = timeout( - Duration::from_secs(/*secs*/ 15), - app_server.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert_eq!(error.error.code, -32603); - assert!(error.error.message.contains("failed to upload feedback")); - } - - let request_id = app_server - .send_raw_request( - "feedback/upload", - Some(json!({ "classification": "bug", "includeLogs": false })), - ) - .await?; - let (mut stream, _) = timeout(Duration::from_secs(/*secs*/ 15), proxy.accept()).await??; - stream.write_all(unavailable).await?; - stream.shutdown().await?; - let error = timeout( - Duration::from_secs(/*secs*/ 15), - app_server.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert_eq!(error.error.code, -32603); - Ok(()) -} - -#[tokio::test] -async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures() -> Result<()> { +async fn feedback_save_recovers_persisted_evidence_and_reports_sqlite_failures() -> Result<()> { use std::collections::HashSet; use std::io::Read; - use std::sync::Arc; use app_test_support::MockResponsesConfig; use codex_app_server_protocol::ClientNotification; use codex_protocol::ThreadId; - use tokio::io::AsyncReadExt; - use tokio_rustls::TlsAcceptor; - use tokio_rustls::rustls; - // Terminate HTTPS locally and capture real Sentry envelopes. Never forward uploads. let home = tempfile::tempdir()?; let daemon_logs = home.path().join("app-server-daemon"); std::fs::create_dir(&daemon_logs)?; @@ -124,70 +36,6 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures daemon_logs.join("daemon-updater.stderr.log"), "current updater diagnostic", )?; - let cert = rcgen::generate_simple_self_signed(vec!["o33249.ingest.us.sentry.io".to_string()])?; - let cert_path = home.path().join("feedback-ca.pem"); - std::fs::write(&cert_path, cert.cert.pem())?; - let tls = rustls::ServerConfig::builder_with_provider(Arc::new( - rustls::crypto::aws_lc_rs::default_provider(), - )) - .with_safe_default_protocol_versions()? - .with_no_client_auth() - .with_single_cert( - vec![cert.cert.der().clone()], - rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()).into(), - )?; - let acceptor = TlsAcceptor::from(Arc::new(tls)); - let listener = TcpListener::bind("127.0.0.1:0").await?; - let proxy_uri = format!("http://{}", listener.local_addr()?); - let (uploads_tx, mut uploads_rx) = tokio::sync::mpsc::unbounded_channel(); - let _proxy = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move { - while let Ok((stream, _)) = listener.accept().await { - let mut stream = BufReader::new(stream); - loop { - let mut line = String::new(); - anyhow::ensure!(stream.read_line(&mut line).await? > 0, "missing CONNECT"); - if line == "\r\n" { - break; - } - } - stream - .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") - .await?; - let mut stream = BufReader::new(acceptor.accept(stream.into_inner()).await?); - let mut length = None; - loop { - let mut line = String::new(); - anyhow::ensure!( - stream.read_line(&mut line).await? > 0, - "missing HTTP headers" - ); - if line == "\r\n" { - break; - } - if let Some((name, value)) = line.split_once(':') - && name.eq_ignore_ascii_case("content-length") - { - length = Some(value.trim().parse::()?); - } - } - let length = length.ok_or_else(|| anyhow::anyhow!("missing content length"))?; - anyhow::ensure!(length < 16 * 1024 * 1024, "unexpected envelope size"); - let mut body = vec![0; length]; - stream.read_exact(&mut body).await?; - if body.starts_with(&[0x1f, 0x8b]) { - let mut decoded = Vec::new(); - flate2::read::GzDecoder::new(body.as_slice()).read_to_end(&mut decoded)?; - body = decoded; - } - uploads_tx.send(body)?; - stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}") - .await?; - stream.flush().await?; - } - Ok::<(), anyhow::Error>(()) - })); - let models = wiremock::MockServer::start().await; MockResponsesConfig::new(&models.uri()) .with_root_config(&format!("log_dir = {:?}", home.path().join("log"))) @@ -252,15 +100,9 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures // This new process can recover review context only from SQLite. let mut app_server = TestAppServer::builder() .with_codex_home(home.path()) - .with_env_overrides(&[ - ("HTTPS_PROXY", Some(proxy_uri.as_str())), - ("https_proxy", Some(proxy_uri.as_str())), - ("NO_PROXY", Some("127.0.0.1,localhost")), - ("no_proxy", Some("127.0.0.1,localhost")), - ("SSL_CERT_FILE", cert_path.to_str()), - ]) .build_initialized() .await?; + let output = tempfile::tempdir()?; let pool = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?; // This old history exists only in SQLite, as if it had already left the memory ring. sqlx::query("INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id) VALUES (unixepoch(), 0, 'INFO', 'test', 'sqlite-only-history', ?)") @@ -281,7 +123,7 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures } Phase::WithoutLogs | Phase::WriteFailure => {} } - // Notifications emit an INFO log, ensuring feedback/upload has a batch to flush. + // Notifications emit an INFO log, ensuring feedback/save has a batch to flush. app_server .send_notification(ClientNotification::Initialized) .await?; @@ -299,11 +141,15 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures message: "Codex couldn't save diagnostic logs to its local database. Use /feedback with logs included before closing Codex, or run `codex doctor` for diagnostics.".to_string(), }); } + let saved = output.path().join(format!("{phase:?}.zip")); let request = app_server .send_raw_request( - "feedback/upload", + "feedback/save", Some(json!({ - "classification": "bug", "includeLogs": phase != Phase::WithoutLogs, "threadId": thread_id + "classification": "bug", + "includeLogs": phase != Phase::WithoutLogs, + "threadId": thread_id, + "savePath": saved, })), ) .await?; @@ -313,43 +159,34 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures ) .await??; let mut attachments = std::collections::BTreeMap::new(); - let mut uploaded_rollouts = HashSet::::new(); - while let Ok(envelope) = uploads_rx.try_recv() { - let mut bytes = envelope.as_slice(); - // Skip the envelope header, then decode each length-delimited item. - let header_end = bytes.iter().position(|byte| *byte == b'\n').unwrap(); - bytes = &bytes[header_end + 1..]; - while !bytes.is_empty() { - let header_end = bytes.iter().position(|byte| *byte == b'\n').unwrap(); - let header: serde_json::Value = serde_json::from_slice(&bytes[..header_end])?; - let length = header["length"].as_u64().unwrap() as usize; - bytes = &bytes[header_end + 1..]; - if header["filename"] == "rollouts.tar.gz" { - let mut archive = - tar::Archive::new(flate2::read::GzDecoder::new(&bytes[..length])); - for entry in archive.entries()? { - uploaded_rollouts.insert(serde_json::from_reader(entry?)?); - } - } else if let Some(filename) = header["filename"].as_str() { - attachments.insert( - filename.to_string(), - String::from_utf8_lossy(&bytes[..length]).into_owned(), - ); - } - bytes = &bytes[length..]; - if bytes.starts_with(b"\n") { - bytes = &bytes[1..]; - } + let mut saved_rollouts = HashSet::::new(); + let mut zip = zip::ZipArchive::new(std::fs::File::open(&saved)?)?; + for index in 0..zip.len() { + let mut entry = zip.by_index(index)?; + let Some(filename) = entry + .name()? + .strip_prefix("attachments/") + .and_then(|name| name.rsplit('/').next()) + .map(str::to_string) + else { + continue; + }; + let mut contents = Vec::new(); + entry.read_to_end(&mut contents)?; + if filename.starts_with("rollout-") { + saved_rollouts.insert(serde_json::from_slice(&contents)?); + } else { + attachments.insert(filename, String::from_utf8_lossy(&contents).into_owned()); } } if phase == Phase::WithoutLogs { - assert!(uploaded_rollouts.is_empty()); + assert!(saved_rollouts.is_empty()); assert!(!attachments.contains_key("auto-review-failures.jsonl")); assert!(!attachments.contains_key("codex-logs.log")); assert!(!attachments.contains_key("codex-logs-legacy.log")); continue; } - assert_eq!(uploaded_rollouts, HashSet::from([thread_id, attached_id])); + assert_eq!(saved_rollouts, HashSet::from([thread_id, attached_id])); assert_eq!( attachments.get("codex-logs-legacy.log"), (phase == Phase::Corrupt) @@ -393,7 +230,7 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures Ok(()) } -/// Disabling uploads still permits local ZIPs, with invalid paths and collisions leaving existing files intact. +/// Local ZIPs stay local even with feedback disabled, and invalid paths or collisions leave existing files intact. #[tokio::test] async fn feedback_save_is_local_and_never_overwrites() -> Result<()> { let proxy = TcpListener::bind("127.0.0.1:0").await?; @@ -408,17 +245,6 @@ async fn feedback_save_is_local_and_never_overwrites() -> Result<()> { ]) .build_initialized() .await?; - let request = app_server - .send_raw_request("feedback/upload", Some(json!({ "classification": "bug" }))) - .await?; - let error = app_server - .read_stream_until_error_message(RequestId::Integer(request)) - .await?; - assert_eq!( - error.error.message, - "sending feedback is disabled by configuration" - ); - let directory = tempfile::tempdir()?; let saved = directory.path().join("local.zip"); std::fs::write(&saved, b"existing export")?; diff --git a/codex-rs/app-server/tests/suite/v2/guardian_action_budget_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_action_budget_tests.rs index d9b72916..b37934ca 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_action_budget_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_action_budget_tests.rs @@ -117,15 +117,13 @@ with urllib.request.urlopen(request, timeout=30) as response: )) .join("\n"); std::fs::write(codex_home.path().join("requirements.toml"), hooks)?; - let analytics_server = responses::start_mock_server().await; - mount_analytics_capture(&analytics_server, codex_home.path()).await?; MockResponsesConfig::new(&responses_url) .with_model(MODEL) .with_provider_config("supports_websockets = false") .with_approval_policy("on-request") - .with_root_config(&format!("approvals_reviewer = \"auto_review\"\nchatgpt_base_url = \"{}\"", analytics_server.uri())) + .with_root_config("approvals_reviewer = \"auto_review\"") .with_extra_config(&format!( - "[mcp_servers.{TEST_SERVER_NAME}]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"prompt\"\n\n[analytics]\nenabled = true\n\n[features.guardianv2]\nenabled = true\nmax_action_tokens = 128\n\n[features.guardianv2.review_scope]\ncomputer_use_only = false" + "[mcp_servers.{TEST_SERVER_NAME}]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"prompt\"\n\n[features.guardianv2]\nenabled = true\nmax_action_tokens = 128\n\n[features.guardianv2.review_scope]\ncomputer_use_only = false" )) .enable_feature(Feature::GuardianApproval) .write(codex_home.path())?; @@ -140,7 +138,7 @@ with urllib.request.urlopen(request, timeout=30) as response: state.allow_guardian_review.notify_one(); let id = app_server .send_turn_start_request(TurnStartParams { - thread_id: thread.id, + thread_id: thread.id.clone(), input: vec![UserInput::Text { text: USER_CONTEXT.to_owned(), text_elements: Vec::new(), @@ -156,24 +154,7 @@ with urllib.request.urlopen(request, timeout=30) as response: wait_for_guardian_reviews(&state, 1 + index).await?; // First establish a permissive score; after overflow, establish a new one. state.allow_luna.notify_one(); - timeout(TIMEOUT, async { - loop { - let events = captured_analytics_events(&analytics_server).await; - if events - .iter() - .filter(|event| { - event["event_type"] == "codex_guardian_v2_classification" - && event["event_params"]["outcome"] == "success" - }) - .count() - > index - { - break; - } - tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await; - } - }) - .await?; + wait_for_classification_logs(&codex_home, &thread.id, index + 1).await?; gate.notify_one(); } let completed: TurnCompletedNotification = diff --git a/codex-rs/app-server/tests/suite/v2/guardian_code_mode_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_code_mode_tests.rs index 24988123..22a2749e 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_code_mode_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_code_mode_tests.rs @@ -141,18 +141,13 @@ async fn model_guardian_policy_scores_code_mode_cells( ) } }; - let analytics_server = responses::start_mock_server().await; - mount_analytics_capture(&analytics_server, codex_home.path()).await?; MockResponsesConfig::new(&responses_url) .with_model(MODEL) .with_provider_config("supports_websockets = false") .with_approval_policy("on-request") - .with_root_config(&format!( - "approvals_reviewer = \"auto_review\"\nchatgpt_base_url = \"{}\"", - analytics_server.uri(), - )) + .with_root_config("approvals_reviewer = \"auto_review\"") .with_extra_config(&format!( - "[mcp_servers.node_repl]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"auto\"\n\n[analytics]\nenabled = true{legacy_config}" + "[mcp_servers.node_repl]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"auto\"{legacy_config}" )) .enable_feature(Feature::GuardianApproval) .enable_feature(Feature::CodeModeOnly) @@ -182,7 +177,7 @@ async fn model_guardian_policy_scores_code_mode_cells( state.allow_guardian_review.notify_one(); let id = app_server .send_turn_start_request(TurnStartParams { - thread_id: thread.id, + thread_id: thread.id.clone(), input: vec![UserInput::Text { text: USER_CONTEXT.to_owned(), text_elements: Vec::new(), @@ -203,27 +198,7 @@ async fn model_guardian_policy_scores_code_mode_cells( } for completed_scores in 1..=scores_per_cell { state.allow_luna.notify_one(); - timeout(TIMEOUT, async { - loop { - let events = captured_analytics_events(&analytics_server).await; - if events - .iter() - .filter(|event| { - event["event_type"] == "codex_guardian_v2_classification" - && matches!( - event["event_params"]["outcome"].as_str(), - Some("success" | "superseded") - ) - }) - .count() - >= completed_scores - { - break; - } - tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await; - } - }) - .await?; + wait_for_classification_logs(&codex_home, &thread.id, completed_scores).await?; } continue_parent.notify_one(); let completed: TurnCompletedNotification = diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v2.rs b/codex-rs/app-server/tests/suite/v2/guardian_v2.rs index 76dee71d..421c0372 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v2.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v2.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::io::Write; use std::path::Path; use std::sync::Arc; @@ -67,9 +66,6 @@ use tokio::net::TcpListener; use tokio::sync::Notify; use tokio::time::timeout; -use super::analytics::captured_analytics_events; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; use super::mcp_tool::TEST_SERVER_NAME; use super::mcp_tool::TEST_TOOL_NAME; use super::mcp_tool::start_mcp_server; @@ -190,10 +186,6 @@ struct MockResponsesState { gate_each_guardian_review: bool, gate_second_tool_on_classification: bool, allow_second_tool: Notify, - classification_completed: Notify, - truncation_recorded: Notify, - context_metric_bounds: Mutex>>, - context_metrics_recorded: Notify, luna_score: f64, invalid_classification: bool, fail_after_classification: bool, @@ -326,6 +318,52 @@ fn sync_review_fragments(request: &Value) -> Vec<&str> { .collect() } +async fn wait_for_luna_completions(state: &MockResponsesState, expected: usize) -> Result<()> { + timeout(TIMEOUT, async { + while state.luna_completions.load(Ordering::Relaxed) < expected { + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await?; + Ok(()) +} + +/// Waits until `expected` Guardian V2 classifications of `thread_id` have finished, using the +/// result or failure line each classification writes to the local feedback logs. +async fn wait_for_classification_logs( + codex_home: &TempDir, + thread_id: &str, + expected: usize, +) -> Result<()> { + let state_db = StateRuntime::init( + load_default_config_for_test(codex_home).await.sqlite, + "mock_provider".to_owned(), + ) + .await?; + timeout(TIMEOUT, async { + loop { + let logs = String::from_utf8( + state_db + .query_feedback_logs_for_threads(&[thread_id]) + .await?, + )?; + let finished = logs + .lines() + .filter(|line| { + line.contains("Guardian V2 classification result") + || line.contains("Guardian V2 background scoring failed") + }) + .count(); + if finished >= expected { + return anyhow::Ok(()); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await??; + Ok(()) +} + async fn wait_for_luna_request(state: &MockResponsesState, index: usize) -> Result { Ok(timeout(TIMEOUT, async { loop { @@ -779,73 +817,6 @@ async fn guardian_v2_routes_scoped_tool_approvals( let responses_url = format!("http://{}", listener.local_addr()?); let router = Router::new() .route("/v1/responses", get(luna_websocket).post(parent_response)) - .route( - "/metrics", - post( - |State(state): State>, body: String| async move { - if matches!(state.transcript_content, TranscriptContent::MixedEvidence) { - let payload: Value = serde_json::from_str(&body).expect("OTLP JSON"); - for metric in payload["resourceMetrics"] - .as_array() - .into_iter() - .flatten() - .flat_map(|resource| { - resource["scopeMetrics"].as_array().into_iter().flatten() - }) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .filter(|metric| { - matches!( - metric["name"].as_str(), - Some( - "codex.guardian.context.request_tokens" - | "codex.guardian.context.section_cost" - ) - ) - }) - { - let name = metric["name"].as_str().expect("context metric name"); - for point in metric["histogram"]["dataPoints"] - .as_array() - .into_iter() - .flatten() - { - let attributes = - point["attributes"].as_array().expect("metric attributes"); - for target in ["sync", "async"] { - if attributes.iter().any(|attr| { - attr["key"] == "target" - && attr["value"]["stringValue"] == target - }) { - let mut bounds = state - .context_metric_bounds - .lock() - .expect("context metric bounds"); - bounds.insert( - (name.to_owned(), target.to_owned()), - point["explicitBounds"] - .as_array() - .and_then(|bounds| bounds.last()) - .and_then(Value::as_f64), - ); - if bounds.len() == 4 { - state.context_metrics_recorded.notify_one(); - } - } - } - } - } - } - if body.contains("\"codex.guardian_v2.classification\"") { - state.classification_completed.notify_one(); - } - if body.contains("codex.guardian_v2.classification.truncation") - && body.contains("sync_review_action") - { - state.truncation_recorded.notify_one(); - } - }, - ), - ) .with_state(Arc::clone(&responses_state)); let responses_server = tokio::spawn(async move { let _ = axum::serve(listener, router).await; @@ -853,8 +824,6 @@ async fn guardian_v2_routes_scoped_tool_approvals( let (mcp_server_url, mcp_server_handle) = start_mcp_server(sensitive_action).await?; let codex_home = TempDir::new()?; - let analytics_server = responses::start_mock_server().await; - mount_analytics_capture(&analytics_server, codex_home.path()).await?; let mixed_evidence = matches!(transcript_content, TranscriptContent::MixedEvidence); let root_skill = if matches!(lifecycle, ThreadLifecycle::RootTrustedSkill) || mixed_evidence { let path = codex_home.path().join("skills/root-trusted/SKILL.md"); @@ -930,12 +899,9 @@ async fn guardian_v2_routes_scoped_tool_approvals( .with_model(MODEL) .with_provider_config("supports_websockets = false") .with_approval_policy("on-request") - .with_root_config(&format!( - "{reviewer_config}\nchatgpt_base_url = \"{}\"", - analytics_server.uri(), - )) + .with_root_config(reviewer_config) .with_extra_config(&format!( - "[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[analytics]\nenabled = true\n\n[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{responses_url}/metrics\", protocol = \"json\" }} }}\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}" + "[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}" )) .enable_feature(Feature::GuardianApproval); if lifecycle.has_user_input() || lifecycle.has_root_user_input() { @@ -1008,10 +974,7 @@ async fn guardian_v2_routes_scoped_tool_approvals( .then(|| traces.path().to_str().expect("trace root path")); let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) - .with_env_overrides(&[ - ("OTEL_METRIC_EXPORT_INTERVAL", Some("25")), - ("CODEX_ROLLOUT_TRACE_ROOT", trace_root), - ]) + .with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", trace_root)]) .build_initialized_with_timeout(TIMEOUT) .await?; let thread = match lifecycle { @@ -1244,7 +1207,13 @@ async fn guardian_v2_routes_scoped_tool_approvals( .await??; } responses_state.allow_luna.notify_one(); - timeout(TIMEOUT, responses_state.classification_completed.notified()).await?; + if late_root_restriction { + // A superseded classification leaves no observable trace, so only wait + // until the classifier response has been served. + wait_for_luna_completions(&responses_state, /*expected*/ 1).await?; + } else { + wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 1).await?; + } if late_root_restriction { responses_state.allow_guardian_review.notify_one(); } else { @@ -1700,26 +1669,6 @@ async fn guardian_v2_routes_scoped_tool_approvals( assert!(text.contains("Planned action JSON:")); } } - if mixed_evidence { - timeout(TIMEOUT, responses_state.context_metrics_recorded.notified()) - .await - .expect("sync and async request/section metrics should all be exported"); - let bounds = responses_state - .context_metric_bounds - .lock() - .expect("context metric bounds"); - for ((metric, target), bound) in bounds.iter() { - assert_eq!( - *bound, - Some(if metric == "codex.guardian.context.request_tokens" { - 2_000_000.0 - } else { - 16_777_216.0 - }), - "{metric} ({target}) must export its context metric buckets" - ); - } - } if lifecycle.has_user_answer() { let reviews = responses_state .guardian_requests @@ -1793,7 +1742,7 @@ async fn guardian_v2_routes_scoped_tool_approvals( "mock_provider".to_owned(), ) .await?; - // Exercise the same log export used by feedback/upload, including async + // Exercise the same log export used by feedback/save, including async // classifier events that cannot rely on inheriting a thread tracing span. let logs = timeout(TIMEOUT, async { loop { @@ -1826,7 +1775,7 @@ async fn guardian_v2_routes_scoped_tool_approvals( if matches!(lifecycle, ThreadLifecycle::RequiredModelSwitch) { // Both MCP actions have low scores; the sandboxed exec must still receive full review. - timeout(TIMEOUT, responses_state.classification_completed.notified()).await?; + wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 2).await?; // Continue without new user input so authorization changes cannot invalidate the score. // Only the required-model check should prevent cached approval of the sandboxed command. let request_id = app_server @@ -2051,26 +2000,10 @@ async fn guardian_v2_routes_scoped_tool_approvals( responses_state.allow_luna.notify_one(); } - if matches!(review_outcome, ReviewOutcome::Deny) && !lifecycle.has_user_answer() { - timeout(TIMEOUT, responses_state.truncation_recorded.notified()).await?; - } - if matches!(lifecycle, ThreadLifecycle::New) && matches!(scope, GuardianToolScope::AllTools) && sensitive_action.is_none() { - if classifier_in_scope { - wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| { - event["event_type"] == "codex_guardian_v2_classification" - && event["event_params"]["item_id"] == "guardian-action-0" - }) - .await?; - } - let turn = wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["thread_id"] == reviewed_thread_id - }) - .await?; timeout(TIMEOUT, app_server.shutdown_gracefully()).await??; if matches!(review_outcome, ReviewOutcome::Deny) { // Denied calls have no backend response, but their runtime result must @@ -2135,58 +2068,6 @@ async fn guardian_v2_routes_scoped_tool_approvals( None ), ); - let events = captured_analytics_events(&analytics_server).await; - let turn = &turn["event_params"]; - assert_eq!(turn["guardian_v2_enabled"], classifier_in_scope); - let classification = events.iter().find(|event| { - event["event_type"] == "codex_guardian_v2_classification" - && event["event_params"]["item_id"] == "guardian-action-0" - }); - assert_eq!(classification.is_some(), classifier_in_scope); - if let Some(event) = classification { - assert_eq!( - json!([ - event["event_params"]["outcome"], - event["event_params"]["risk_level"] - ]), - match risk { - GuardianRisk::Low | GuardianRisk::LowWithStreamFailure => - json!(["success", "low"]), - GuardianRisk::Threshold | GuardianRisk::High => json!(["success", "high"]), - GuardianRisk::InvalidResponse => json!(["failure", null]), - } - ); - } - let approvals = events - .iter() - .filter(|event| event["event_type"] == "codex_guardian_v2_fast_decision") - .collect::>(); - assert_eq!( - approvals.len(), - usize::from(classifier_in_scope && matches!(risk, GuardianRisk::Low)) - ); - for event in classification.into_iter().chain(approvals) { - let params = &event["event_params"]; - for key in [ - "session_id", - "thread_id", - "turn_id", - "model", - "app_server_client", - "runtime", - "thread_source", - "subagent_source", - "parent_thread_id", - ] { - assert_eq!(params[key], turn[key], "{key}"); - } - if event["event_type"] == "codex_guardian_v2_fast_decision" { - assert_eq!( - json!([params["item_id"], params["decision"]]), - json!(["guardian-action-1", "approved"]) - ); - } - } } mcp_server_handle.abort(); diff --git a/codex-rs/app-server/tests/suite/v2/history_notes_extension.rs b/codex-rs/app-server/tests/suite/v2/history_notes_extension.rs index bc12a8b8..adea19a6 100644 --- a/codex-rs/app-server/tests/suite/v2/history_notes_extension.rs +++ b/codex-rs/app-server/tests/suite/v2/history_notes_extension.rs @@ -3,6 +3,7 @@ use std::time::Duration; use anyhow::Result; use app_test_support::MockResponsesConfig; use app_test_support::TestAppServer; +use app_test_support::mount_chatgpt_account; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::UserInput; @@ -21,11 +22,6 @@ use wiremock::matchers::body_partial_json; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; - -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(30); - const THREAD_HINT: &str = "Recent notes (up to 5, most-recent first):\n- /root/notes/latest.md (2 lines, 14 UTF-8 bytes)"; const BRIDGE_HINT: &str = "unstructured notes/thread_hint fixture result"; @@ -138,7 +134,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints( server.uri(), )) .write(codex_home.path())?; - mount_analytics_capture(&backend, codex_home.path()).await?; + mount_chatgpt_account(&backend, codex_home.path()).await?; let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -231,27 +227,11 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints( && item["name"] == "thread_hint" })); - if use_history_notes_extension { - let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_thread_hint_status" - && event["event_params"]["thread_id"] == thread.id - }) - .await?; - assert_eq!( - event["event_params"]["status"], - if hint_status == 200 { - "succeeded" - } else { - "failed" - }, - ); - } - Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result<()> { +async fn history_notes_and_async_message_control_tools_execute() -> Result<()> { let encrypted_query = format!("enc_query_{}", "x".repeat(1_001)); let calls = [ ("history", "list_windows", json!({})), @@ -364,7 +344,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result "[features.token_budget]\nenabled = true\nuse_history_notes_extension = true", ) .write(codex_home.path())?; - mount_analytics_capture(&backend, codex_home.path()).await?; + mount_chatgpt_account(&backend, codex_home.path()).await?; let mut app_server = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -376,7 +356,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result .start_thread(ThreadStartParams::default()) .await? .thread; - let completed = app_server + app_server .start_turn_and_wait_for_completion(TurnStartParams { thread_id: thread.id.clone(), input: vec![UserInput::Text { @@ -400,45 +380,6 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result assert_eq!(tool["parameters"]["properties"][field]["encrypted"], true); } - for (index, (namespace, tool, _)) in calls.iter().enumerate() { - let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_control_tool_call_event" - && event["event_params"]["item_id"] == format!("call-{index}") - }) - .await?; - let params = &event["event_params"]; - assert_eq!( - json!({ - "tool": params["tool_name"], - "thread": params["thread_id"], - "turn": params["turn_id"], - "status": params["terminal_status"], - "origin": params["originating_response_id"], - "duration": params["execution_duration_ms"].is_u64(), - }), - json!({ - "tool": if *namespace == "functions" { tool.to_string() } else { format!("{namespace}.{tool}") }, - "thread": thread.id, - "turn": completed.turn.id, - "status": if index < 10 { "completed" } else { "failed" }, - "origin": format!("resp-{index}"), - "duration": true, - }) - ); - assert!(!event.to_string().contains("PRIVATE_")); - } - let turn_event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == completed.turn.id - }) - .await?; - assert_eq!( - json!({ - "total": turn_event["event_params"]["total_tool_call_count"], - "dynamic": turn_event["event_params"]["dynamic_tool_call_count"], - }), - json!({"total": calls.len(), "dynamic": 0}) - ); assert_eq!( response_mock.requests()[10].function_call_output_text("call-9"), Some(r#"{"accepted":true}"#.to_string()) diff --git a/codex-rs/app-server/tests/suite/v2/imagegen_extension.rs b/codex-rs/app-server/tests/suite/v2/imagegen_extension.rs index ad0880b5..fce26622 100644 --- a/codex-rs/app-server/tests/suite/v2/imagegen_extension.rs +++ b/codex-rs/app-server/tests/suite/v2/imagegen_extension.rs @@ -6,6 +6,7 @@ use anyhow::Result; use app_test_support::ChatGptAuthFixture; use app_test_support::MockResponsesConfig; use app_test_support::TestAppServer; +use app_test_support::mount_chatgpt_account; use app_test_support::write_chatgpt_auth; use base64::Engine; use codex_app_server_protocol::GeneratedImageRef; @@ -43,9 +44,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_analytics_event; - const RESULT: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; // Two one-pixel frames, red then blue, with a 200 ms frame duration. const ANIMATED_RESULT: &str = "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQAFAAAACwAAAAAAQABAAAIBAABBAQAIfkEARQAAQAsAAAAAAEAAQCBAAD/AAAAAAAAAAAACAQAAQQEADs="; @@ -132,7 +130,7 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model( let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri(), ImagegenTestMode::Direct)?; - mount_analytics_capture(&server, codex_home.path()).await?; + mount_chatgpt_account(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -286,21 +284,6 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model( "standalone image generation should not emit the legacy developer-message hint" ); - let event = wait_for_analytics_event( - &server, - DEFAULT_READ_TIMEOUT, - "codex_image_generation_event", - ) - .await?; - assert_eq!( - event["event_params"]["imagegen_request_id"], - json!("req-imagegen-123") - ); - assert_eq!( - event["event_params"]["generation_id"], - json!("gen-image-123") - ); - Ok(()) } @@ -708,17 +691,6 @@ async fn standalone_image_generation_failure_emits_terminal_item( ) ); - let event = wait_for_analytics_event( - &server, - DEFAULT_READ_TIMEOUT, - "codex_image_generation_event", - ) - .await?; - assert_eq!( - event["event_params"]["imagegen_request_id"], - json!("req-imagegen-failed-123") - ); - Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index 6d76cb3d..f13418c0 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -5,13 +5,10 @@ mod account_system_proxy; mod account_gcp; mod account_thread_usage; mod agent_message_board; -mod analytics; mod application_network; #[path = "attached_thread_tests.rs"] mod attached_thread; mod attestation; -#[path = "auth_storage_originator_tests.rs"] -mod auth_storage_originator; mod auto_env; #[path = "bedrock_gov_cloud_tests.rs"] mod bedrock_gov_cloud; @@ -45,8 +42,6 @@ mod connection_handling_websocket; mod connection_handling_websocket_compression; #[cfg(unix)] mod connection_handling_websocket_unix; -#[path = "critical_path_analytics_tests.rs"] -mod critical_path_analytics; #[cfg(unix)] mod curated_mcp_sync; mod current_time; @@ -106,7 +101,6 @@ mod model_provider_config_tests; mod model_provider_enforcement; mod model_provider_list_tests; mod multi_agent_v2_developer_instructions; -mod otel; mod output_schema; mod permission_profile_list; mod plan_item; @@ -169,7 +163,6 @@ mod thread_timeline; mod thread_unarchive; mod thread_unload; mod thread_unsubscribe; -mod turn_cost_otel; mod turn_interrupt; mod turn_settings_update; mod turn_start; diff --git a/codex-rs/app-server/tests/suite/v2/otel.rs b/codex-rs/app-server/tests/suite/v2/otel.rs deleted file mode 100644 index 302e749d..00000000 --- a/codex-rs/app-server/tests/suite/v2/otel.rs +++ /dev/null @@ -1,363 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::encode_id_token; -use app_test_support::write_chatgpt_auth; -use app_test_support::write_models_cache; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_config::types::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use std::path::Path; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; - -const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30); -const INITIAL_ACCOUNT_ID: &str = "123e4567-e89b-42d3-a456-426614174000"; -const NEXT_ACCOUNT_ID: &str = "123e4567-e89b-42d3-a456-426614174001"; -const INITIAL_EMAIL: &str = "initial-workspace@example.com"; -const NEXT_EMAIL: &str = "next-account@example.com"; -const PARENT_TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736"; -const PARENT_TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; - -enum TraceExporterSetting { - Disabled, - Collector, -} - -#[tokio::test] -async fn account_switch_reloads_telemetry_collectors_and_preserves_trace_context() -> Result<()> { - let collector = MockServer::start().await; - Mock::given(method("POST")) - .respond_with(ResponseTemplate::new(200)) - .mount(&collector) - .await; - - let codex_home = TempDir::new()?; - let initial_endpoint = format!("{}/initial", collector.uri()); - write_otel_config( - codex_home.path(), - &initial_endpoint, - TraceExporterSetting::Collector, - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("initial-access-token") - .account_id(INITIAL_ACCOUNT_ID) - .chatgpt_account_id(INITIAL_ACCOUNT_ID) - .chatgpt_user_id("initial-user") - .plan_type("pro") - .email(INITIAL_EMAIL), - AuthCredentialsStoreMode::File, - )?; - write_models_cache(codex_home.path()).await?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("TRACEPARENT", Some(PARENT_TRACEPARENT))]) - .with_json_logging("codex_app_server::otel_reloader=info") - .build_initialized_with_timeout(TEST_TIMEOUT) - .await?; - app_server - .start_thread(ThreadStartParams::default()) - .await?; - - let contains = |requests: &[wiremock::Request], path: &str, value: &str| { - requests.iter().any(|request| { - request.url.path() == path && String::from_utf8_lossy(&request.body).contains(value) - }) - }; - timeout(TEST_TIMEOUT, async { - let mut poll = tokio::time::interval(Duration::from_millis(/*millis*/ 25)); - loop { - poll.tick().await; - let requests = collector.received_requests().await.unwrap_or_default(); - if contains(&requests, "/initial/logs", INITIAL_EMAIL) - && contains(&requests, "/initial/traces", PARENT_TRACE_ID) - { - break; - } - } - }) - .await - .context("initial account telemetry must be exported before its permission is revoked")?; - - let next_endpoint = format!("{}/next", collector.uri()); - write_otel_config( - codex_home.path(), - &next_endpoint, - TraceExporterSetting::Collector, - )?; - let access_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .email(NEXT_EMAIL) - .plan_type("pro") - .chatgpt_account_id(NEXT_ACCOUNT_ID) - .chatgpt_user_id("next-user"), - )?; - let request_id = app_server - .send_chatgpt_auth_tokens_login_request( - access_token, - NEXT_ACCOUNT_ID.to_string(), - Some("pro".to_string()), - ) - .await?; - let response: LoginAccountResponse = - timeout(TEST_TIMEOUT, app_server.read_response(request_id)).await??; - assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); - timeout( - TEST_TIMEOUT, - app_server.wait_for_json_log_event( - "codex.app_server.otel_reloaded", - Duration::from_secs(/*secs*/ 10), - ), - ) - .await??; - timeout(TEST_TIMEOUT, async { - let mut poll = tokio::time::interval(Duration::from_secs(/*secs*/ 1)); - loop { - poll.tick().await; - app_server - .start_thread(ThreadStartParams::default()) - .await?; - let requests = collector.received_requests().await.unwrap_or_default(); - if contains(&requests, "/next/logs", NEXT_EMAIL) { - break Ok::<(), anyhow::Error>(()); - } - } - }) - .await - .context("new account telemetry must reach the replacement collector")??; - - let status = timeout(TEST_TIMEOUT, app_server.shutdown_gracefully()).await??; - assert!(status.success(), "app-server did not shut down cleanly"); - - let requests = collector - .received_requests() - .await - .context("collector did not record requests")?; - for request in requests - .iter() - .filter(|request| request.url.path().ends_with("/logs")) - { - assert_eq!( - request - .headers - .get("x-collector-key") - .and_then(|value| value.to_str().ok()), - Some("test-collector-key") - ); - } - let exported = |path: &str| { - requests - .iter() - .filter(|request| request.url.path() == path) - .map(|request| String::from_utf8_lossy(&request.body).into_owned()) - .collect::>() - .join("\n") - }; - let initial_logs = exported("/initial/logs"); - let initial_traces = exported("/initial/traces"); - let next_logs = exported("/next/logs"); - let next_traces = exported("/next/traces"); - let next_metrics = exported("/next/metrics"); - - assert!( - initial_logs.contains(INITIAL_EMAIL), - "the initial account's logs were not exported: {initial_logs}" - ); - assert!( - initial_traces.contains(PARENT_TRACE_ID), - "the initial account's trace context was not propagated: {initial_traces}" - ); - assert!( - next_logs.contains(NEXT_EMAIL), - "the next account's logs did not reach its collector: {next_logs}" - ); - assert!( - next_traces.contains(PARENT_TRACE_ID), - "the next account's trace context was not propagated: {next_traces}" - ); - assert!( - next_metrics.contains("codex.thread.started"), - "the next account's metrics did not reach its collector: {next_metrics}" - ); - assert!( - next_metrics.contains("is_worktree"), - "the thread-start worktree tag did not reach its collector: {next_metrics}" - ); - - Ok(()) -} - -#[tokio::test] -async fn account_switch_enables_trace_exporter_after_startup_without_tracing() -> Result<()> { - let collector = MockServer::start().await; - Mock::given(method("POST")) - .respond_with(ResponseTemplate::new(200)) - .mount(&collector) - .await; - - let codex_home = TempDir::new()?; - let initial_endpoint = format!("{}/initial", collector.uri()); - write_otel_config( - codex_home.path(), - &initial_endpoint, - TraceExporterSetting::Disabled, - )?; - write_trace_requirements( - codex_home.path(), - &initial_endpoint, - TraceExporterSetting::Disabled, - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("initial-access-token") - .account_id(INITIAL_ACCOUNT_ID) - .chatgpt_account_id(INITIAL_ACCOUNT_ID) - .chatgpt_user_id("initial-user") - .plan_type("pro") - .email(INITIAL_EMAIL), - AuthCredentialsStoreMode::File, - )?; - write_models_cache(codex_home.path()).await?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("TRACEPARENT", Some(PARENT_TRACEPARENT))]) - .with_json_logging("codex_app_server::otel_reloader=info") - .build_initialized_with_timeout(TEST_TIMEOUT) - .await?; - app_server - .start_thread(ThreadStartParams::default()) - .await?; - - let next_endpoint = format!("{}/next", collector.uri()); - write_trace_requirements( - codex_home.path(), - &next_endpoint, - TraceExporterSetting::Collector, - )?; - let access_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .email(NEXT_EMAIL) - .plan_type("pro") - .chatgpt_account_id(NEXT_ACCOUNT_ID) - .chatgpt_user_id("next-user"), - )?; - let request_id = app_server - .send_chatgpt_auth_tokens_login_request( - access_token, - NEXT_ACCOUNT_ID.to_string(), - Some("pro".to_string()), - ) - .await?; - let response: LoginAccountResponse = - timeout(TEST_TIMEOUT, app_server.read_response(request_id)).await??; - assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); - timeout( - TEST_TIMEOUT, - app_server.wait_for_json_log_event( - "codex.app_server.otel_reloaded", - Duration::from_secs(/*secs*/ 10), - ), - ) - .await??; - app_server - .start_thread(ThreadStartParams::default()) - .await?; - - let status = timeout(TEST_TIMEOUT, app_server.shutdown_gracefully()).await??; - assert!(status.success(), "app-server did not shut down cleanly"); - - let requests = collector - .received_requests() - .await - .context("collector did not record requests")?; - let exported = |path: &str| { - requests - .iter() - .filter(|request| request.url.path() == path) - .map(|request| String::from_utf8_lossy(&request.body).into_owned()) - .collect::>() - .join("\n") - }; - let initial_traces = exported("/initial/traces"); - let next_traces = exported("/next/traces"); - - assert!( - initial_traces.is_empty(), - "traces were exported before tracing was configured: {initial_traces}" - ); - assert!( - next_traces.contains(PARENT_TRACE_ID), - "the requirements-managed trace exporter did not start after account switch: {next_traces}" - ); - - Ok(()) -} - -fn write_otel_config( - codex_home: &Path, - collector_endpoint: &str, - trace_exporter_setting: TraceExporterSetting, -) -> Result<()> { - let trace_exporter = match trace_exporter_setting { - TraceExporterSetting::Disabled => String::new(), - TraceExporterSetting::Collector => format!( - r#"trace_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/traces", protocol = "json" }} }}"# - ), - }; - std::fs::write( - codex_home.join("config.toml"), - format!( - r#"model = "mock-model" -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider" -base_url = "http://127.0.0.1:1/v1" -wire_api = "responses" - -[analytics] -enabled = false - -[otel] -environment = "test" -exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/logs", protocol = "json", headers = {{ x-collector-key = "test-collector-key" }} }} }} -{trace_exporter} -metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/metrics", protocol = "json" }} }} -"# - ), - )?; - Ok(()) -} - -fn write_trace_requirements( - codex_home: &Path, - collector_endpoint: &str, - trace_exporter_setting: TraceExporterSetting, -) -> Result<()> { - let trace_exporter = match trace_exporter_setting { - TraceExporterSetting::Disabled => "trace_exporter = \"none\"".to_string(), - TraceExporterSetting::Collector => format!( - r#"trace_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/traces", protocol = "json" }} }}"# - ), - }; - std::fs::write( - codex_home.join("requirements.toml"), - format!( - r#"[otel] -{trace_exporter} -"# - ), - )?; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/plugin_install.rs b/codex-rs/app-server/tests/suite/v2/plugin_install.rs index 19a4327b..482b119f 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_install.rs @@ -9,9 +9,7 @@ use std::time::Duration; use anyhow::Result; use anyhow::bail; use app_test_support::ChatGptAuthFixture; -use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::TestAppServer; -use app_test_support::start_analytics_events_server; use app_test_support::write_chatgpt_auth; use axum::Json; use axum::Router; @@ -565,12 +563,11 @@ async fn plugin_install_rejects_invalid_remote_plugin_name() -> Result<()> { } #[tokio::test] -async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Result<()> { +async fn plugin_install_reports_remote_detail_fetch_failure() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; configure_remote_plugin_test(codex_home.path(), &server)?; mount_empty_remote_installed_plugins(&server).await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -587,27 +584,11 @@ async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Res assert_eq!(err.error.code, -32600); assert!(err.error.message.contains("failed with status 404")); - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], json!(null)); - assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID); - assert_eq!(event_params["plugin_name"], json!(null)); - assert_eq!(event_params["marketplace_name"], json!(null)); - assert_eq!(event_params["source"], "manual"); - assert_eq!( - event_params["error_type"], - "remote_catalog_unexpected_status" - ); - assert_eq!(event_params["sub_error_type"], "http_404"); Ok(()) } #[tokio::test] -async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() -> Result<()> { +async fn plugin_install_reports_rate_limited_remote_install() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; let bundle_url = mount_remote_plugin_bundle( @@ -628,7 +609,6 @@ async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() - .respond_with(ResponseTemplate::new(/*status_code*/ 429).set_body_string("rate limited")) .mount(&server) .await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -659,21 +639,6 @@ async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() - /*expected_count*/ 1, ) .await?; - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote"); - assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID); - assert_eq!(event_params["marketplace_name"], "openai-curated-remote"); - assert_eq!(event_params["source"], "manual"); - assert_eq!( - event_params["error_type"], - "remote_catalog_unexpected_status" - ); - assert_eq!(event_params["sub_error_type"], "http_429"); Ok(()) } @@ -697,7 +662,6 @@ async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download( ) .await; mount_empty_remote_installed_plugins(&server).await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -734,16 +698,6 @@ async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download( .join("plugins/cache/openai-curated-remote/linear") .exists() ); - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote"); - assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID); - assert_eq!(event_params["error_type"], "remote_plugin_not_available"); - assert_eq!(event_params["sub_error_type"], "disabled_by_admin"); Ok(()) } @@ -760,7 +714,6 @@ async fn plugin_install_rejects_remote_plugin_not_available() -> Result<()> { ) .await; mount_empty_remote_installed_plugins(&server).await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -783,19 +736,6 @@ async fn plugin_install_rejects_remote_plugin_not_available() -> Result<()> { /*expected_count*/ 0, ) .await?; - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote"); - assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID); - assert_eq!(event_params["error_type"], "remote_plugin_not_available"); - assert_eq!( - event_params["sub_error_type"], - "install_policy_not_available" - ); Ok(()) } @@ -831,18 +771,8 @@ async fn plugin_install_returns_invalid_request_for_missing_marketplace_file() - } #[tokio::test] -async fn plugin_install_tracks_analytics_when_marketplace_file_cannot_be_read() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; +async fn plugin_install_reports_unreadable_marketplace_file() -> Result<()> { let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; let marketplace_path = codex_home.path().join("marketplace-dir"); std::fs::create_dir_all(&marketplace_path)?; @@ -872,20 +802,6 @@ async fn plugin_install_tracks_analytics_when_marketplace_file_cannot_be_read() .contains("failed to read marketplace file") ); - let payload = - wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], json!(null)); - assert_eq!(event_params["remote_plugin_id"], json!(null)); - assert_eq!(event_params["error_type"], "marketplace_io"); - assert_eq!( - event_params["sub_error_type"], - "failed_to_read_marketplace_file" - ); Ok(()) } @@ -984,85 +900,8 @@ async fn plugin_install_returns_invalid_request_for_disallowed_product_plugin() } #[tokio::test] -async fn plugin_install_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; +async fn plugin_install_rejects_missing_local_plugin_source() -> Result<()> { let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - /*install_policy*/ None, - /*auth_policy*/ None, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &[])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - install_attempt_id: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - let response: PluginInstallResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(response.apps_needing_auth, Vec::::new()); - - let payload = - wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_installed").await?; - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "sample-plugin@debug", - "remote_plugin_id": null, - "plugin_name": "sample-plugin", - "marketplace_name": "debug", - "has_skills": false, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_failure_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; - let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; let repo_root = TempDir::new()?; write_plugin_marketplace( @@ -1096,28 +935,11 @@ async fn plugin_install_failure_tracks_analytics_event() -> Result<()> { .await??; assert_eq!(err.error.code, -32600); - let payload = - wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], "sample-plugin@debug"); - assert_eq!(event_params["remote_plugin_id"], json!(null)); - assert_eq!(event_params["plugin_name"], "sample-plugin"); - assert_eq!(event_params["marketplace_name"], "debug"); - assert_eq!(event_params["has_skills"], json!(null)); - assert_eq!(event_params["mcp_server_count"], json!(null)); - assert_eq!(event_params["connector_ids"], json!(null)); - assert_eq!(event_params["product_client_id"], DEFAULT_CLIENT_NAME); - assert_eq!(event_params["source"], "manual"); - assert_eq!(event_params["error_type"], "store_invalid"); Ok(()) } #[tokio::test] -async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> { +async fn plugin_install_forwards_install_attempt_id_to_remote_install() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; let bundle_url = mount_remote_plugin_bundle( @@ -1130,7 +952,6 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> { mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await; mount_empty_remote_installed_plugins(&server).await; mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -1154,25 +975,6 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> { json!({"install_attempt_id": INSTALL_ATTEMPT_ID}) ); - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_installed").await?; - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "linear@openai-curated-remote", - "remote_plugin_id": REMOTE_PLUGIN_ID, - "plugin_name": "linear", - "marketplace_name": "openai-curated-remote", - "has_skills": true, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); Ok(()) } @@ -1188,7 +990,6 @@ async fn plugin_install_preserves_status_when_remote_bundle_error_body_is_too_la mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await; mount_empty_remote_installed_plugins(&server).await; mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await; - mount_backend_analytics_events(&server).await; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -1234,18 +1035,6 @@ async fn plugin_install_preserves_status_when_remote_bundle_error_body_is_too_la /*expected_count*/ 0, ) .await?; - let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?; - let event_params = &payload["events"][0]["event_params"]; - assert_eq!( - payload["events"][0]["event_type"], - "codex_plugin_install_failed" - ); - assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote"); - assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID); - assert_eq!(event_params["marketplace_name"], "openai-curated-remote"); - assert_eq!(event_params["source"], "manual"); - assert_eq!(event_params["error_type"], "remote_bundle_download_status"); - assert_eq!(event_params["sub_error_type"], "http_5xx"); assert!( !codex_home .path() @@ -2861,84 +2650,6 @@ connectors = true ) } -fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!("chatgpt_base_url = \"{base_url}\"\n"), - ) -} - -async fn mount_backend_analytics_events(server: &MockServer) { - Mock::given(method("POST")) - .and(path("/backend-api/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#)) - .mount(server) - .await; -} - -async fn wait_for_plugin_analytics_payload( - server: &MockServer, - event_type: &str, -) -> Result { - timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - for request in requests.iter().filter(|request| { - request.method == "POST" - && request - .url - .path() - .ends_with("/codex/analytics-events/events") - }) { - let mut payload: serde_json::Value = serde_json::from_slice(&request.body) - .map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?; - let events = payload["events"] - .as_array_mut() - .ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?; - events.retain(|event| event["event_type"] == event_type); - if !events.is_empty() { - return Ok(payload); - } - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await? -} - -#[tokio::test] -async fn plugin_analytics_wait_ignores_unrelated_requests_and_batched_events() -> Result<()> { - let server = MockServer::start().await; - mount_backend_analytics_events(&server).await; - let client = HttpClientBuilder::new().build_direct()?; - let expected = json!({ - "event_type": "codex_plugin_install_failed", - "event_params": {"plugin_id": "sample-plugin@debug"} - }); - for events in [ - json!([{"event_type": "codex_turn_event"}]), - json!([{"event_type": "codex_thread_initialized"}, expected.clone()]), - ] { - client - .post(format!( - "{}/backend-api/codex/analytics-events/events", - server.uri() - )) - .json(&json!({"events": events})) - .send() - .await? - .error_for_status()?; - } - assert_eq!( - wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?, - json!({"events": [expected]}) - ); - Ok(()) -} - async fn oauth_discovery_request_count(server: &MockServer) -> usize { server .received_requests() diff --git a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs index 1e0d5d83..2041b31d 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs @@ -3,16 +3,13 @@ use std::time::Duration; use anyhow::Result; use anyhow::bail; use app_test_support::ChatGptAuthFixture; -use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::TestAppServer; -use app_test_support::start_analytics_events_server; use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::PluginUninstallParams; use codex_app_server_protocol::PluginUninstallResponse; use codex_app_server_protocol::RequestId; use codex_config::types::AuthCredentialsStoreMode; use pretty_assertions::assert_eq; -use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; use wiremock::Mock; @@ -63,72 +60,6 @@ enabled = true Ok(()) } -#[tokio::test] -async fn plugin_uninstall_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; - let codex_home = TempDir::new()?; - write_installed_plugin(&codex_home, "debug", "sample-plugin")?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "chatgpt_base_url = \"{}\"\n\n[features]\nplugins = true\n\n[plugins.\"sample-plugin@debug\"]\nenabled = true\n", - analytics_server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let response = uninstall_plugin(&mut mcp, "sample-plugin@debug").await?; - assert_eq!(response, PluginUninstallResponse {}); - - let payload = timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = analytics_server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - if let Some(request) = requests.iter().find(|request| { - request.method == "POST" && request.url.path() == "/codex/analytics-events/events" - }) { - break request.body.clone(); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - let payload: serde_json::Value = serde_json::from_slice(&payload).expect("analytics payload"); - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_uninstalled", - "event_params": { - "plugin_id": "sample-plugin@debug", - "remote_plugin_id": null, - "plugin_name": "sample-plugin", - "marketplace_name": "debug", - "has_skills": false, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); - Ok(()) -} - #[tokio::test] async fn plugin_uninstall_rejects_remote_plugin_when_plugins_are_disabled() -> Result<()> { let codex_home = TempDir::new()?; @@ -195,11 +126,6 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl ) .mount(&server) .await; - Mock::given(method("POST")) - .and(path("/backend-api/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#)) - .mount(&server) - .await; let remote_plugin_cache_root = codex_home .path() @@ -225,7 +151,7 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl .await?; // Simulate a background remote-cache refresh removing the local bundle - // before the uninstall request captures its telemetry metadata. + // before the uninstall request runs. std::fs::remove_dir_all(remote_plugin_cache_root.join("1.0.0"))?; let response = uninstall_plugin(&mut mcp, REMOTE_PLUGIN_ID).await?; @@ -240,25 +166,6 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl .await?; assert!(!remote_plugin_cache_root.exists()); assert!(!legacy_remote_plugin_cache_root.exists()); - let payload = wait_for_plugin_analytics_payload(&server).await?; - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_uninstalled", - "event_params": { - "plugin_id": "linear@openai-curated-remote", - "remote_plugin_id": REMOTE_PLUGIN_ID, - "plugin_name": "linear", - "marketplace_name": "openai-curated-remote", - "has_skills": true, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); Ok(()) } @@ -663,29 +570,6 @@ async fn mount_remote_plugin_detail_with_name( .await; } -async fn wait_for_plugin_analytics_payload(server: &MockServer) -> Result { - timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - if let Some(request) = requests.iter().find(|request| { - request.method == "POST" - && request - .url - .path() - .ends_with("/codex/analytics-events/events") - }) { - return serde_json::from_slice(&request.body) - .map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}")); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await? -} - async fn wait_for_remote_plugin_request_count( server: &MockServer, method_name: &str, diff --git a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs index 90b318f0..75294bce 100644 --- a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs +++ b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs @@ -6,6 +6,7 @@ use anyhow::Result; use app_test_support::ChatGptAuthFixture; use app_test_support::TestAppServer; use app_test_support::create_final_assistant_message_sse_response; +use app_test_support::mount_chatgpt_account; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; @@ -38,9 +39,6 @@ use tokio::process::Child; use tokio::process::Command; use tokio::time::timeout; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; - const READ_TIMEOUT: Duration = Duration::from_secs(20); const EXECUTOR_ID: &str = "executor-1"; const EXECUTOR_ENV_NAME: &str = "MCP_EXECUTOR_MARKER"; @@ -78,7 +76,7 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions( let explicitly_mentioned = !matches!(mention, PluginMention::Unmentioned); let responses_server = responses::start_mock_server().await; let fixture = selected_capability_fixture(&responses_server.uri(), &responses_server.uri())?; - mount_analytics_capture(&responses_server, fixture.codex_home.path()).await?; + mount_chatgpt_account(&responses_server, fixture.codex_home.path()).await?; let config_path = fixture.codex_home.path().join("config.toml"); let config = std::fs::read_to_string(&config_path)?.replace( "executor_capability_discovery = true", @@ -146,7 +144,7 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions( app_server.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; - let TurnStartResponse { turn } = to_response(response)?; + let _: TurnStartResponse = to_response(response)?; wait_for_pid_file(&fixture.pid_file).await?; if explicitly_mentioned { // An explicit mention must outwait the optional one-second grace. @@ -173,17 +171,6 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions( explicitly_mentioned, ); - let event = wait_for_matching_analytics_event(&responses_server, READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["thread_id"] == thread_id - && event["event_params"]["turn_id"] == turn.id - }) - .await?; - assert_eq!( - event["event_params"]["active_plugin_ids_at_turn_start"], - json!([PLUGIN_ID]) - ); - exec_server.kill().await?; Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/sleep.rs b/codex-rs/app-server/tests/suite/v2/sleep.rs index b515dbce..958e1d4a 100644 --- a/codex-rs/app-server/tests/suite/v2/sleep.rs +++ b/codex-rs/app-server/tests/suite/v2/sleep.rs @@ -18,151 +18,17 @@ use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; use core_test_support::responses; use pretty_assertions::assert_eq; -use serde_json::json; use std::time::Duration; use tempfile::TempDir; use test_case::test_case; use tokio::time::timeout; -use super::analytics::captured_analytics_events; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; - #[cfg(windows)] const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(25); #[cfg(not(windows))] const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); const CURRENT_TIME_AT: i64 = 1_781_717_655; -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn clock_tools_emit_control_tool_analytics() -> Result<()> { - let calls = [ - ("curr_time", json!({}), "completed"), - ("sleep", json!({"duration_ms": 1}), "completed"), - ( - "sleep", - json!({"duration_ms": "PRIVATE_INVALID_DURATION"}), - "failed", - ), - ("sleep", json!({"duration_ms": 43_200_000}), "interrupted"), - ]; - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - calls - .iter() - .enumerate() - .map(|(index, (tool, arguments, _))| { - let response_id = format!("resp-{index}"); - responses::sse(vec![ - responses::ev_response_created(&response_id), - responses::ev_function_call_with_namespace( - &format!("call-{index}"), - "clock", - tool, - &arguments.to_string(), - ), - responses::ev_completed(&response_id), - ]) - }) - .collect(), - ) - .await; - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) - .with_provider_config("supports_websockets = false") - .with_extra_config("[features.current_time_reminder]\nenabled = true\nsleep_tool = true") - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .without_managed_config() - .build_initialized() - .await?; - let thread = app_server - .start_thread(ThreadStartParams::default()) - .await? - .thread; - let TurnStartResponse { turn } = app_server - .request(|request_id| ClientRequest::TurnStart { - request_id, - params: TurnStartParams { - thread_id: thread.id.clone(), - input: vec![V2UserInput::Text { - text: "Exercise clock tools".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }, - }) - .await?; - wait_for_sleep_started(&mut app_server, "call-3").await?; - app_server - .interrupt_turn_and_wait_for_aborted( - thread.id.clone(), - turn.id.clone(), - DEFAULT_READ_TIMEOUT, - ) - .await?; - let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" && event["event_params"]["turn_id"] == turn.id - }) - .await?; - timeout(DEFAULT_READ_TIMEOUT, app_server.shutdown_gracefully()).await??; - - let events = captured_analytics_events(&server).await; - let mut control_events = events - .iter() - .filter(|event| event["event_type"] == "codex_control_tool_call_event") - .collect::>(); - control_events.sort_by_key(|event| event["event_params"]["item_id"].as_str()); - assert_eq!( - control_events - .iter() - .map(|event| { - let params = &event["event_params"]; - json!({ - "tool": params["tool_name"], - "call": params["item_id"], - "thread": params["thread_id"], - "turn": params["turn_id"], - "status": params["terminal_status"], - "origin": params["originating_response_id"], - "duration": params["execution_duration_ms"].is_u64(), - }) - }) - .collect::>(), - calls - .iter() - .enumerate() - .map(|(index, (tool, _, status))| json!({ - "tool": format!("clock.{tool}"), - "call": format!("call-{index}"), - "thread": thread.id, - "turn": turn.id, - "status": status, - "origin": format!("resp-{index}"), - "duration": true, - })) - .collect::>() - ); - let control_json = serde_json::to_string(&control_events)?; - for private_content in ["PRIVATE_INVALID_DURATION", "It is ", "Sleep completed."] { - assert!(!control_json.contains(private_content)); - } - assert_eq!( - json!({ - "total": turn_event["event_params"]["total_tool_call_count"], - "dynamic": turn_event["event_params"]["dynamic_tool_call_count"], - }), - json!({"total": calls.len(), "dynamic": 0}) - ); - assert_eq!(response_mock.requests().len(), calls.len()); - Ok(()) -} - #[test_case(0; "initial read fails")] #[test_case(1; "polling read fails")] #[test_case(3; "successful reads")] diff --git a/codex-rs/app-server/tests/suite/v2/thread_archive.rs b/codex-rs/app-server/tests/suite/v2/thread_archive.rs index d4002041..dcbb3ae7 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_archive.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_archive.rs @@ -39,15 +39,11 @@ use codex_state::StateRuntime; use codex_utils_absolute_path::test_support::PathExt; use core_test_support::responses; use pretty_assertions::assert_eq; -use serde_json::Value; use serde_json::json; use std::path::Path; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_matching_analytics_event; - const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); fn body_contains(request: &wiremock::Request, text: &str) -> bool { @@ -287,7 +283,6 @@ async fn thread_archive_without_turns(history_mode: ThreadHistoryMode) -> Result MockResponsesConfig::new(&server.uri()) .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -355,40 +350,6 @@ async fn thread_archive_without_turns(history_mode: ThreadHistoryMode) -> Result assert_eq!(archived.turns, Vec::new()); assert_eq!(archived.status, ThreadStatus::NotLoaded); - let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_thread_archive_event" - && event["event_params"]["thread_id"] == thread.id - }) - .await?; - let occurred_at_ms = event["event_params"]["occurred_at_ms"] - .as_u64() - .expect("thread archive analytics must include its producer timestamp"); - assert_eq!( - event, - json!({ - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": thread.id, - "action": "archived", - "occurred_at_ms": occurred_at_ms, - "app_server_client": { - "product_client_id": "codex_work_desktop", - "client_name": "codex_work_desktop", - "client_version": "0.1.0", - "rpc_transport": "stdio", - "experimental_api_enabled": true, - }, - "runtime": { - "codex_rs_version": env!("CARGO_PKG_VERSION"), - "runtime_os": std::env::consts::OS, - "runtime_os_version": event["event_params"]["runtime"]["runtime_os_version"], - "runtime_arch": std::env::consts::ARCH, - }, - "thread_source": "user", - }, - }) - ); - // Verify file moved. let archived_directory = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR); // The archived file keeps the original filename (rollout-...-.jsonl). @@ -561,7 +522,6 @@ async fn thread_archive_succeeds_when_descendant_archive_fails() -> Result<()> { MockResponsesConfig::new(&server.uri()) .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let parent_id = create_fake_rollout( codex_home.path(), @@ -702,68 +662,13 @@ async fn thread_archive_succeeds_when_descendant_archive_fails() -> Result<()> { .await??; unarchive(&mut mcp, &parent_id).await?; - wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_thread_archive_event" - && event["event_params"]["thread_id"] == grandchild_id - && event["event_params"]["action"] == "unarchived" - }) - .await?; - - let requests = server - .received_requests() - .await - .ok_or_else(|| anyhow::anyhow!("wiremock did not record requests"))?; - let mut archive_events = Vec::new(); - for request in requests { - if request.url.path() != "/codex/analytics-events/events" { - continue; - } - let payload: Value = serde_json::from_slice(&request.body)?; - let events = payload["events"] - .as_array() - .ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?; - for event in events - .iter() - .filter(|event| event["event_type"] == "codex_thread_archive_event") - { - for (header, expected) in [ - ("authorization", "Bearer chatgpt-token"), - ("chatgpt-account-id", "account-123"), - ] { - assert_eq!( - request - .headers - .get(header) - .and_then(|value| value.to_str().ok()), - Some(expected) - ); - } - archive_events.push(event.clone()); - } - } - - let expected = [ - (parent_id.as_str(), "archived"), - (grandchild_id.as_str(), "archived"), - (parent_id.as_str(), "unarchived"), - (grandchild_id.as_str(), "unarchived"), - ]; - assert_eq!(archive_events.len(), expected.len()); - for (event, (thread_id, action)) in archive_events.iter().zip(expected) { - let occurred_at_ms = event["event_params"]["occurred_at_ms"] - .as_u64() - .expect("thread archive analytics must include its producer timestamp"); - assert_eq!( - event, - &json!({ - "event_type": "codex_thread_archive_event", - "event_params": { - "thread_id": thread_id, - "action": action, - "occurred_at_ms": occurred_at_ms, - }, - }) - ); + for thread_id in [&parent_id, &grandchild_id] { + let notification: ThreadUnarchivedNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_notification("thread/unarchived"), + ) + .await??; + assert_eq!(¬ification.thread_id, thread_id); } Ok(()) diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index 3d05a626..a99f1245 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -103,11 +103,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::assert_basic_thread_initialized_event; -use super::analytics::mount_analytics_capture; -use super::analytics::thread_initialized_event; -use super::analytics::wait_for_analytics_payload; - #[cfg(windows)] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] @@ -1453,63 +1448,6 @@ async fn thread_fork_can_exclude_turns_and_skip_restored_token_usage() -> Result Ok(()) } -#[tokio::test] -async fn thread_fork_tracks_thread_initialized_analytics() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let conversation_id = create_fake_rollout( - codex_home.path(), - "2025-01-05T12-00-00", - "2025-01-05T12:00:00Z", - "Saved user message", - Some("mock_provider"), - /*git_info*/ None, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .without_managed_config() - .build_initialized() - .await?; - - let fork_id = mcp - .send_thread_fork_request(ThreadForkParams { - thread_id: conversation_id, - thread_source: Some(ThreadSource::User), - ..Default::default() - }) - .await?; - let ThreadForkResponse { thread, .. } = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(fork_id)).await??; - - let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?; - let event = thread_initialized_event(&payload)?; - assert_basic_thread_initialized_event( - event, - &thread.id, - &thread.session_id, - "codex", - "mock-model", - "forked", - "user", - ); - assert_eq!( - event["event_params"]["forked_from_thread_id"], - thread - .forked_from_id - .as_deref() - .expect("forked thread has a source thread") - ); - Ok(()) -} - #[test_case(ThreadHistoryMode::Legacy; "legacy")] #[test_case(ThreadHistoryMode::Paginated; "paginated")] #[tokio::test] diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 096ddfed..8ed5839d 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -52,6 +52,7 @@ use codex_app_server_protocol::ThreadGoalGetParams; use codex_app_server_protocol::ThreadGoalGetResponse; use codex_app_server_protocol::ThreadGoalSetResponse; use codex_app_server_protocol::ThreadGoalStatus; +use codex_app_server_protocol::ThreadGoalUpdatedNotification; use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::ThreadListResponse; @@ -66,7 +67,6 @@ use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadSettingsUpdateParams; use codex_app_server_protocol::ThreadSettingsUpdateResponse; -use codex_app_server_protocol::ThreadSource; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStatus; @@ -151,13 +151,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::assert_basic_thread_initialized_event; -use super::analytics::mount_analytics_capture; -use super::analytics::thread_initialized_event; -use super::analytics::wait_for_analytics_payload; -use super::analytics::wait_for_goal_event; -use super::analytics::wait_for_matching_analytics_event; - #[path = "thread_resume_account_tests.rs"] mod account_tests; @@ -2637,166 +2630,6 @@ async fn goal_first_live_thread_appears_in_state_db_thread_list() -> Result<()> Ok(()) } -#[tokio::test] -async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - - let codex_home = TempDir::new()?; - mock_responses_config(&server.uri()) - .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let conversation_id = create_fake_rollout( - codex_home.path(), - "2025-01-05T12-00-00", - "2025-01-05T12:00:00Z", - "Saved user message", - Some("mock_provider"), - /*git_info*/ None, - )?; - set_session_meta_on_fake_rollout( - codex_home.path(), - "2025-01-05T12-00-00", - &conversation_id, - "user", - "codex_work_desktop", - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - - let resume_id = mcp - .send_thread_resume_request(ThreadResumeParams { - thread_id: conversation_id, - ..Default::default() - }) - .await?; - let ThreadResumeResponse { thread, .. } = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; - assert!( - !thread.session_id.is_empty(), - "session id should not be empty" - ); - assert_eq!(thread.thread_source, Some(ThreadSource::User)); - - let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?; - let event = thread_initialized_event(&payload)?; - assert_basic_thread_initialized_event( - event, - &thread.id, - &thread.session_id, - "codex_work_desktop", - "gpt-5.4", - "resumed", - "user", - ); - assert_eq!(event["event_params"]["thread_source"], "user"); - Ok(()) -} - -#[tokio::test] -async fn thread_resume_running_thread_tracks_thread_originator_in_analytics() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - - let codex_home = TempDir::new()?; - mock_responses_config(&server.uri()) - .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - - let start_id = mcp - .send_thread_start_request_with_auto_env(ThreadStartParams { - model: Some("mock-model".to_string()), - thread_source: Some(ThreadSource::User), - service_name: Some("codex_work_desktop".to_string()), - ..Default::default() - }) - .await?; - let ThreadStartResponse { thread, .. } = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(start_id)).await??; - - let turn_id = mcp - .send_turn_start_request(TurnStartParams { - thread_id: thread.id.clone(), - client_user_message_id: None, - input: vec![UserInput::Text { - text: "materialize rollout".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - let resume_id = mcp - .send_thread_resume_request(ThreadResumeParams { - thread_id: thread.id.clone(), - exclude_turns: true, - ..Default::default() - }) - .await?; - let ThreadResumeResponse { - thread: resumed, .. - } = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; - - let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_thread_initialized" - && event["event_params"]["thread_id"] == resumed.id - && event["event_params"]["initialization_mode"] == "resumed" - }) - .await?; - assert_basic_thread_initialized_event( - &event, - &resumed.id, - &resumed.session_id, - "codex_work_desktop", - "mock-model", - "resumed", - "user", - ); - Ok(()) -} - -fn set_session_meta_on_fake_rollout( - codex_home: &std::path::Path, - filename_ts: &str, - thread_id: &str, - thread_source: &str, - originator: &str, -) -> Result<()> { - let path = rollout_path(codex_home, filename_ts, thread_id); - let contents = std::fs::read_to_string(&path)?; - let mut lines = contents.lines(); - let session_meta = lines - .next() - .ok_or_else(|| anyhow::anyhow!("fake rollout missing session meta"))?; - let mut session_meta: serde_json::Value = serde_json::from_str(session_meta)?; - session_meta["payload"]["thread_source"] = serde_json::json!(thread_source); - session_meta["payload"]["originator"] = serde_json::json!(originator); - let remaining = lines.collect::>().join("\n"); - std::fs::write(&path, format!("{session_meta}\n{remaining}\n"))?; - Ok(()) -} - #[tokio::test] async fn thread_resume_returns_rollout_history() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -4016,7 +3849,7 @@ fn ungated_goal_response(body: String) -> Vec { } #[tokio::test] -async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Result<()> { +async fn thread_goal_lifecycle_accounts_usage_and_clear_deletes_goal() -> Result<()> { let server = create_mock_responses_server_sequence_unchecked(vec![ responses::sse(vec![ responses::ev_response_created("materialize-thread"), @@ -4031,9 +3864,7 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul let codex_home = TempDir::new()?; mock_responses_config(&server.uri()) .enable_feature(Feature::Goals) - .with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri())) .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -4090,36 +3921,19 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul ) .await??; - let created = wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "created", "active").await?; - let persisted_goal_id = created["event_params"]["goal_id"] - .as_str() - .expect("created goal id"); - assert_eq!(created["event_params"]["thread_id"], thread.id); - assert_eq!(created["event_params"]["turn_id"], serde_json::Value::Null); - assert_eq!(created["event_params"]["has_token_budget"], true); - assert!(created["event_params"]["session_id"].is_string()); - assert!(created["event_params"]["app_server_client"].is_object()); - assert!(created["event_params"]["runtime"].is_object()); - assert!(created["event_params"].get("objective").is_none()); - assert!(created["event_params"].get("token_budget").is_none()); - - let usage = wait_for_goal_event( - &server, - DEFAULT_READ_TIMEOUT, - "usage_accounted", - "budget_limited", - ) - .await?; - let causal_turn_id = usage["event_params"]["turn_id"] - .as_str() - .expect("accounted usage turn id"); - assert_eq!(usage["event_params"]["goal_id"], persisted_goal_id); - assert_eq!(usage["event_params"]["cumulative_tokens_accounted"], 200); - assert!( - usage["event_params"]["cumulative_time_accounted_seconds"] - .as_i64() - .is_some() - ); + // The continuation turn spends the whole budget. + let budget_limited = timeout(DEFAULT_READ_TIMEOUT, async { + loop { + let notification: ThreadGoalUpdatedNotification = + mcp.read_notification("thread/goal/updated").await?; + if notification.goal.status == ThreadGoalStatus::BudgetLimited { + return Ok::<_, anyhow::Error>(notification); + } + } + }) + .await??; + assert_eq!(budget_limited.thread_id, thread.id); + assert_eq!(budget_limited.goal.tokens_used, 200); let requests = server .received_requests() @@ -4138,35 +3952,10 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul let metadata: serde_json::Value = serde_json::from_str(metadata_header)?; assert_eq!(metadata["turn_trigger"].as_str(), Some("goal")); - let status = wait_for_goal_event( - &server, - DEFAULT_READ_TIMEOUT, - "status_changed", - "budget_limited", - ) - .await?; - assert_eq!(status["event_params"]["goal_id"], persisted_goal_id); - assert_eq!(status["event_params"]["turn_id"], causal_turn_id); - assert_eq!( - status["event_params"]["cumulative_tokens_accounted"], - serde_json::Value::Null - ); - assert_eq!( - status["event_params"]["cumulative_time_accounted_seconds"], - serde_json::Value::Null - ); - - let requests = server.received_requests().await.expect("wiremock requests"); - let goal_request = requests - .iter() - .filter(|request| request.url.path().ends_with("/responses")) - .nth(1) - .expect("externally created goal continuation request"); - let goal_request_body = goal_request.body_json::()?; - assert_eq!( - goal_request_body["client_metadata"]["turn_id"], - causal_turn_id - ); + let goal_request_body = response_requests[1].body_json::()?; + let causal_turn_id = goal_request_body["client_metadata"]["turn_id"] + .as_str() + .expect("goal continuation turn id"); responses::assert_root_turn(&goal_request_body, Some(causal_turn_id))?; responses::assert_parent_turn(&goal_request_body, /*expected*/ None)?; @@ -4188,11 +3977,6 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul ) .await??; - let cleared = - wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "cleared", "budget_limited").await?; - assert_eq!(cleared["event_params"]["goal_id"], persisted_goal_id); - assert_eq!(cleared["event_params"]["turn_id"], serde_json::Value::Null); - let get_id = mcp .send_raw_request( "thread/goal/get", diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index c8956575..a10312fa 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -62,11 +62,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::assert_basic_thread_initialized_event; -use super::analytics::mount_analytics_capture; -use super::analytics::thread_initialized_event; -use super::analytics::wait_for_analytics_payload; - const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const INVALID_REQUEST_ERROR_CODE: i64 = -32600; const EXEC_POLICY_PARSE_WARNING_SUMMARY: &str = "Error parsing rules; custom rules not applied."; @@ -955,44 +950,6 @@ fn normalize_path_for_comparison(path: impl AsRef) -> PathBuf { path.as_ref().to_path_buf() } -#[test_case("codex_work_desktop")] -#[tokio::test] -async fn thread_start_tracks_thread_initialized_analytics(originator: &str) -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - - let codex_home = TempDir::new()?; - create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - - let ThreadStartResponse { thread, .. } = mcp - .start_thread(ThreadStartParams { - thread_source: Some(ThreadSource::User), - service_name: Some(originator.to_string()), - ..Default::default() - }) - .await?; - - let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?; - assert_eq!(payload["events"].as_array().expect("events array").len(), 1); - let event = thread_initialized_event(&payload)?; - assert_basic_thread_initialized_event( - event, - &thread.id, - &thread.session_id, - originator, - "mock-model", - "new", - "user", - ); - Ok(()) -} - #[tokio::test] async fn thread_start_respects_project_config_from_cwd() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs b/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs deleted file mode 100644 index f9a06f2e..00000000 --- a/codex-rs/app-server/tests/suite/v2/turn_cost_otel.rs +++ /dev/null @@ -1,324 +0,0 @@ -//! Exercises the best-effort SiWC cost happy path through real app-server startup and OTLP. -//! The public in-process transport permits advancing the production timer without test-only hooks. - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::write_chatgpt_auth; -use app_test_support::write_models_cache; -use codex_app_server::in_process; -use codex_app_server::in_process::InProcessServerEvent; -use codex_app_server::in_process::InProcessStartArgs; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -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; -use codex_arg0::Arg0DispatchPaths; -use codex_config::CloudConfigBundleLoader; -use codex_config::LoaderOverrides; -use codex_config::NoopThreadConfigLoader; -use codex_core::config::ConfigBuilder; -use codex_exec_server::EnvironmentManager; -use codex_feedback::CodexFeedback; -use codex_login::AuthCredentialsStoreMode; -use codex_protocol::protocol::SessionSource; -use core_test_support::responses; -use core_test_support::test_codex::test_env; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::sync::Arc; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const COST_PATH: &str = "/api/codex/usage/thread-estimates/query"; - -#[tokio::test] -async fn chatgpt_turn_cost_reaches_otlp_on_success() -> Result<()> { - let server = MockServer::start().await; - let collector = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/metrics")) - .respond_with(ResponseTemplate::new(200)) - .mount(&collector) - .await; - Mock::given(method("POST")).and(path(COST_PATH)) - .and(header("authorization", "Bearer siwc-token")) - .and(header("chatgpt-account-id", "workspace-a")) - .respond_with(move |request: &wiremock::Request| { - let body: Value = serde_json::from_slice(&request.body).expect("cost request"); - assert_eq!(body["include_settled_response_ids"], true); - let threads: Vec<_> = body["threads"].as_array().expect("threads").iter().map(|thread| { - let turns: Vec<_> = thread["turn_ids"].as_array().expect("turns").iter().map(|turn_id| json!({ - "turn_id": turn_id, "model": "mock-model", "estimated_usage_usd_micros": 1250001, - "settled_response_ids": ["resp-cost"] - })).collect(); - json!({"thread_id": thread["thread_id"], "turns": turns}) - }).collect(); - ResponseTemplate::new(200).set_body_json(json!({"threads": threads})) - }).mount(&server).await; - let model = responses::mount_sse_once( - &server, - responses::sse(vec![ - responses::ev_response_created("resp-cost"), - responses::ev_assistant_message("msg-cost", "Done"), - responses::ev_completed("resp-cost"), - ]), - ) - .await; - let home = TempDir::new()?; - std::fs::write( - home.path().join("config.toml"), - format!( - r#" -model = "mock-model" -model_provider = "openai" -openai_base_url = "{}/v1" -chatgpt_base_url = "{}" -approval_policy = "never" -[features] -responses_websockets = false -responses_websockets_v2 = false -runtime_metrics = true -[analytics] -enabled = true -[otel] -exporter = "none" -metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" }} }} -"#, - server.uri(), - server.uri(), - collector.uri() - ), - )?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new("siwc-token") - .account_id("workspace-a") - .chatgpt_account_id("workspace-a") - .chatgpt_user_id("user-a"), - AuthCredentialsStoreMode::File, - )?; - write_models_cache(home.path()).await?; - let loader_overrides = LoaderOverrides::without_managed_config_for_tests(); - let config = Arc::new( - ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .loader_overrides(loader_overrides.clone()) - .build() - .await?, - ); - let provider = codex_core::otel_init::build_provider( - &config, - "test", - Some("codex-app-server"), - /*default_analytics_enabled*/ false, - ) - .map_err(|error| anyhow::anyhow!(error.to_string()))? - .expect("OTLP enabled"); - let metrics = provider.metrics.clone().expect("metrics exporter"); - let env = test_env().await?; - let environment_manager = if let Some(url) = env.exec_server_url() { - EnvironmentManager::create_for_tests( - Some(url.to_string()), - /*local_runtime_paths*/ None, - ) - .await - } else { - EnvironmentManager::default_for_tests() - }; - let mut client = in_process::start(InProcessStartArgs { - arg0_paths: Arg0DispatchPaths::default(), - config, - cli_overrides: Vec::new(), - loader_overrides, - strict_config: false, - cloud_config_bundle: CloudConfigBundleLoader::default(), - embedded_network_policy: Default::default(), - thread_config_loader: Arc::new(NoopThreadConfigLoader), - feedback: CodexFeedback::new(), - log_db: None, - state_db: None, - environment_manager: Arc::new(environment_manager), - config_warnings: Vec::new(), - session_source: SessionSource::Cli, - enable_codex_api_key_env: false, - initialize: InitializeParams { - client_info: ClientInfo { - name: "codex-app-server-tests".to_string(), - title: None, - version: "test".to_string(), - }, - capabilities: Some(InitializeCapabilities { - experimental_api: true, - ..Default::default() - }), - }, - channel_capacity: in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, - }) - .await?; - wait_for_cost_queries(&server, /*count*/ 1).await; - let response = client - .request(ClientRequest::ThreadStart { - request_id: RequestId::Integer(1), - params: ThreadStartParams { - environments: Some(vec![TurnEnvironmentParams { - environment_id: env.selection().environment_id.clone(), - cwd: env.selection().cwd.clone().into(), - runtime_workspace_roots: None, - }]), - ..Default::default() - }, - }) - .await? - .expect("thread/start"); - let ThreadStartResponse { thread, .. } = serde_json::from_value(response)?; - let response = client - .request(ClientRequest::TurnStart { - request_id: RequestId::Integer(2), - params: TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }, - }) - .await? - .expect("turn/start"); - let TurnStartResponse { turn } = serde_json::from_value(response)?; - timeout(Duration::from_secs(/*secs*/ 30), async { - while let Some(event) = client.next_event().await { - if let InProcessServerEvent::ServerNotification(event) = event - && let ServerNotification::TurnCompleted(event) = *event - { - assert!( - event.turn.error.is_none(), - "turn failed: {:?}", - event.turn.error - ); - break; - } - } - }) - .await?; - assert_eq!( - model.single_request().header("authorization").as_deref(), - Some("Bearer siwc-token") - ); - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(/*secs*/ 301)).await; - tokio::time::resume(); - wait_for_cost_queries(&server, /*count*/ 2).await; - // Synchronize with actual recording, not just the backend receiving a request. - timeout(Duration::from_secs(/*secs*/ 10), async { - loop { - if metrics - .snapshot() - .expect("snapshot") - .scope_metrics() - .flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics) - .any(|metric| metric.name() == "codex.turn.cost_microusd") - { - break; - } - tokio::task::yield_now().await; - } - }) - .await?; - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(/*secs*/ 301)).await; - tokio::time::resume(); - client.shutdown().await?; - tokio::task::spawn_blocking(move || provider.shutdown()).await?; - let mut points = Vec::new(); - for request in collector.received_requests().await.expect("OTLP requests") { - let body: Value = serde_json::from_slice(&request.body)?; - for resource in body["resourceMetrics"] - .as_array() - .expect("resource metrics") - { - for scope in resource["scopeMetrics"].as_array().expect("scope metrics") { - for metric in scope["metrics"].as_array().expect("metrics") { - if metric["name"] == "codex.turn.cost_microusd" { - points.extend( - metric["sum"]["dataPoints"] - .as_array() - .expect("cost points") - .clone(), - ); - } - } - } - } - } - assert_eq!(points.len(), 1); - assert_eq!(points[0]["asInt"], json!(1250001)); - let attrs: std::collections::BTreeMap<_, _> = points[0]["attributes"] - .as_array() - .expect("attributes") - .iter() - .map(|attr| { - ( - attr["key"].as_str().expect("key"), - attr["value"]["stringValue"].as_str().expect("value"), - ) - }) - .collect(); - assert_eq!(attrs["turn.id"], turn.id); - assert_eq!(attrs["conversation.id"], thread.id); - assert_eq!(attrs["auth_mode"], "Chatgpt"); - let requests = server - .received_requests() - .await - .expect("settlement requests"); - let cost_requests: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == COST_PATH) - .collect(); - assert_eq!(cost_requests.len(), 2); - assert_eq!( - serde_json::from_slice::(&cost_requests[1].body)?, - json!({ - "threads": [{"thread_id": thread.id, "turn_ids": [turn.id]}], "include_settled_response_ids": true - }) - ); - server.verify().await; - Ok(()) -} - -async fn wait_for_cost_queries(server: &MockServer, count: usize) { - timeout(Duration::from_secs(/*secs*/ 15), async { - loop { - if server - .received_requests() - .await - .expect("requests") - .iter() - .filter(|request| request.url.path() == COST_PATH) - .count() - >= count - { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("cost query"); -} diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index dfa24492..0c423b52 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -11,7 +11,6 @@ use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_mock_responses_server_sequence_unchecked; -use app_test_support::create_request_user_input_sse_response; use app_test_support::format_with_current_shell_display; use app_test_support::write_chatgpt_auth; use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; @@ -116,10 +115,6 @@ use wiremock::matchers::body_partial_json; use wiremock::matchers::method; use wiremock::matchers::path; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_analytics_event; -use super::analytics::wait_for_matching_analytics_event; - #[cfg(windows)] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] @@ -357,13 +352,8 @@ async fn turn_start_omits_notification_media_without_changing_model_input() -> R Ok(()) } -#[test_case(None; "analytics_unset")] -#[test_case(Some(true); "analytics_enabled")] -#[test_case(Some(false); "analytics_disabled")] #[tokio::test] -async fn tool_call_metadata_stays_out_of_raw_response_item_notifications( - analytics_enabled: Option, -) -> Result<()> { +async fn tool_call_metadata_stays_out_of_raw_response_item_notifications() -> Result<()> { skip_if_no_network!(Ok(())); let arguments = json!({"query": "redaction"}); @@ -409,7 +399,7 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications( .mount(&server) .await; let codex_home = TempDir::new()?; - let mut config = MockResponsesConfig::new(&server.uri()) + MockResponsesConfig::new(&server.uri()) .with_provider_name("OpenAI") .with_provider_config("supports_websockets = false") .with_root_config(&format!( @@ -417,11 +407,8 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications( apps.chatgpt_base_url )) .enable_feature(Feature::Apps) - .enable_feature(Feature::ExecutedToolCallMetadata); - if let Some(enabled) = analytics_enabled { - config = config.with_extra_config(&format!("[analytics]\nenabled = {enabled}")); - } - config.write(codex_home.path())?; + .enable_feature(Feature::ExecutedToolCallMetadata) + .write(codex_home.path())?; write_chatgpt_auth( codex_home.path(), ChatGptAuthFixture::new("chatgpt-test-token") @@ -537,11 +524,11 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications( .find(|item| item["type"] == "function_call_output" && item["call_id"] == "mcp-call") .context("persisted MCP output")?; assert_eq!(captured["output"], raw_output["output"]); - // The custom inference endpoint omits raw metadata, so verify capture in the rollout. + // Raw MCP result metadata is never recorded, not even in the local rollout. assert_eq!( captured["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0] .get("tool_result_metadata"), - (analytics_enabled != Some(false)).then_some(&result_metadata), + None, ); Ok(()) } @@ -555,7 +542,6 @@ async fn turn_start_with_empty_input_runs_model_request() -> Result<()> { MockResponsesConfig::new(&server.uri()) .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -610,15 +596,6 @@ async fn turn_start_with_empty_input_runs_model_request() -> Result<()> { [codex_app_server_protocol::ThreadItem { payload: ThreadItemPayload::AgentMessage { text, .. }, .. }] if text == "Done" )); - let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; - assert_eq!( - ( - event["event_params"]["turn_id"].as_str(), - event["event_params"]["root_turn_id"].as_str(), - ), - (Some(turn.id.as_str()), Some(turn.id.as_str())) - ); - let requests = server .received_requests() .await @@ -1497,7 +1474,7 @@ async fn thread_start_omits_empty_instruction_overrides_from_model_request() -> } #[tokio::test] -async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { +async fn turn_start_forwards_trigger_and_source_after_retry() -> Result<()> { let server = responses::start_mock_server().await; let response_mock = responses::mount_response_sequence( &server, @@ -1523,7 +1500,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { let config = std::fs::read_to_string(&config_path)? .replace("stream_max_retries = 0", "stream_max_retries = 1"); std::fs::write(config_path, config)?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -1540,7 +1516,7 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { }) .await?; - let TurnStartResponse { turn } = mcp + let _: TurnStartResponse = mcp .request(|request_id| ClientRequest::TurnStart { request_id, params: TurnStartParams { @@ -1568,11 +1544,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { ) .await??; - let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; - assert_eq!(event["event_params"]["thread_id"], thread.id); - assert_eq!(event["event_params"]["session_id"], thread.session_id); - assert_eq!(event["event_params"]["turn_id"], turn.id); - assert_eq!(event["event_params"]["root_turn_id"], turn.id); let request = response_mock.requests()[0].body_json(); let request_metadata: Value = serde_json::from_str( request["client_metadata"]["x-codex-turn-metadata"] @@ -1581,82 +1552,14 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { )?; assert_eq!( json!({ - "eventTrigger": event["event_params"]["turn_trigger"], - "eventSource": event["event_params"]["codex_turn_source"], "requestTrigger": request_metadata["turn_trigger"], "requestSource": request_metadata["source"], - }), - json!({ - "eventTrigger": "user", - "eventSource": "composer", - "requestTrigger": "user", - "requestSource": "composer", - }) - ); - assert_eq!( - event["event_params"]["app_server_client"]["product_client_id"], - "codex_work_desktop" - ); - assert_eq!(event["event_params"]["model"], "mock-model"); - assert_eq!(event["event_params"]["model_provider"], "mock_provider"); - assert_eq!(event["event_params"]["sandbox_policy"], "read_only"); - assert_eq!(event["event_params"]["workspace_kind"], "projectless"); - assert_eq!(event["event_params"]["ephemeral"], false); - assert_eq!(event["event_params"]["thread_source"], "user"); - assert_eq!(event["event_params"]["initialization_mode"], "new"); - assert_eq!( - event["event_params"]["subagent_source"], - serde_json::Value::Null - ); - assert_eq!( - event["event_params"]["parent_thread_id"], - serde_json::Value::Null - ); - assert_eq!(event["event_params"]["num_input_images"], 1); - assert_eq!( - event["event_params"]["image_preparations"], - json!([{ - "message_role": "user", - "item_id": null, - "effective_detail": "high", - "source_width": 1, - "source_height": 1, - "prepared_width": 1, - "prepared_height": 1, - }]) - ); - assert_eq!(event["event_params"]["status"], "completed"); - assert!(event["event_params"]["started_at"].as_u64().is_some()); - assert!(event["event_params"]["completed_at"].as_u64().is_some()); - assert!(event["event_params"]["duration_ms"].as_u64().is_some()); - assert_eq!(event["event_params"]["input_tokens"], 0); - assert_eq!(event["event_params"]["cached_input_tokens"], 0); - assert_eq!(event["event_params"]["output_tokens"], 0); - assert_eq!(event["event_params"]["reasoning_output_tokens"], 0); - assert_eq!(event["event_params"]["total_tokens"], 0); - let params = &event["event_params"]; - let timings_are_numbers = [ - "before_first_sampling_ms", - "sampling_ms", - "between_sampling_overhead_ms", - "tool_blocking_ms", - "after_last_sampling_ms", - ] - .into_iter() - .all(|field| params[field].as_u64().is_some()); - assert_eq!( - json!({ - "timingsAreNumbers": timings_are_numbers, - "toolBlockingMs": params["tool_blocking_ms"], - "samplingRequestCount": params["sampling_request_count"], - "samplingRetryCount": params["sampling_retry_count"], "responseRequestCount": response_mock.requests().len(), }), json!({ - "timingsAreNumbers": true, - "toolBlockingMs": 0, - "samplingRequestCount": 2, - "samplingRetryCount": 1, + "requestTrigger": "user", + "requestSource": "composer", + // The first sampling request fails with a retryable error. "responseRequestCount": 2, }) ); @@ -1664,296 +1567,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn code_mode_exec_emits_correlated_production_analytics() -> Result<()> { - let server = responses::start_mock_server().await; - let _responses = responses::mount_sse_sequence( - &server, - vec![ - responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_custom_tool_call("exec-1", "exec", "text('analytics');"), - responses::ev_completed("resp-1"), - ]), - responses::sse(vec![responses::ev_completed("resp-2")]), - ], - ) - .await; - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .enable_feature(Feature::CodeModeOnly) - .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - let params = ThreadStartParams::default(); - let thread = app_server.start_thread(params).await?; - let turn = app_server - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.thread.id, - input: vec![V2UserInput::Text { - text: "run exec".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - - let event = wait_for_analytics_event( - &server, - DEFAULT_READ_TIMEOUT, - "codex_dynamic_tool_call_event", - ) - .await?; - assert_eq!( - json!({ - "turnId": event["event_params"]["turn_id"], - "rootTurnId": event["event_params"]["root_turn_id"], - "tool": event["event_params"]["tool_name"], - "origin": event["event_params"]["originating_response_id"], - "subsequent": event["event_params"]["subsequent_response_id"], - "hasCell": event["event_params"]["cell_id"].as_str().is_some(), - }), - json!({ - "turnId": turn.turn.id, - "rootTurnId": turn.turn.id, - "tool": "exec", - "origin": "resp-1", - "subsequent": "resp-2", - "hasCell": true, - }) - ); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<()> { - let control_tools = [ - ("call1", "request_user_input", json!({})), - ( - "plan-call", - "update_plan", - json!({"plan": [{"step": "PRIVATE_PLAN", "status": "in_progress"}]}), - ), - ( - "image-call", - "view_image", - json!({"path": "PRIVATE_IMAGE_PATH.png"}), - ), - ("get-goal-call", "get_goal", json!({})), - ( - "create-goal-call", - "create_goal", - json!({"objective": "PRIVATE_GOAL"}), - ), - ( - "update-goal-call", - "update_goal", - json!({"status": "complete"}), - ), - ]; - let mut responses = vec![ - create_request_user_input_sse_response("call1")?, - create_final_assistant_message_sse_response("Done")?, - ]; - responses.extend(control_tools.iter().skip(1).map(|(call_id, tool, args)| { - let response_id = format!("resp-{call_id}"); - responses::sse(vec![ - responses::ev_response_created(&response_id), - responses::ev_function_call(call_id, tool, &args.to_string()), - responses::ev_completed(&response_id), - ]) - })); - responses.push(create_final_assistant_message_sse_response("Done")?); - let server = create_mock_responses_server_sequence(responses).await; - - let codex_home = TempDir::new()?; - MockResponsesConfig::new(&server.uri()) - .enable_feature(Feature::Goals) - .with_root_config(&format!( - "chatgpt_base_url = \"{}\"\ntools.update_plan.enabled = true", - server.uri() - )) - .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized() - .await?; - - let ThreadStartResponse { thread, .. } = mcp - .start_thread(ThreadStartParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - - let TurnStartResponse { turn: first_turn } = mcp - .request(|request_id| ClientRequest::TurnStart { - request_id, - params: TurnStartParams { - thread_id: thread.id.clone(), - client_user_message_id: None, - input: vec![V2UserInput::Text { - text: "ask something".to_string(), - text_elements: Vec::new(), - }], - collaboration_mode: Some(CollaborationMode { - mode: ModeKind::Plan, - settings: Settings { - model: "mock-model".to_string(), - reasoning_effort: Some(ReasoningEffort::Medium), - developer_instructions: None, - }, - }), - ..Default::default() - }, - }) - .await?; - - let server_req = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::ToolRequestUserInput { request_id, .. } = server_req else { - panic!("expected ToolRequestUserInput request, got: {server_req:?}"); - }; - tokio::time::sleep(std::time::Duration::from_millis(25)).await; - mcp.send_response( - request_id, - json!({ - "answers": { - "confirm_path": { "answers": ["yes"] } - } - }), - ) - .await?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; - let params = &event["event_params"]; - assert_eq!( - json!({ - "turnId": params["turn_id"], - "rootTurnId": params["root_turn_id"], - "toolBlockingIsPositive": params["tool_blocking_ms"] - .as_u64() - .is_some_and(|duration| duration > 0), - "samplingRequestCount": params["sampling_request_count"], - "samplingRetryCount": params["sampling_retry_count"], - "totalToolCalls": params["total_tool_call_count"], - "dynamicToolCalls": params["dynamic_tool_call_count"], - "status": params["status"], - }), - json!({ - "turnId": first_turn.id, - "rootTurnId": first_turn.id, - "toolBlockingIsPositive": true, - "samplingRequestCount": 2, - "samplingRetryCount": 0, - "totalToolCalls": 1, - "dynamicToolCalls": 0, - "status": "completed", - }) - ); - - let second_turn = mcp - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![V2UserInput::Text { - text: "run the other control tools".to_string(), - text_elements: Vec::new(), - }], - collaboration_mode: Some(CollaborationMode { - mode: ModeKind::Default, - settings: Settings { - model: "mock-model".to_string(), - reasoning_effort: Some(ReasoningEffort::Medium), - developer_instructions: None, - }, - }), - ..Default::default() - }) - .await?; - - for (call_id, tool_name, _) in control_tools { - let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_control_tool_call_event" - && event["event_params"]["item_id"] == call_id - }) - .await?; - let success = tool_name != "view_image"; - let turn_id = if call_id == "call1" { - &first_turn.id - } else { - &second_turn.turn.id - }; - assert_eq!( - json!({ - "turnId": event["event_params"]["turn_id"], - "rootTurnId": event["event_params"]["root_turn_id"], - "tool": event["event_params"]["tool_name"], - "success": event["event_params"]["success"], - "status": event["event_params"]["terminal_status"], - "hasOrigin": event["event_params"]["originating_response_id"] - .as_str() - .is_some(), - }), - json!({ - "turnId": turn_id, - "rootTurnId": turn_id, - "tool": tool_name, - "success": success, - "status": if success { "completed" } else { "failed" }, - "hasOrigin": true, - }) - ); - let serialized = event.to_string(); - assert!( - ![ - "PRIVATE_PLAN", - "PRIVATE_IMAGE_PATH", - "PRIVATE_GOAL", - "Proceed with the plan?" - ] - .iter() - .any(|private_input| serialized.contains(private_input)), - "tool-call analytics must not contain private tool arguments: {serialized}" - ); - } - - let second_turn_event = - wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == second_turn.turn.id - }) - .await?; - assert_eq!( - json!({ - "rootTurnId": second_turn_event["event_params"]["root_turn_id"], - "total": second_turn_event["event_params"]["total_tool_call_count"], - "dynamic": second_turn_event["event_params"]["dynamic_tool_call_count"], - }), - json!({"rootTurnId": second_turn.turn.id, "total": 5, "dynamic": 0}) - ); - - Ok(()) -} - #[tokio::test] async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> { let responses = vec![create_final_assistant_message_sse_response("Done")?]; @@ -4426,7 +4039,6 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<() server.uri() )) .write(codex_home.path())?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -4545,42 +4157,22 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<() assert_eq!(turn_completed.thread_id, thread.id); assert_eq!(turn_completed.turn.id, turn.turn.id); - let child_turn_event = - wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["thread_id"] == receiver_thread_id - }) - .await?; - let child_tool_event = - wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_control_tool_call_event" - && event["event_params"]["item_id"] == CHILD_PLAN_CALL_ID - }) - .await?; - let child_request = child_turn - .requests() - .into_iter() - .find(|request| request.body_json()["client_metadata"]["thread_id"] == receiver_thread_id) - .context("child should issue a model request")? - .body_json(); + let child_request = timeout(DEFAULT_READ_TIMEOUT, async { + loop { + if let Some(request) = child_turn.requests().into_iter().find(|request| { + request.body_json()["client_metadata"]["thread_id"] == receiver_thread_id + }) { + return request.body_json(); + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + }) + .await?; let child_turn_id = child_request["client_metadata"]["turn_id"] .as_str() .context("child request should have a turn id")?; assert_ne!(child_turn_id, turn.turn.id); - for event in [child_turn_event, child_tool_event] { - assert_eq!( - json!({ - "thread_id": event["event_params"]["thread_id"], - "turn_id": event["event_params"]["turn_id"], - "root_turn_id": event["event_params"]["root_turn_id"], - }), - json!({ - "thread_id": receiver_thread_id, - "turn_id": child_turn_id, - "root_turn_id": turn.turn.id, - }) - ); - } + responses::assert_root_turn(&child_request, Some(turn.turn.id.as_str()))?; // Reuse this live spawn setup to cover thread/delete's ThreadManager descendant path. let _: ThreadDeleteResponse = mcp @@ -4668,7 +4260,6 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected( .with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri())) .write(codex_home.path())?; write_models_cache(codex_home.path()).await?; - mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -4942,63 +4533,6 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected( ); } - let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_collab_agent_tool_call_event" - && event["event_params"]["item_id"] == SPAWN_CALL_ID - }) - .await?; - assert_eq!( - json!({ - "tool_name": event["event_params"]["tool_name"], - "sender_thread_id": event["event_params"]["sender_thread_id"], - "receiver_thread_ids": event["event_params"]["receiver_thread_ids"], - "agent_state_count": event["event_params"]["agent_state_count"], - "terminal_status": event["event_params"]["terminal_status"], - }), - json!({ - "tool_name": "spawn_agent", - "sender_thread_id": thread.id, - "receiver_thread_ids": [child_thread_id], - "agent_state_count": 1, - "terminal_status": "completed", - }) - ); - let duration_ms = event["event_params"]["duration_ms"] - .as_u64() - .context("successful spawn should report its execution duration")?; - assert_eq!(event["event_params"]["execution_duration_ms"], duration_ms); - assert!(!event.to_string().contains(CHILD_PROMPT)); - - let failed_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_collab_agent_tool_call_event" - && event["event_params"]["item_id"] == FAILED_SPAWN_CALL_ID - }) - .await?; - assert_eq!( - json!({ - "tool_name": failed_event["event_params"]["tool_name"], - "receiver_thread_count": failed_event["event_params"]["receiver_thread_count"], - "receiver_thread_ids": failed_event["event_params"]["receiver_thread_ids"], - "terminal_status": failed_event["event_params"]["terminal_status"], - "failure_kind": failed_event["event_params"]["failure_kind"], - }), - json!({ - "tool_name": "spawn_agent", - "receiver_thread_count": 0, - "receiver_thread_ids": [], - "terminal_status": "failed", - "failure_kind": "tool_error", - }) - ); - assert!(!failed_event.to_string().contains(CHILD_PROMPT)); - - let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" && event["event_params"]["thread_id"] == thread.id - }) - .await?; - assert_eq!(turn_event["event_params"]["subagent_tool_call_count"], 2); - assert_eq!(turn_event["event_params"]["total_tool_call_count"], 2); - Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/turn_steer.rs b/codex-rs/app-server/tests/suite/v2/turn_steer.rs index 38f5cace..9ccb8c94 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_steer.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_steer.rs @@ -6,6 +6,7 @@ use app_test_support::TestAppServer; use app_test_support::create_command_execution_sse_response; use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_mock_responses_server_sequence_unchecked; +use app_test_support::mount_chatgpt_account; use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; use codex_app_server::INVALID_PARAMS_ERROR_CODE; @@ -32,9 +33,6 @@ use std::collections::HashMap; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::mount_analytics_capture; -use super::analytics::wait_for_analytics_event; - const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); #[tokio::test] @@ -49,7 +47,7 @@ async fn turn_steer_requires_active_turn() -> Result<()> { &server.uri(), &server.uri(), )?; - mount_analytics_capture(&server, &codex_home).await?; + mount_chatgpt_account(&server, &codex_home).await?; let mut mcp = TestAppServer::builder() .with_codex_home(&codex_home) @@ -85,21 +83,6 @@ async fn turn_steer_requires_active_turn() -> Result<()> { .await??; assert_eq!(steer_err.error.code, -32600); - let event = - wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_steer_event").await?; - assert_eq!(event["event_params"]["thread_id"], thread.id); - assert_eq!(event["event_params"]["result"], "rejected"); - assert_eq!(event["event_params"]["num_input_images"], 0); - assert_eq!( - event["event_params"]["expected_turn_id"], - "turn-does-not-exist" - ); - assert_eq!( - event["event_params"]["accepted_turn_id"], - serde_json::Value::Null - ); - assert_eq!(event["event_params"]["rejection_reason"], "no_active_turn"); - let malformed_request = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id, @@ -175,7 +158,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> { &server.uri(), &server.uri(), )?; - mount_analytics_capture(&server, &codex_home).await?; + mount_chatgpt_account(&server, &codex_home).await?; let mut mcp = TestAppServer::builder() .with_codex_home(&codex_home) @@ -292,7 +275,7 @@ async fn turn_steer_returns_active_turn_id(tool_outputs: bool) -> Result<()> { &server.uri(), &server.uri(), )?; - mount_analytics_capture(&server, &codex_home).await?; + mount_chatgpt_account(&server, &codex_home).await?; let mut mcp = TestAppServer::builder() .with_codex_home(&codex_home) @@ -387,19 +370,6 @@ async fn turn_steer_returns_active_turn_id(tool_outputs: bool) -> Result<()> { }) .await??; - let event = - wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_steer_event").await?; - assert_eq!(event["event_params"]["thread_id"], thread.id); - assert_eq!(event["event_params"]["session_id"], thread.session_id); - assert_eq!(event["event_params"]["result"], "accepted"); - assert_eq!(event["event_params"]["num_input_images"], 0); - assert_eq!(event["event_params"]["expected_turn_id"], turn.id); - assert_eq!(event["event_params"]["accepted_turn_id"], turn.id); - assert_eq!( - event["event_params"]["rejection_reason"], - serde_json::Value::Null - ); - timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/completed"), @@ -476,7 +446,7 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu &server.uri(), &server.uri(), )?; - mount_analytics_capture(&server, &codex_home).await?; + mount_chatgpt_account(&server, &codex_home).await?; let mut mcp = TestAppServer::builder() .with_codex_home(&codex_home) diff --git a/codex-rs/backend-client/src/analytics_session.rs b/codex-rs/backend-client/src/analytics_session.rs deleted file mode 100644 index 3445a1a7..00000000 --- a/codex-rs/backend-client/src/analytics_session.rs +++ /dev/null @@ -1,182 +0,0 @@ -//! Local analytics authentication, server plan discovery, and account/user identity checks. -//! Each new session fetches its plan once; token plan claims do not select reports. - -use crate::Client; -use crate::RequestError; -use codex_features::RuntimeAuthMode; -use codex_http_client::HttpClientFactory; -use codex_login::AuthManager; -use codex_login::AuthManagerConfig; -use codex_login::CodexAuth; -use codex_protocol::account::PlanType; -use codex_runtime_agent_instance::RegistrationError; -use codex_runtime_agent_instance::RuntimeAuthError; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::resolve_installation_id; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::sync::Arc; - -/// Non-secret account metadata associated with an analytics session. -#[derive(Clone, Debug)] -pub struct AnalyticsAccount { - pub id: String, - pub email: Option, - pub plan_type: Option, -} - -/// A backend client bound to its initial ChatGPT account and user, with a server plan snapshot. -pub struct AnalyticsSession { - client: Client, - auth_manager: Arc, - auth: CodexAuth, - account: AnalyticsAccount, -} - -impl AnalyticsSession { - /// Load local ChatGPT credentials and the current server plan using the configured HTTP policy. - pub async fn from_config( - config: &impl AuthManagerConfig, - http_client_factory: HttpClientFactory, - runtime_auth_mode: Option, - ) -> Result { - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false) - .await - .map_err(|_| { - "Couldn't load local sign-in. Sign in with ChatGPT and retry.".to_string() - })?; - let auth = auth_manager - .auth() - .await - .filter(CodexAuth::is_chatgpt_auth) - .ok_or("Sign in locally with ChatGPT to view Analytics.")?; - let (Some(id), Some(_)) = (auth.get_account_id(), auth.get_chatgpt_user_id()) else { - return Err("Analytics requires a ChatGPT account and user identity.".into()); - }; - let account = AnalyticsAccount { - id, - email: auth.get_account_email(), - plan_type: None, - }; - let base_url = config.chatgpt_base_url(); - let runtime_auth_mode = runtime_auth_mode - .filter(|_| codex_runtime_agent_instance::is_openai_api_url(&base_url)); - let client = match runtime_auth_mode { - Some(mode) => { - let home = AbsolutePathBuf::from_absolute_path(config.codex_home()) - .map_err(|_| "Couldn't initialize local Analytics authentication.")?; - let installation_id = resolve_installation_id(&home) - .await - .map_err(|_| "Couldn't initialize local Analytics authentication.")?; - let runtime = ( - Arc::new(RuntimeAuthManager::for_codex( - Arc::clone(&auth_manager), - &base_url, - &installation_id, - )), - mode, - ); - Client::from_auth_with_runtime_without_redirects( - &base_url, - &auth, - http_client_factory, - Some(&runtime), - /*headers*/ &Default::default(), - ) - .await - .map_err(|error| { - match error.downcast_ref::() { - Some( - RuntimeAuthError::RefreshFailed - | RuntimeAuthError::RefreshTokenFailed(_) - | RuntimeAuthError::Registration(RegistrationError::Rejected { - status: http::StatusCode::UNAUTHORIZED, - .. - }), - ) => "Sign in again to load Analytics.", - _ => "Couldn't authenticate the Analytics request.", - } - })? - } - None => Client::new_without_redirects(base_url, http_client_factory) - .with_auth_provider(codex_model_provider::auth_provider_from_auth_manager( - Arc::clone(&auth_manager), - &auth, - )) - .map_err(|_| "Couldn't initialize local Analytics authentication.")?, - }; - let mut session = Self { - client, - auth_manager, - auth, - account, - }; - let accounts = session - .request(|client| async move { client.get_accounts_check().await }) - .await; - // Preserve account-switch guidance even when it interrupts account discovery. - session.ensure_identity().await?; - let accounts = accounts.map_err(|error| { - if error.is_unauthorized() { - "Sign in again to load Analytics." - } else { - "Couldn't load account plan. Press R to retry Analytics." - } - })?; - session.account.plan_type = Some( - accounts - .accounts - .into_iter() - .find(|account| account.id == session.account.id) - .and_then(|account| account.plan_type) - .ok_or("Couldn't load account plan. Press R to retry Analytics.")?, - ); - Ok(session) - } - - /// Return the account metadata captured when this session was opened. - pub fn account(&self) -> &AnalyticsAccount { - &self.account - } - /// Reject responses or cached data after a local account or user change. - pub async fn ensure_identity(&self) -> Result<(), String> { - self.auth_manager.reload().await; - let current = self.auth_manager.auth().await; - if current.is_none_or(|auth| { - auth.get_account_id() != self.auth.get_account_id() - || auth.get_chatgpt_user_id() != self.auth.get_chatgpt_user_id() - }) { - return Err("Account changed. Press R to refresh Analytics.".into()); - } - Ok(()) - } - - /// Run an account-scoped request with bounded unauthorized recovery. - pub async fn request(&self, request: impl Fn(Client) -> F) -> Result - where - F: std::future::Future>, - { - let mut recovery = self.auth_manager.unauthorized_recovery(); - loop { - self.ensure_identity() - .await - .map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?; - let result = request(self.client.clone()).await; - // Keep the original 401 when recovery fails so callers retain sign-in guidance. - if result.as_ref().is_err_and(RequestError::is_unauthorized) - && recovery.has_next() - && recovery.next().await.is_ok() - { - continue; - } - self.ensure_identity() - .await - .map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?; - return result; - } - } -} - -#[cfg(test)] -#[path = "analytics_session_tests.rs"] -mod tests; diff --git a/codex-rs/backend-client/src/analytics_session_tests.rs b/codex-rs/backend-client/src/analytics_session_tests.rs deleted file mode 100644 index 642ed727..00000000 --- a/codex-rs/backend-client/src/analytics_session_tests.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! Authentication recovery preserves actionable status without changing the account scope. - -use super::*; -use codex_http_client::OutboundProxyPolicy; -use codex_login::ExternalAuth; -use codex_login::ExternalAuthFuture; -use codex_login::ExternalAuthRefreshContext; -use codex_login::RefreshTokenError; -use codex_protocol::auth::RefreshTokenFailedError; -use codex_protocol::auth::RefreshTokenFailedReason; -use pretty_assertions::assert_eq; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; - -enum RefreshOutcome { - Accepted, - Rejected, -} - -struct ExternalCredentials { - auth: CodexAuth, - outcome: RefreshOutcome, - refreshes: AtomicUsize, -} - -impl ExternalAuth for ExternalCredentials { - fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { Ok(self.auth.clone()) }) - } - - fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { - self.refreshes.fetch_add(/*val*/ 1, Ordering::SeqCst); - match self.outcome { - RefreshOutcome::Accepted => Ok(self.auth.clone()), - RefreshOutcome::Rejected => Err(std::io::Error::other("refresh rejected")), - } - }) - } - - fn classify_error(&self, error: std::io::Error) -> RefreshTokenError { - RefreshTokenError::Permanent(RefreshTokenFailedError::new( - RefreshTokenFailedReason::Other, - error.to_string(), - )) - } -} - -#[tokio::test] -async fn failed_recovery_preserves_unauthorized_status() { - assert_unauthorized_after_recovery(RefreshOutcome::Rejected, /*expected_requests*/ 1).await; -} - -#[tokio::test] -async fn persistent_unauthorized_stops_after_successful_recovery() { - assert_unauthorized_after_recovery(RefreshOutcome::Accepted, /*expected_requests*/ 2).await; -} - -async fn assert_unauthorized_after_recovery(outcome: RefreshOutcome, expected_requests: u64) { - let auth = CodexAuth::from_external_chatgpt_tokens( - "e30.eyJleHAiOjQxMDI0NDQ4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X3VzZXJfaWQiOiJ1c2VyLWEifX0.test", "account-a", Some("plus"), - ).unwrap(); - let auth_manager = AuthManager::from_auth_for_testing(auth.clone()); - let credentials = Arc::new(ExternalCredentials { - auth: auth.clone(), - outcome, - refreshes: AtomicUsize::new(/*v*/ 0), - }); - auth_manager - .set_external_auth(credentials.clone()) - .await - .unwrap(); - let server = MockServer::start().await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(/*s*/ 401)) - .expect(expected_requests) - .mount(&server) - .await; - let client = Client::new_without_redirects( - server.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ) - .with_auth_provider(codex_model_provider::auth_provider_from_auth_manager( - Arc::clone(&auth_manager), - &auth, - )) - .unwrap(); - let session = AnalyticsSession { - account: AnalyticsAccount { - id: "account-a".into(), - email: None, - plan_type: auth.account_plan_type(), - }, - client, - auth_manager, - auth, - }; - let error = session - .request(|client| async move { - client - .get_account_analytics(crate::AnalyticsReport::Usage, "2026-09-01", "2026-09-07") - .await - }) - .await - .unwrap_err(); - assert_eq!(error.status().map(|status| status.as_u16()), Some(401)); - session.ensure_identity().await.unwrap(); - assert_eq!(credentials.refreshes.load(Ordering::SeqCst), 1); - server.verify().await; -} diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index 6dafe2e1..fb6d88e8 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -43,7 +43,6 @@ use std::fmt; use std::sync::Arc; use std::time::Duration; -pub(crate) mod analytics; mod chatgpt_turn_cost; pub(crate) mod plan_history; pub(crate) mod profile; diff --git a/codex-rs/backend-client/src/client/analytics.rs b/codex-rs/backend-client/src/client/analytics.rs deleted file mode 100644 index c4b97c29..00000000 --- a/codex-rs/backend-client/src/client/analytics.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! Authenticated account analytics reads. Attribution and missing amounts remain unmodified. - -use super::Client; -use super::PathStyle; -use super::RequestError; -use codex_backend_openapi_models::models::analytics as models; -use http::Method; - -/// The bounded set of reports used by consumer and workspace Analytics views. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum AnalyticsReport { - Usage, - EnterpriseTokens, - Credits, - WorkspaceCredits, - EnterpriseCredits { breakdown: &'static str }, - Messages, - Plugins { limit: u8 }, - Skills { limit: u8 }, -} - -/// Endpoint-specific backend contracts; normalization belongs to the consumer. -#[derive(Clone, Debug, PartialEq)] -pub enum AnalyticsResponse { - Usage(models::DailyProductSurfaceUsageResponse), - Credits(models::CreditUsageEventsResponse), - EnterpriseCredits(models::CurrentUserCreditUsageResponse), - Messages(models::DailyWorkspaceUsageCountResponse), - Plugins(models::PluginUsageMetricsResponse), - Skills(models::DailySkillUsageMetricsResponse), -} - -impl Client { - /// Fetches one report for an inclusive UTC date range supplied by the caller. - pub async fn get_account_analytics( - &self, - report: AnalyticsReport, - start_date: &str, - end_date: &str, - ) -> Result { - let route = match report { - AnalyticsReport::Usage => "usage/daily-token-usage-breakdown", - AnalyticsReport::Credits => "usage/credit-usage-events", - AnalyticsReport::WorkspaceCredits | AnalyticsReport::EnterpriseTokens => { - "usage/daily-workspace-user-token-usage-breakdown" - } - AnalyticsReport::EnterpriseCredits { .. } => "usage/daily-workspace-user-credit-usage", - AnalyticsReport::Messages => "analytics/daily-workspace-usage-counts", - AnalyticsReport::Plugins { .. } => "analytics/daily-plugin-usage-metrics", - AnalyticsReport::Skills { .. } => "analytics/daily-skill-usage-metrics", - }; - let prefix = match self.path_style { - PathStyle::CodexApi => "api/codex", - PathStyle::ChatGptApi => "wham", - }; - let mut url = url::Url::parse(&format!("{}/{prefix}/{route}", self.base_url)) - .map_err(anyhow::Error::from)?; - if report != AnalyticsReport::Credits { - url.query_pairs_mut() - .append_pair("start_date", start_date) - .append_pair("end_date", end_date); - if let AnalyticsReport::EnterpriseCredits { breakdown } = report { - url.query_pairs_mut().append_pair("breakdown", breakdown); - } else { - url.query_pairs_mut().append_pair("group_by", "day"); - } - } - if matches!( - report, - AnalyticsReport::Messages - | AnalyticsReport::Plugins { .. } - | AnalyticsReport::Skills { .. } - ) { - url.query_pairs_mut().append_pair("workspace_user", "true"); - } - match report { - AnalyticsReport::EnterpriseTokens => { - url.query_pairs_mut() - .append_pair("breakdown_by", "model") - .append_pair("modes", "codex") - .append_pair("modes", "work"); - } - AnalyticsReport::Plugins { limit } => { - url.query_pairs_mut() - .append_pair("top_plugin_limit", &limit.to_string()); - } - AnalyticsReport::Skills { limit } => { - url.query_pairs_mut() - .append_pair("top_skill_limit", &limit.to_string()); - } - AnalyticsReport::Usage - | AnalyticsReport::Credits - | AnalyticsReport::WorkspaceCredits - | AnalyticsReport::EnterpriseCredits { .. } - | AnalyticsReport::Messages => {} - } - let request = self - .request(Method::GET, url.as_str()) - .headers(self.headers().await?); - let (body, _) = self - .exec_request_detailed(request, "GET", url.as_str()) - .await?; - // Do not include an untyped billing response in errors or diagnostics. - let response = match report { - AnalyticsReport::Usage - | AnalyticsReport::EnterpriseTokens - | AnalyticsReport::WorkspaceCredits => { - serde_json::from_str(&body).map(AnalyticsResponse::Usage) - } - AnalyticsReport::Credits => serde_json::from_str(&body).map(AnalyticsResponse::Credits), - AnalyticsReport::EnterpriseCredits { .. } => { - serde_json::from_str(&body).map(AnalyticsResponse::EnterpriseCredits) - } - AnalyticsReport::Messages => { - serde_json::from_str(&body).map(AnalyticsResponse::Messages) - } - AnalyticsReport::Plugins { .. } => { - serde_json::from_str(&body).map(AnalyticsResponse::Plugins) - } - AnalyticsReport::Skills { .. } => { - serde_json::from_str(&body).map(AnalyticsResponse::Skills) - } - }; - response.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid analytics response."))) - } -} - -#[cfg(test)] -#[path = "analytics_tests.rs"] -mod tests; diff --git a/codex-rs/backend-client/src/client/analytics_tests.rs b/codex-rs/backend-client/src/client/analytics_tests.rs deleted file mode 100644 index b8650f83..00000000 --- a/codex-rs/backend-client/src/client/analytics_tests.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! HTTP contract coverage for account analytics report reads. - -use super::*; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -#[tokio::test] -async fn account_analytics_uses_personal_daily_scope_and_plugin_contract() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/api/codex/analytics/daily-plugin-usage-metrics")) - .and(query_param("start_date", "2026-01-03")) - .and(query_param("end_date", "2026-01-09")) - .and(query_param("group_by", "day")) - .and(query_param("workspace_user", "true")) - .and(query_param("top_plugin_limit", "10")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "data": [{"date": "2026-01-03", "plugin_usage_overviews": [{ - "plugin_id": null, "plugin_name": "example", "marketplace": null, - "display_name": "Example plugin", "invocation_counts": 12 - }]}] - }))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let client = Client::new( - server.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ); - let response = client - .get_account_analytics( - AnalyticsReport::Plugins { limit: 10 }, - "2026-01-03", - "2026-01-09", - ) - .await - .unwrap(); - assert_eq!( - response, - AnalyticsResponse::Plugins(models::PluginUsageMetricsResponse { - data: vec![models::PluginUsageBucket { - date: "2026-01-03".into(), - plugin_usage_overviews: vec![models::PluginUsageOverview { - plugin_id: None, - plugin_name: "example".into(), - display_name: "Example plugin".into(), - marketplace: None, - invocation_counts: 12, - }], - }], - data_freshness_ts: None, - group_by: None, - }) - ); -} - -#[tokio::test] -async fn account_analytics_preserves_signed_credit_events() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/wham/usage/credit-usage-events")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "data": [{"date": "2026-01-03", "product_surface": "cli", "credit_amount": -0.004}] - }))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let client = Client::new( - server.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ) - .with_path_style(PathStyle::ChatGptApi); - let response = client - .get_account_analytics(AnalyticsReport::Credits, "2026-01-03", "2026-01-09") - .await - .unwrap(); - assert_eq!( - response, - AnalyticsResponse::Credits(models::CreditUsageEventsResponse { - data: vec![models::CreditUsageEventBySurface { - date: "2026-01-03".into(), - product_surface: "cli".into(), - credit_amount: -0.004, - usage_id: None, - }], - }) - ); -} - -#[tokio::test] -async fn account_analytics_rejects_another_reports_shape_without_logging_the_body() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/api/codex/analytics/daily-workspace-usage-counts")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "data": [{"date": "2026-01-03", "product_surface": "sensitive-value", "credit_amount": 10}] - }))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let client = Client::new( - server.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ); - let error = client - .get_account_analytics(AnalyticsReport::Messages, "2026-01-03", "2026-01-09") - .await - .unwrap_err(); - assert_eq!(error.to_string(), "Invalid analytics response."); -} - -#[tokio::test] -async fn account_analytics_decodes_each_endpoint_and_accepts_new_string_values() { - for (report, route, body, expected) in [ - ( - AnalyticsReport::Usage, - "usage/daily-token-usage-breakdown", - json!({"data": [{"date": "2026-01-03", "product_surface_usage_values": {"future_surface": 1.0}}], "units": "future_unit"}), - AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse { - data: vec![models::DailyProductSurfaceUsage { - date: "2026-01-03".into(), - product_surface_usage_values: [("future_surface".into(), 1.0)].into(), - ..Default::default() - }], - units: Some("future_unit".into()), - ..Default::default() - }), - ), - ( - AnalyticsReport::EnterpriseCredits { breakdown: "model" }, - "usage/daily-workspace-user-credit-usage", - json!({"data": [], "series": [], "breakdown": "model"}), - AnalyticsResponse::EnterpriseCredits(models::CurrentUserCreditUsageResponse { - breakdown: "model".into(), - ..Default::default() - }), - ), - ( - AnalyticsReport::Messages, - "analytics/daily-workspace-usage-counts", - json!({"data": []}), - AnalyticsResponse::Messages(models::DailyWorkspaceUsageCountResponse::default()), - ), - ( - AnalyticsReport::Skills { limit: 10 }, - "analytics/daily-skill-usage-metrics", - json!({"data": []}), - AnalyticsResponse::Skills(models::DailySkillUsageMetricsResponse::default()), - ), - ( - AnalyticsReport::WorkspaceCredits, - "usage/daily-workspace-user-token-usage-breakdown", - json!({"data": []}), - AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()), - ), - ( - AnalyticsReport::EnterpriseTokens, - "usage/daily-workspace-user-token-usage-breakdown", - json!({"data": []}), - AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()), - ), - ] { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path(format!("/api/codex/{route}"))) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(body)) - .expect(/*r*/ 1) - .mount(&server) - .await; - let client = Client::new( - server.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ); - assert_eq!( - client - .get_account_analytics(report, "2026-01-03", "2026-01-09") - .await - .unwrap(), - expected - ); - } -} diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs index 1f836459..4b7631df 100644 --- a/codex-rs/backend-client/src/lib.rs +++ b/codex-rs/backend-client/src/lib.rs @@ -1,9 +1,6 @@ -mod analytics_session; mod client; pub(crate) mod types; -pub use analytics_session::AnalyticsAccount; -pub use analytics_session::AnalyticsSession; pub use client::AddCreditsNudgeCreditType; pub use client::ChatgptThreadTurnCosts; pub use client::ChatgptTurnCost; @@ -11,8 +8,6 @@ pub use client::Client; pub use client::RequestError; pub use client::ThreadUsage; pub use client::ThreadUsageBreakdownGroup; -pub use client::analytics::AnalyticsReport; -pub use client::analytics::AnalyticsResponse; pub use client::profile::AccountProfile; pub use client::profile::ProfileIdentity; pub use client::profile::ProfileInvocation; @@ -61,4 +56,3 @@ pub use client::task_usage::TaskUsageGroup; pub use client::task_usage::TaskUsageResponse; pub use client::task_usage::TaskUsageStatus; pub use client::task_usage::TaskUsageThread; -pub use codex_backend_openapi_models::models::analytics as analytics_models; diff --git a/codex-rs/cli/src/daemon_telemetry.rs b/codex-rs/cli/src/daemon_telemetry.rs deleted file mode 100644 index 0bc3fed7..00000000 --- a/codex-rs/cli/src/daemon_telemetry.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Foreground daemon observations use the CLI's existing consent and identity handling. -//! Detached updater entry points never call this module. - -use codex_utils_cli::CliConfigOverrides; -use std::time::Duration; -use tokio::time::timeout; - -pub(crate) async fn record_command( - overrides: &CliConfigOverrides, - analytics_default_enabled: bool, - target: &'static str, - result: &anyhow::Result>, -) { - if std::env::var_os(codex_app_server_daemon::telemetry::HANDOFF_ENV).is_some() { - return; - } - // Skip telemetry if consent-aware configuration cannot be loaded promptly. - let Ok(Ok(config)) = timeout( - Duration::from_secs(/*secs*/ 2), - crate::cloud_config::load_config(overrides, codex_config::LoaderOverrides::default()), - ) - .await - else { - return; - }; - use codex_app_server_daemon::UpdateStatus; - let outcome = match result { - Ok(Some(output)) => match output.status { - UpdateStatus::Updated => "updated", - UpdateStatus::NoUpdate => "no_update", - UpdateStatus::Unsupported => "unsupported", - }, - Ok(None) => "cancelled", - Err(_) => "unconfirmed", - }; - let Ok(Ok(Some(otel))) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - analytics_default_enabled, - ) - })) else { - return; - }; - if let Some(metrics) = otel.metrics() { - let mut tags = codex_app_server_daemon::telemetry::settings_tags(&config.codex_home) - .await - .to_vec(); - tags.extend([ - ("initiation_source", "cli"), - ("update_target", target), - ("outcome", outcome), - ]); - let _ = metrics.counter("codex.daemon.update", /*inc*/ 1, &tags); - } - let _ = otel - .shutdown_with_timeout(std::time::Duration::from_secs(/*secs*/ 2)) - .await; -} diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index dc45513a..b6012e6e 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -48,7 +48,6 @@ static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; mod config_override_args; mod daemon_install; -mod daemon_telemetry; mod doctor; #[cfg(test)] #[path = "exec_args_tests.rs"] @@ -579,23 +578,10 @@ struct AppServerCommand { #[arg(long, hide = true)] managed_daemon: bool, - /// Controls whether analytics are enabled by default. - /// - /// Analytics are disabled by default for app-server. Users have to explicitly opt in - /// via the `analytics` section in the config.toml file. - /// - /// However, for first-party use cases like the VSCode IDE extension, we default analytics - /// to be enabled by default by setting this flag. Users can still opt out by setting this - /// in their config.toml: - /// - /// ```toml - /// [analytics] - /// enabled = false - /// ``` - /// - /// See https://developers.openai.com/codex/config-advanced/#metrics for more details. - #[arg(long = "analytics-default-enabled")] - analytics_default_enabled: bool, + /// Deprecated and ignored: aKode never collects usage data. Accepted only so + /// existing launchers that still pass this legacy flag keep working. + #[arg(long = "analytics-default-enabled", hide = true)] + _legacy_usage_data_flag: bool, #[command(flatten)] auth: codex_websocket_auth::WebsocketAuthArgs, @@ -762,7 +748,6 @@ fn run_update_action( println!("Updating the local background server..."); let status = std::process::Command::new(executable) .args(source.command_args()) - .env(codex_app_server_daemon::telemetry::HANDOFF_ENV, "1") .status()?; anyhow::ensure!( status.success(), @@ -1207,8 +1192,8 @@ async fn dispatch_cli( listen, stdio, managed_daemon, - analytics_default_enabled, auth, + .. } = app_server_cli; let strict_config = app_server_strict_config || root_strict_config; reject_strict_config_for_app_server_subcommand(strict_config, subcommand.as_ref())?; @@ -1262,7 +1247,6 @@ async fn dispatch_cli( root_config_overrides, LoaderOverrides::default(), strict_config, - analytics_default_enabled, transport, codex_protocol::protocol::SessionSource::VSCode, auth, @@ -1336,13 +1320,6 @@ async fn dispatch_cli( daemon_install::confirm_install(request, yes) }) .await; - daemon_telemetry::record_command( - &root_config_overrides, - analytics_default_enabled, - "this_cli", - &result, - ) - .await; if let Some(output) = result? { println!("{}", serde_json::to_string(&output)?); } @@ -1380,13 +1357,6 @@ async fn dispatch_cli( let result = codex_app_server_daemon::update(http_client_factory) .await .map(Some); - daemon_telemetry::record_command( - &root_config_overrides, - analytics_default_enabled, - "public_stable", - &result, - ) - .await; if let Some(output) = result? { println!("{}", serde_json::to_string(&output)?); } @@ -4111,9 +4081,8 @@ enabled = true } #[test] - fn app_server_analytics_default_disabled_without_flag() { + fn app_server_defaults_to_stdio_transport() { let app_server = app_server_from_args(["codex", "app-server"].as_ref()); - assert!(!app_server.analytics_default_enabled); assert_eq!( app_server.listen, codex_app_server::AppServerTransport::Stdio @@ -4131,10 +4100,13 @@ enabled = true } #[test] - fn app_server_analytics_default_enabled_with_flag() { + fn app_server_accepts_and_ignores_legacy_usage_data_flag() { let app_server = app_server_from_args(["codex", "app-server", "--analytics-default-enabled"].as_ref()); - assert!(app_server.analytics_default_enabled); + assert_eq!( + app_server.listen, + codex_app_server::AppServerTransport::Stdio + ); } #[test] diff --git a/codex-rs/cli/src/migrate_rollouts.rs b/codex-rs/cli/src/migrate_rollouts.rs index f7f695b7..d4c0e224 100644 --- a/codex-rs/cli/src/migrate_rollouts.rs +++ b/codex-rs/cli/src/migrate_rollouts.rs @@ -56,17 +56,6 @@ pub(crate) async fn run( .cli_overrides(overrides) .build() .await?; - let otel = codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - /*default_analytics_enabled*/ true, - ) - .unwrap_or_else(|error| { - eprintln!("Could not create otel exporter: {error}"); - None - }); - codex_core::otel_init::record_process_start(otel.as_ref(), "codex_migrate_rollouts"); let mode = if command.apply { RolloutMigrationMode::Apply } else { diff --git a/codex-rs/cli/tests/daemon_startup.rs b/codex-rs/cli/tests/daemon_startup.rs index aadb8248..a3b8aa21 100644 --- a/codex-rs/cli/tests/daemon_startup.rs +++ b/codex-rs/cli/tests/daemon_startup.rs @@ -182,7 +182,7 @@ async fn daemon_startup(command: &str) -> Result<()> { format!( "model = \"gpt-5.6-terra\"\n\ cli_auth_credentials_store = \"file\"\n\ - suppress_unstable_features_warning = true\nanalytics.enabled = false\n\ + suppress_unstable_features_warning = true\n\ windows.sandbox = \"unelevated\"\n\ tui.disable_paste_burst = true\n\ {}\n\ diff --git a/codex-rs/cli/tests/daemon_telemetry.rs b/codex-rs/cli/tests/daemon_telemetry.rs deleted file mode 100644 index 1d34cefe..00000000 --- a/codex-rs/cli/tests/daemon_telemetry.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Foreground updates honor explicit metrics exporters and never claim unconfirmed installation. - -use anyhow::Context as _; -use pretty_assertions::assert_eq; -use serde_json::Value; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; - -#[tokio::test] -async fn foreground_update_honors_metrics_exporter_and_reports_unconfirmed() -> anyhow::Result<()> { - for (analytics_config, analytics_default_enabled, metrics_enabled) in [ - ("", false, true), - ("", true, true), - ("analytics.enabled = true\n", false, true), - ("analytics.enabled = false\n", true, true), - ("analytics.enabled = true\n", true, false), - ] { - let codex = codex_utils_cargo_bin::cargo_bin("codex")?; - let server = MockServer::start().await; - Mock::given(wiremock::matchers::path("/metrics")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - let home = tempfile::tempdir()?; - std::fs::write( - home.path().join("config.toml"), - format!( - "cli_auth_credentials_store = \"file\"\n{analytics_config}[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{}/metrics\", protocol = \"json\" }} }}\n", - server.uri(), - ), - )?; - // No managed installation exists, so the command cannot confirm an applied update. - let mut command = tokio::process::Command::new(&codex); - command - .current_dir(home.path()) - .env("CODEX_HOME", home.path()) - .env_remove(codex_app_server_daemon::telemetry::HANDOFF_ENV) - .arg("app-server"); - if analytics_default_enabled { - command.arg("--analytics-default-enabled"); - } - if !metrics_enabled { - command.args(["-c", "otel.metrics_exporter=\"none\""]); - } - let output = command - .args(["daemon", "update", "--from-cli", "--yes"]) - .output() - .await?; - assert!(!output.status.success()); - let requests = server - .received_requests() - .await - .context("metric requests")?; - assert_eq!(requests.len(), usize::from(metrics_enabled)); - if !metrics_enabled { - continue; - } - let body: Value = serde_json::from_slice(&requests[0].body)?; - let metric = body["resourceMetrics"] - .as_array() - .into_iter() - .flatten() - .flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten()) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .find(|metric| metric["name"] == "codex.daemon.update") - .context("daemon update metric")?; - assert!( - metric["sum"]["dataPoints"][0]["attributes"] - .as_array() - .context("metric attributes")? - .iter() - .any(|tag| tag["key"] == "outcome" && tag["value"]["stringValue"] == "unconfirmed") - ); - } - Ok(()) -} diff --git a/codex-rs/cli/tests/doctor_path_safety.rs b/codex-rs/cli/tests/doctor_path_safety.rs index a91de8b9..63de7dee 100644 --- a/codex-rs/cli/tests/doctor_path_safety.rs +++ b/codex-rs/cli/tests/doctor_path_safety.rs @@ -73,8 +73,6 @@ impl Fixture { cli_auth_credentials_store = "file" check_for_update_on_startup = false model_provider = "local" -[analytics] -enabled = false [model_providers.local] name = "local test" base_url = "http://127.0.0.1:9/v1" @@ -621,7 +619,7 @@ async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> { let fixture = Fixture::new()?; let proxy = TcpListener::bind("127.0.0.1:0").await?; let proxy_uri = format!("http://{}", proxy.local_addr()?); - // Reject all outbound traffic locally, including the final feedback upload. + // Reject all outbound traffic locally; feedback collection must not need the network. let proxy_task = tokio::spawn(async move { while let Ok((stream, _)) = proxy.accept().await { let mut stream = BufReader::new(stream); @@ -664,20 +662,24 @@ async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> { ]) .build_initialized_with_timeout(Duration::from_secs(/*secs*/ 30)) .await?; + // Feedback is only ever saved locally; collecting its diagnostics must not run PATH helpers. + let save_path = fixture.root.path().join("feedback.zip"); let request_id = app_server .send_raw_request( - "feedback/upload", + "feedback/save", Some(json!({ - "classification": "bug", "includeLogs": true + "classification": "bug", + "includeLogs": true, + "savePath": save_path.to_string_lossy(), })), ) .await?; - let error = timeout( + timeout( Duration::from_secs(/*secs*/ 45), - app_server.read_stream_until_error_message(RequestId::Integer(request_id)), + app_server.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; - assert!(error.error.message.contains("failed to upload feedback")); + assert!(save_path.exists(), "feedback must be saved locally"); assert!(!fixture.marker.exists(), "feedback executed a PATH helper"); timeout( Duration::from_secs(/*secs*/ 10), diff --git a/codex-rs/cli/tests/exec_server.rs b/codex-rs/cli/tests/exec_server.rs index 8469b2ff..e24b8f44 100644 --- a/codex-rs/cli/tests/exec_server.rs +++ b/codex-rs/cli/tests/exec_server.rs @@ -45,7 +45,6 @@ use predicates::str::contains; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::io::AsyncBufReadExt; -use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::net::TcpListener; @@ -457,12 +456,6 @@ async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Resul const EXECUTOR_REGISTRATION_ID: &str = "registration-parent-lifetime"; const TEST_TIMEOUT: Duration = Duration::from_secs(30); - let collector = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/v1/metrics")) - .respond_with(ResponseTemplate::new(202)) - .mount(&collector) - .await; let listener = TcpListener::bind("127.0.0.1:0").await?; let rendezvous_url = format!("ws://{}", listener.local_addr()?); let registry = MockServer::start().await; @@ -489,21 +482,9 @@ async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Resul .await; let codex_home = TempDir::new()?; - let collector_url = collector.uri(); std::fs::write( codex_home.path().join("config.toml"), - format!( - r#" -cli_auth_credentials_store = "file" - -[analytics] -enabled = true - -[otel] -environment = "test" -metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_url}/v1/metrics", protocol = "json" }} }} -"# - ), + "cli_auth_credentials_store = \"file\"\n", )?; let package = TempDir::new()?; let bin_dir = package.path().join("bin"); @@ -685,29 +666,6 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_url}/v1/metrics", pr relay_task.abort(); let _ = relay_task.await; - let requests = collector - .received_requests() - .await - .ok_or_else(|| anyhow::anyhow!("failed to read OTLP collector requests"))?; - let metrics = requests - .iter() - .filter(|request| request.url.path() == "/v1/metrics") - .map(|request| serde_json::from_slice::(&request.body)) - .collect::>>()?; - assert_metric_point(&metrics, "exec_server_processes_active", &[], Some(0)); - assert_metric_point( - &metrics, - "exec_server_processes_finished_total", - &[("result", "terminated")], - Some(1), - ); - assert_metric_point( - &metrics, - "exec_server_requests_total", - &[("method", "process/start"), ("result", "success")], - Some(1), - ); - Ok(()) } @@ -804,8 +762,6 @@ async fn remote_exec_server_scoped_credentials_authenticate_only_register_and_va home.path().join("config.toml"), format!( r#" -[analytics] -enabled = true [otel] metrics_exporter = {{ otlp-http = {{ endpoint = "{}/v1/metrics", protocol = "json", headers = {{ Authorization = "general-telemetry-token" }} }} }} "#, @@ -1087,155 +1043,6 @@ async fn proxy_parent_lifetime_relay( Ok(()) } -#[tokio::test] -async fn local_exec_server_flushes_telemetry_on_stdio_disconnect() -> Result<()> { - let collector = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/v1/metrics")) - .respond_with(ResponseTemplate::new(202)) - .mount(&collector) - .await; - let codex_home = TempDir::new()?; - let base_url = collector.uri(); - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -[analytics] -enabled = true - -[otel] -environment = "test" -metrics_exporter = {{ otlp-http = {{ endpoint = "{base_url}/v1/metrics", protocol = "json" }} }} -"# - ), - )?; - - let cwd = url::Url::from_directory_path(std::env::current_dir()?) - .map_err(|()| anyhow::anyhow!("could not convert cwd to file URL"))?; - #[cfg(windows)] - let argv = vec!["ping.exe", "-n", "61", "127.0.0.1"]; - #[cfg(not(windows))] - let argv = vec!["/bin/sleep", "60"]; - let codex_bin = codex_utils_cargo_bin::cargo_bin("codex")?; - let codex_home = codex_home.path().to_path_buf(); - let subprocess = async move { - let mut command = tokio::process::Command::new(codex_bin); - command - .env("CODEX_HOME", codex_home) - .env("NO_PROXY", "127.0.0.1,localhost") - .env("no_proxy", "127.0.0.1,localhost") - .args(["exec-server", "--listen", "stdio"]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .kill_on_drop(true); - let mut child = command.spawn()?; - let mut stdin = child - .stdin - .take() - .ok_or_else(|| anyhow::anyhow!("exec-server stdin was not piped"))?; - let stdout = child - .stdout - .take() - .ok_or_else(|| anyhow::anyhow!("exec-server stdout was not piped"))?; - let mut stdout = BufReader::new(stdout); - send_json_line( - &mut stdin, - &serde_json::json!({ - "id": 1, - "method": "initialize", - "params": {"clientName": "otel-test", "resumeSessionId": null} - }), - ) - .await?; - wait_for_response(&mut stdout, /*expected_id*/ 1).await?; - send_json_line( - &mut stdin, - &serde_json::json!({"method": "initialized", "params": {}}), - ) - .await?; - send_json_line( - &mut stdin, - &serde_json::json!({ - "id": 2, - "method": "process/start", - "params": { - "processId": "otel-process", - "argv": argv, - "cwd": cwd, - "env": {}, - "tty": false, - "pipeStdin": false, - "arg0": null - } - }), - ) - .await?; - wait_for_response(&mut stdout, /*expected_id*/ 2).await?; - drop(stdin); - let mut remaining_stdout = String::new(); - stdout.read_to_string(&mut remaining_stdout).await?; - let status = child.wait().await?; - anyhow::ensure!( - status.success(), - "exec-server exited with {status}; remaining stdout: {remaining_stdout}" - ); - Ok::<(), anyhow::Error>(()) - }; - let subprocess_result = tokio::time::timeout(Duration::from_secs(30), subprocess) - .await - .map_err(|_| anyhow::anyhow!("exec-server subprocess timed out"))?; - subprocess_result?; - - let requests = collector - .received_requests() - .await - .ok_or_else(|| anyhow::anyhow!("failed to read OTLP collector requests"))?; - let metrics = requests - .iter() - .filter(|request| request.url.path() == "/v1/metrics") - .map(|request| serde_json::from_slice::(&request.body)) - .collect::>>()?; - assert_metric_point( - &metrics, - "exec_server_connections_active", - &[("transport", "stdio")], - Some(0), - ); - assert_metric_point( - &metrics, - "exec_server_connections_total", - &[("transport", "stdio")], - Some(1), - ); - assert_metric_point( - &metrics, - "exec_server_requests_total", - &[("method", "process/start"), ("result", "success")], - Some(1), - ); - assert_metric_point(&metrics, "exec_server_processes_active", &[], Some(0)); - assert_metric_point( - &metrics, - "exec_server_processes_finished_total", - &[("result", "terminated")], - Some(1), - ); - assert_metric_point( - &metrics, - "exec_server_request_duration_seconds", - &[("method", "process/start"), ("result", "success")], - /*value*/ None, - ); - assert_metric_point( - &metrics, - "exec_server_process_duration_seconds", - &[("result", "terminated")], - /*value*/ None, - ); - Ok(()) -} - async fn send_json_line( stdin: &mut (impl tokio::io::AsyncWrite + Unpin), message: &serde_json::Value, @@ -1314,45 +1121,3 @@ async fn wait_for_response( } } } - -fn assert_metric_point( - payloads: &[serde_json::Value], - name: &str, - attributes: &[(&str, &str)], - value: Option, -) { - let found = payloads - .iter() - .flat_map(|payload| payload["resourceMetrics"].as_array().into_iter().flatten()) - .flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten()) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .filter(|metric| metric["name"].as_str() == Some(name)) - .flat_map(|metric| { - ["gauge", "sum", "histogram"] - .into_iter() - .find_map(|kind| metric[kind]["dataPoints"].as_array()) - .into_iter() - .flatten() - }) - .any(|point| { - let actual_attributes = point["attributes"] - .as_array() - .map(Vec::as_slice) - .unwrap_or_default(); - let attributes_match = actual_attributes.len() == attributes.len() - && attributes.iter().all(|(expected_key, expected_value)| { - actual_attributes.iter().any(|actual| { - actual["key"].as_str() == Some(*expected_key) - && actual["value"]["stringValue"].as_str() == Some(*expected_value) - }) - }); - let actual_value = point["asInt"] - .as_i64() - .or_else(|| point["asInt"].as_str()?.parse().ok()); - attributes_match && value.is_none_or(|expected| actual_value == Some(expected)) - }); - assert!( - found, - "metric {name} with attributes {attributes:?} and value {value:?} missing" - ); -} diff --git a/codex-rs/cli/tests/queue.rs b/codex-rs/cli/tests/queue.rs index 23c241ff..340a16a9 100644 --- a/codex-rs/cli/tests/queue.rs +++ b/codex-rs/cli/tests/queue.rs @@ -194,7 +194,7 @@ fn queue_rejects_unsupported_options() -> Result<()> { "`--dangerously-bypass-hook-trust`", ), ( - "-c model=other queue -c analytics.enabled=false", + "-c model=other queue -c check_for_update_on_startup=false", "`model` config override", ), ("queue -s read-only", "`--sandbox`"), @@ -307,7 +307,7 @@ async fn remote_session_commands_with_workload_identity_use_server_auth() -> Res .mount_as_scoped(&model) .await; MockResponsesConfig::new(&model.uri()) - .with_root_config("features.plugins = false\nanalytics.enabled = false") + .with_root_config("features.plugins = false") .with_provider_config("env_key = \"CODEX_QUEUE_SERVER_API_KEY\"") .write(codex_home.path())?; let _server = TestAppServer::builder() @@ -685,7 +685,7 @@ async fn queue_rejects_overrides_that_bypass_local_daemon() -> Result<()> { "-C", ".", "-c", - "analytics.enabled=false", + "check_for_update_on_startup=false", "--thread", THREAD_ID, "--message", diff --git a/codex-rs/cli/tests/worktree.rs b/codex-rs/cli/tests/worktree.rs index 13b69149..5c1144d8 100644 --- a/codex-rs/cli/tests/worktree.rs +++ b/codex-rs/cli/tests/worktree.rs @@ -9,7 +9,6 @@ use std::io::Write as _; use std::path::Path; use std::process::Command; use std::time::Duration; -use std::time::Instant; #[cfg(not(unix))] use tempfile::TempDir; use wiremock::Mock; @@ -176,7 +175,7 @@ async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> { fs::create_dir(source.join(".codex"))?; fs::write( source.join(".codex/config.toml"), - "model = \"destination-model\"\nanalytics.enabled = false\ncli_auth_credentials_store = \"file\"\n", + "model = \"destination-model\"\ncli_auth_credentials_store = \"file\"\n", )?; git(&source, &["init", "--quiet"])?; git(&source, &["add", "."])?; @@ -190,7 +189,6 @@ async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> { r#" cli_auth_credentials_store = "file" chatgpt_base_url = "{}/source/backend-api" -analytics.enabled = false check_for_update_on_startup = false features.daemon_auto_start = {} features.mcp_oauth_refresh_coordination = true @@ -223,7 +221,7 @@ trust_level = "trusted" )?; fs::write( source.join(".codex/config.toml"), - "model = \"source-model\"\nanalytics.enabled = true\n", + "model = \"source-model\"\n", )?; app_test_support::write_chatgpt_auth( &home, @@ -253,11 +251,6 @@ trust_level = "trusted" env.insert("no_proxy".into(), "127.0.0.1,localhost".into()); env.insert("TERM".into(), "xterm-256color".into()); env.insert("TERM_PROGRAM".into(), "unrecognized-terminal".into()); - env.insert("OTEL_METRIC_EXPORT_INTERVAL".into(), "100".into()); - env.insert( - "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE".into(), - "delta".into(), - ); for key in [ "CODEX_EXEC_SERVER_URL", "CODEX_ACCESS_TOKEN", @@ -313,12 +306,11 @@ trust_level = "trusted" let mut owner = None; let mut previous: Vec = Vec::new(); let prompt = "describe checkout"; - for (fork, explicit_cd, analytics, auth_failure) in [ - (false, false, false, false), - (true, false, false, false), - (true, true, false, false), - (false, false, true, false), - (false, false, false, true), + for (fork, explicit_cd, auth_failure) in [ + (false, false, false), + (true, false, false), + (true, true, false), + (false, false, true), ] { if auth_failure { fs::write( @@ -337,12 +329,8 @@ trust_level = "trusted" )?; fs::write(source.join(".codex/config.toml"), "")?; } - let (metric_tx, mut metric_rx) = tokio::sync::mpsc::unbounded_channel(); Mock::given(wiremock::matchers::path("/metrics")) - .respond_with(move |request: &wiremock::Request| { - let _ = metric_tx.send(request.body.clone()); - ResponseTemplate::new(200).set_body_json(serde_json::json!({})) - }) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({}))) .mount(&server) .await; Mock::given(wiremock::matchers::method("GET")) @@ -410,18 +398,6 @@ trust_level = "trusted" if explicit_cd { args.extend(["--cd".into(), source.join(".codex").display().to_string()]); } - if analytics { - args.extend([ - "-c".into(), - // An explicit collector is independent of built-in analytics consent. - "analytics.enabled=false".into(), - "-c".into(), - format!( - "otel.metrics_exporter={{otlp-http={{endpoint=\"{}/metrics\",protocol=\"json\"}}}}", - server.uri() - ), - ]); - } args.push(prompt.into()); if previous.is_empty() { let mut untrusted_args = args.clone(); @@ -536,7 +512,7 @@ trust_level = "trusted" } else { Ok(()) }; - if backend == "daemon" && !analytics && matches!(observed, Ok(Ok(_))) { + if backend == "daemon" && matches!(observed, Ok(Ok(_))) { session.writer_sender().send(b"/status\r".to_vec()).await?; tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async { while !output.contains("Local background server") { @@ -555,46 +531,6 @@ trust_level = "trusted" .await .with_context(|| format!("daemon status timed out: {output}"))??; } - if analytics { - for reason in ["turn_start", "resize"] { - let started = Instant::now(); - let wait = if reason == "resize" { - session.resize(codex_utils_pty::TerminalSize { - rows: 80, - cols: 240, - })?; - Duration::from_secs(/*secs*/ 30) - } else { - Duration::from_secs(/*secs*/ 10) - }; - tokio::time::timeout(wait, async { - loop { - tokio::select! { - body = metric_rx.recv() => { - let payload: Value = serde_json::from_slice(&body.context("metric body")?)?; - let found = payload["resourceMetrics"].as_array().into_iter().flatten() - .flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten()) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .filter(|metric| metric["name"] == "codex.tui.terminal_size") - .flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten()) - .any(|point| point["attributes"].as_array().into_iter().flatten().any(|attribute| - attribute["key"] == "observation_reason" && attribute["value"]["stringValue"] == reason)); - if found { return Ok::<_, anyhow::Error>(()); } - } - bytes = stdout.recv() => { - let bytes = bytes.context("TUI exited before size observation")?; - output.push_str(&String::from_utf8_lossy(&bytes)); - let replies = queries.feed(&bytes); - if !replies.is_empty() { session.writer_sender().send(replies).await?; } - } - } - } - }).await.with_context(|| format!("waiting for {reason} observation"))??; - if reason == "resize" { - assert!(started.elapsed() >= Duration::from_secs(/*secs*/ 15)); - } - } - } let startup_result = observed.as_ref().map(|result| result.as_ref().map(|_| ())); assert!( !output.contains("Under-development features enabled:"), @@ -656,110 +592,7 @@ trust_level = "trusted" .filter(|request| request.url.path() == "/metrics") .map(|request| serde_json::from_slice::(&request.body)) .collect::>>()?; - if analytics { - let exported = metrics - .iter() - .flat_map(|payload| payload["resourceMetrics"].as_array().into_iter().flatten()) - .flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten()) - .flat_map(|scope| scope["metrics"].as_array().into_iter().flatten()) - .collect::>(); - if backend == "embedded" { - let update = exported - .iter() - .find(|metric| metric["name"] == "codex.daemon.update") - .context("handoff metric")?; - let update_point = &update["sum"]["dataPoints"][0]; - assert_eq!(update_point["asInt"], 1); - } - let point = exported - .iter() - .filter(|metric| metric["name"] == "codex.tui.start") - .flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten()) - .next() - .context("codex.tui.start data point")?; - assert_eq!(point["asInt"], 1); - let tags = point["attributes"] - .as_array() - .context("codex.tui.start attributes")? - .iter() - .map(|attribute| { - Ok(( - attribute["key"].as_str().context("metric tag key")?, - attribute["value"]["stringValue"] - .as_str() - .context("metric tag value")?, - )) - }) - .collect::>>()?; - let mut expected_tags = HashMap::from([ - ("app_server_mode", "in_process"), - ("terminal_name", "unknown"), - ("terminal_columns", "120-239"), - ("terminal_rows", "40-79"), - ("multiplexer", "none"), - ("daemon_selection_reason", "incompatible_option"), - ( - "daemon_auto_start", - if backend == "daemon" { - "enabled" - } else { - "disabled" - }, - ), - ("auto_update", "enabled"), - ("auto_update_setting", "default"), - ("update_interval_setting", "default"), - ("shutdown_grace_setting", "default"), - ]); - #[cfg(windows)] - if codex_app_server_daemon::is_elevated()? { - expected_tags.insert("daemon_selection_reason", "elevated_windows"); - } - if backend == "daemon" { - expected_tags.extend([ - ("auto_update", "disabled"), - ("auto_update_setting", "configured"), - ("shutdown_grace_setting", "configured"), - ]); - } - assert_eq!(tags, expected_tags); - let observations = exported - .iter() - .filter(|metric| metric["name"] == "codex.tui.terminal_size") - .flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten()) - .collect::>(); - assert_eq!(observations.len(), 2); - for observation in observations { - assert_eq!(observation["asInt"], 1); - let observation_tags = observation["attributes"] - .as_array() - .context("observation attributes")? - .iter() - .map(|attribute| { - Ok(( - attribute["key"].as_str().context("observation key")?, - attribute["value"]["stringValue"] - .as_str() - .context("observation value")?, - )) - }) - .collect::>>()?; - let reason = observation_tags["observation_reason"]; - let mut expected = expected_tags.clone(); - expected.insert("observation_reason", reason); - match reason { - "turn_start" => {} - "resize" => { - expected.insert("terminal_columns", "240-479"); - expected.insert("terminal_rows", "80-119"); - } - other => anyhow::bail!("unexpected observation: {other}"), - } - assert_eq!(observation_tags, expected); - } - } else { - assert!(metrics.is_empty(), "metrics exporter disabled"); - } + assert!(metrics.is_empty(), "no telemetry may be exported"); let (body, checkout, metadata) = observed .with_context(|| { format!( diff --git a/codex-rs/code-mode-host/Cargo.toml b/codex-rs/code-mode-host/Cargo.toml index 7668df11..6e544962 100644 --- a/codex-rs/code-mode-host/Cargo.toml +++ b/codex-rs/code-mode-host/Cargo.toml @@ -24,7 +24,6 @@ clap = { workspace = true, features = ["derive"] } codex-code-mode-protocol = { workspace = true } codex-code-mode-runtime = { workspace = true } codex-otel = { workspace = true } -codex-otel-trace-websocket = { workspace = true } codex-protocol = { workspace = true } futures = { workspace = true } prost = "0.14.3" diff --git a/codex-rs/code-mode-host/src/main.rs b/codex-rs/code-mode-host/src/main.rs index 8f823c66..b9975e8a 100644 --- a/codex-rs/code-mode-host/src/main.rs +++ b/codex-rs/code-mode-host/src/main.rs @@ -1,28 +1,11 @@ -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::PathBuf; -use std::time::Duration; - -use anyhow::Context; use clap::Parser; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; -use codex_otel_trace_websocket::TraceWebSocket; use tracing_subscriber::Layer; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; -const OTEL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5); - #[derive(Debug, Parser)] struct Cli { - #[arg( - long, - hide = true, - conflicts_with_all = ["listen", "otel_trace_listen", "otel_trace_exporter"] - )] + #[arg(long, hide = true, conflicts_with_all = ["listen"])] codex_ui_plugin_process: bool, /// Transport endpoint: `stdio`, `stdio://`, `grpc+stdio://`, or `grpc://IP:PORT`. @@ -32,32 +15,11 @@ struct Cli { default_value = codex_code_mode_host::DEFAULT_LISTEN_URL )] listen: String, - - /// Optional WebSocket endpoint that streams only raw OTLP trace batches. - #[arg(long, value_name = "URL")] - otel_trace_listen: Option, - - /// Optional OTLP/HTTP JSON trace exporter endpoint, analogous to - /// `otel.trace_exporter` in app-server configuration. - #[arg(long, value_name = "URL", conflicts_with = "otel_trace_listen")] - otel_trace_exporter: Option, } #[tokio::main(flavor = "current_thread")] async fn run(cli: Cli) -> anyhow::Result<()> { - let mut trace_transport = if let Some(trace_listen) = cli.otel_trace_listen.as_deref() { - Some(TraceWebSocket::start(trace_listen).await?) - } else { - None - }; - let trace_exporter_endpoint = trace_transport - .as_ref() - .map(TraceWebSocket::exporter_endpoint) - .or(cli.otel_trace_exporter.as_deref()); - let otel = trace_exporter_endpoint - .map(build_trace_provider) - .transpose()?; - let otel_layer = otel.as_ref().and_then(OtelProvider::tracing_layer); + // Logs stay local: they are written to stderr only. tracing_subscriber::registry() .with( tracing_subscriber::fmt::layer() @@ -65,33 +27,8 @@ async fn run(cli: Cli) -> anyhow::Result<()> { .with_ansi(false) .with_filter(tracing_subscriber::filter::LevelFilter::INFO), ) - .with(otel_layer) .init(); - if let Some(trace_transport) = trace_transport.as_ref() { - let listen_addr = trace_transport.listen_addr(); - tracing::info!("codex-code-mode-host OTEL trace websocket listening on ws://{listen_addr}"); - } - tracing::info_span!( - "code_mode_host.startup", - otel.name = "code_mode_host.startup" - ) - .in_scope(|| {}); - - let main_transport = codex_code_mode_host::run_main(&cli.listen); - let result = match trace_transport.as_mut() { - Some(trace_transport) => tokio::select! { - result = main_transport => result, - result = trace_transport.wait_for_failure() => result, - }, - None => main_transport.await, - }; - if let Some(otel) = otel - && let Err(error) = otel.shutdown_with_timeout(OTEL_SHUTDOWN_TIMEOUT).await - { - tracing::warn!(%error, "failed to finish code-mode host telemetry shutdown"); - } - drop(trace_transport); - result + codex_code_mode_host::run_main(&cli.listen).await } fn main() -> anyhow::Result<()> { @@ -101,28 +38,3 @@ fn main() -> anyhow::Result<()> { } run(cli) } - -fn build_trace_provider(endpoint: &str) -> anyhow::Result { - OtelProvider::try_new(&OtelSettings { - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: "code-mode-host".to_string(), - service_name: "codex-code-mode-host".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("/tmp"), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: endpoint.to_string(), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .map_err(|error| anyhow::anyhow!("failed to build code-mode host OTEL provider: {error}"))? - .context("code-mode host OTEL trace provider was unexpectedly disabled") -} diff --git a/codex-rs/codex-backend-openapi-models/src/models/analytics.rs b/codex-rs/codex-backend-openapi-models/src/models/analytics.rs deleted file mode 100644 index 3962a885..00000000 --- a/codex-rs/codex-backend-openapi-models/src/models/analytics.rs +++ /dev/null @@ -1,230 +0,0 @@ -// Generated by scripts/generate_analytics_models.py; do not edit. -// Selected backend schema SHA-256: 8dad4dcab85a89fd8091236929727587118dcaad334e10148ae8cf95dd640cc8 -// String enums remain open for forward compatibility. - -use serde::Deserialize; -use serde::Serialize; - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ActiveUsersSummary { - pub total_users: i64, - pub clients: Vec, - pub models: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ClientActiveUsersCount { - pub client_id: String, - pub users: i64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ClientWorkspaceUsageCount { - pub client_id: String, - pub users: i64, - pub threads: i64, - pub turns: i64, - pub credits: f64, - pub cost_usd: Option, - pub on_demand_credits: Option, - pub uncached_text_input_tokens: Option, - pub cached_text_input_tokens: Option, - pub text_output_tokens: Option, - pub text_total_tokens: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ConsumptionUsageGroup { - pub dimensions: std::collections::BTreeMap, - pub is_other: Option, - pub credits: f64, - pub on_demand_credits: Option, - pub uncached_text_input_tokens: Option, - pub cached_text_input_tokens: Option, - pub text_output_tokens: Option, - pub text_total_tokens: Option, - pub total_tokens: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct CreditUsageEventBySurface { - pub date: String, - pub product_surface: String, - pub credit_amount: f64, - pub usage_id: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct CreditUsageEventsResponse { - pub data: Vec, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct CurrentUserCreditUsageDatum { - pub date: String, - pub values: std::collections::BTreeMap, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct CurrentUserCreditUsageResponse { - pub breakdown: String, - pub data: Vec, - pub series: Vec, - pub unit: Option, - pub data_freshness_ts: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct CurrentUserCreditUsageSeries { - pub key: String, - pub label: String, - pub total: f64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailyProductSurfaceUsage { - pub attribution: Option>, - pub date: String, - pub product_surface_usage_values: std::collections::BTreeMap, - pub premium_usage_values: Option, - pub models: Option>, - pub groups: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailyProductSurfaceUsageResponse { - pub data: Vec, - pub units: Option, - pub data_freshness_ts: Option, - pub group_by: Option, - pub breakdown_by: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailySkillUsageMetricsResponse { - pub data: Vec, - pub data_freshness_ts: Option, - pub group_by: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailySkillUsageOverview { - pub date: String, - pub skill_usage_overviews: Vec, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailyWorkspaceUsageCount { - pub date: String, - pub totals: WorkspaceUsageCount, - pub clients: Vec, - pub models: Option>, - pub groups: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct DailyWorkspaceUsageCountResponse { - pub data: Vec, - pub balance_unit: Option, - pub active_users_summary: Option, - pub group_by: Option, - pub breakdown_by: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ModelActivitySummary { - pub model: String, - pub users: i64, - pub threads: i64, - pub turns: i64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ModelUsage { - pub model: String, - pub speed: Option, - pub credits: f64, - pub cost_usd: Option, - pub users: Option, - pub threads: Option, - pub turns: Option, - pub on_demand_credits: Option, - pub uncached_text_input_tokens: Option, - pub cached_text_input_tokens: Option, - pub text_output_tokens: Option, - pub text_total_tokens: Option, - pub total_tokens: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct PersonalUsageAttribution { - pub thread_source: String, - pub turn_trigger: String, - pub model: String, - pub surface: String, - pub value: f64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct PluginUsageBucket { - pub date: String, - pub plugin_usage_overviews: Vec, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct PluginUsageMetricsResponse { - pub data: Vec, - pub data_freshness_ts: Option, - pub group_by: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct PluginUsageOverview { - pub plugin_id: Option, - pub plugin_name: String, - pub display_name: String, - pub marketplace: Option, - pub invocation_counts: i64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ProductSurfacePremiumUsageValues { - pub total_usage_credits: std::collections::BTreeMap, - pub credit_usage_credits: std::collections::BTreeMap, - pub uncached_text_input_tokens_by_surface: std::collections::BTreeMap, - pub cached_text_input_tokens_by_surface: std::collections::BTreeMap, - pub text_output_tokens_by_surface: std::collections::BTreeMap, - pub text_total_tokens_by_surface: std::collections::BTreeMap, - pub total_tokens_by_surface: Option>, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct SkillUsageOverview { - pub skill_name: String, - pub display_name: String, - pub skill_ids: Vec, - pub invocation_counts: i64, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct WorkspaceUsageCount { - pub users: i64, - pub threads: i64, - pub turns: i64, - pub credits: f64, - pub cost_usd: Option, - pub on_demand_credits: Option, - pub uncached_text_input_tokens: Option, - pub cached_text_input_tokens: Option, - pub text_output_tokens: Option, - pub text_total_tokens: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct WorkspaceUsageGroup { - pub dimensions: std::collections::BTreeMap, - pub is_other: Option, - pub users: i64, - pub turns: i64, - pub cost_usd: Option, -} diff --git a/codex-rs/codex-backend-openapi-models/src/models/mod.rs b/codex-rs/codex-backend-openapi-models/src/models/mod.rs index 789a5f64..b154a044 100644 --- a/codex-rs/codex-backend-openapi-models/src/models/mod.rs +++ b/codex-rs/codex-backend-openapi-models/src/models/mod.rs @@ -1,4 +1,3 @@ -pub mod analytics; // Curated minimal export list for current workspace usage. // NOTE: This file was previously auto-generated by the OpenAPI generator. // Currently export only the types referenced by the workspace diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index ff8f5bd6..4fba1a47 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -43,7 +43,6 @@ use crate::permissions_toml::PermissionProfileToml; use crate::types::AuthCredentialsStoreMode; use crate::types::FeedbackConfigToml; use crate::types::OtelConfigToml; -use crate::types::OtelExporterKind; use crate::types::WindowsSandboxModeToml; #[derive(Debug, Clone, PartialEq, Eq)] @@ -1002,7 +1001,8 @@ impl FeatureRequirementsToml { #[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct AppToolRequirementToml { pub approval_mode: Option, - /// Opt-in analytics extraction for this exact tool, not a tool argument. + /// Deprecated and ignored: tool-result metadata is never captured. Accepted only so + /// existing managed requirements keep parsing. /// The highest-priority rule wins as a whole, including unsupported formats. pub analytics_result_source: Option, } @@ -1186,24 +1186,84 @@ pub struct ConfigRequirementsToml { pub guardian_extra_policy: Option, } -/// OTEL settings that may be managed through `requirements.toml`. +/// Local logging settings that may be managed through `requirements.toml`. /// /// Tool-result limits are optional here because `config.toml` defaults them, /// while requirements must distinguish unset from managed-to-default. +/// +/// aKode never exports telemetry: the former exporter keys are still accepted +/// so existing managed requirements keep parsing, but their values are ignored. #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)] #[serde(deny_unknown_fields)] pub struct OtelRequirementsToml { pub tool_result: Option, pub log_sse_deltas: Option, pub log_user_prompt: Option, - pub log_agent_responses: Option, - pub log_guardian_assessments: Option, - pub environment: Option, - pub exporter: Option, - pub trace_exporter: Option, - pub metrics_exporter: Option, - pub span_attributes: Option>, - pub tracestate: Option>>, + /// Deprecated and ignored. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub log_agent_responses: Option, + /// Deprecated and ignored. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub log_guardian_assessments: Option, + /// Deprecated and ignored. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub environment: Option, + /// Deprecated and ignored: telemetry exporters were removed. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub exporter: Option, + /// Deprecated and ignored: telemetry exporters were removed. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub trace_exporter: Option, + /// Deprecated and ignored: telemetry exporters were removed. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub metrics_exporter: Option, + /// Deprecated and ignored. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub span_attributes: Option, + /// Deprecated and ignored. + #[serde( + default, + skip_serializing, + deserialize_with = "discard_legacy_otel_key" + )] + pub tracestate: Option, +} + +/// Accepts a deprecated `[otel]` requirement key and discards its value. +fn discard_legacy_otel_key<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + serde::de::IgnoredAny::deserialize(deserializer)?; + Ok(None) } impl OtelRequirementsToml { @@ -1211,23 +1271,6 @@ impl OtelRequirementsToml { self.tool_result.is_none() && self.log_sse_deltas.is_none() && self.log_user_prompt.is_none() - && self.log_agent_responses.is_none() - && self.log_guardian_assessments.is_none() - && self.environment.is_none() - && self.exporter.is_none() - && self.trace_exporter.is_none() - && self.metrics_exporter.is_none() - && !self.has_metadata() - } - - fn has_metadata(&self) -> bool { - self.span_attributes - .as_ref() - .is_some_and(|fields| !fields.is_empty()) - || self - .tracestate - .as_ref() - .is_some_and(|members| members.values().any(|fields| !fields.is_empty())) } } @@ -1882,7 +1925,7 @@ impl ConfigRequirementsToml { return Some("model_providers"); } let otel = self.otel.as_ref(); - let managed_fields: [(bool, &[&str], &'static str); 18] = [ + let managed_fields: [(bool, &[&str], &'static str); 12] = [ ( self.model_provider.is_some(), &["model_provider"], @@ -1938,36 +1981,6 @@ impl ConfigRequirementsToml { &["otel", "log_sse_deltas"], "otel.log_sse_deltas", ), - ( - otel.is_some_and(|otel| otel.log_agent_responses.is_some()), - &["otel", "log_agent_responses"], - "otel.log_agent_responses", - ), - ( - otel.is_some_and(|otel| otel.log_guardian_assessments.is_some()), - &["otel", "log_guardian_assessments"], - "otel.log_guardian_assessments", - ), - ( - otel.is_some_and(|otel| otel.environment.is_some()), - &["otel", "environment"], - "otel.environment", - ), - ( - otel.is_some_and(|otel| otel.exporter.is_some()), - &["otel", "exporter"], - "otel.exporter", - ), - ( - otel.is_some_and(|otel| otel.trace_exporter.is_some()), - &["otel", "trace_exporter"], - "otel.trace_exporter", - ), - ( - otel.is_some_and(|otel| otel.metrics_exporter.is_some()), - &["otel", "metrics_exporter"], - "otel.metrics_exporter", - ), ]; managed_fields @@ -1975,11 +1988,6 @@ impl ConfigRequirementsToml { .find_map(|(is_managed, managed_path, field)| { (is_managed && config_paths_overlap(segments, managed_path)).then_some(field) }) - .or_else(|| { - otel.and_then(|otel| { - exact_otel_metadata_requirement_for_config_path(otel, segments) - }) - }) } } @@ -1995,15 +2003,6 @@ macro_rules! otel_merge_functions { requirements.get_or_insert_default().$field = Some(value.clone()); contributed = true; })+ - if higher_priority.has_metadata() { - let target = requirements.get_or_insert_default(); - merge_otel_metadata( - &mut target.span_attributes, - &mut target.tracestate, - higher_priority, - ); - contributed = true; - } contributed } @@ -2017,91 +2016,12 @@ macro_rules! otel_merge_functions { conflict |= config.$field.as_ref().is_some_and(|current| current != value); config.$field = Some(value.clone()); })+ - conflict |= merge_otel_metadata( - &mut config.span_attributes, - &mut config.tracestate, - requirements, - ); conflict } }; } -otel_merge_functions!( - tool_result, - log_sse_deltas, - log_user_prompt, - log_agent_responses, - log_guardian_assessments, - environment, - exporter, - trace_exporter, - metrics_exporter, -); - -fn merge_otel_metadata( - span_attributes: &mut Option>, - tracestate: &mut Option>>, - requirements: &OtelRequirementsToml, -) -> bool { - let mut conflict = false; - if let Some(attributes) = &requirements.span_attributes - && !attributes.is_empty() - { - let configured = span_attributes.get_or_insert_default(); - for (key, value) in attributes { - conflict |= configured - .insert(key.clone(), value.clone()) - .is_some_and(|configured| configured != *value); - } - } - if let Some(members) = &requirements.tracestate { - for (member, fields) in members.iter().filter(|(_, fields)| !fields.is_empty()) { - let configured = tracestate - .get_or_insert_default() - .entry(member.clone()) - .or_default(); - for (key, value) in fields { - conflict |= configured - .insert(key.clone(), value.clone()) - .is_some_and(|configured| configured != *value); - } - } - } - conflict -} - -fn exact_otel_metadata_requirement_for_config_path( - requirements: &OtelRequirementsToml, - segments: &[String], -) -> Option<&'static str> { - if requirements - .span_attributes - .as_ref() - .is_some_and(|attributes| { - attributes.keys().any(|key| { - config_paths_overlap(segments, &["otel", "span_attributes", key.as_str()]) - }) - }) - { - return Some("otel.span_attributes"); - } - - requirements - .tracestate - .as_ref() - .is_some_and(|members| { - members.iter().any(|(member, fields)| { - fields.keys().any(|field| { - config_paths_overlap( - segments, - &["otel", "tracestate", member.as_str(), field.as_str()], - ) - }) - }) - }) - .then_some("otel.tracestate") -} +otel_merge_functions!(tool_result, log_sse_deltas, log_user_prompt); fn config_paths_overlap(segments: &[String], managed_path: &[&str]) -> bool { segments @@ -2683,23 +2603,17 @@ mod tests { #[test_case::test_case(&["otel", "tool_result", "max_bytes"], Some("otel.tool_result"); "tool_result_max_bytes")] #[test_case::test_case(&["otel", "log_user_prompt"], Some("otel.log_user_prompt"); "log_user_prompt")] #[test_case::test_case(&["otel", "log_sse_deltas"], Some("otel.log_sse_deltas"); "log_sse_deltas")] - #[test_case::test_case(&["otel", "environment"], Some("otel.environment"); "environment")] - #[test_case::test_case(&["otel", "exporter", "otlp-http", "endpoint"], Some("otel.exporter"); "exporter_endpoint")] - #[test_case::test_case(&["otel", "trace_exporter"], Some("otel.trace_exporter"); "trace_exporter")] - #[test_case::test_case(&["otel", "metrics_exporter"], Some("otel.metrics_exporter"); "metrics_exporter")] - #[test_case::test_case(&["otel", "span_attributes"], Some("otel.span_attributes"); "span_attributes")] - #[test_case::test_case(&["otel", "span_attributes", "service.name"], Some("otel.span_attributes"); "span_attributes_service_name")] - #[test_case::test_case(&["otel", "span_attributes", "other"], None; "span_attributes_other")] - #[test_case::test_case(&["otel", "tracestate"], Some("otel.tracestate"); "tracestate")] - #[test_case::test_case(&["otel", "tracestate", "managed", "tenant"], Some("otel.tracestate"); "tracestate_managed_tenant")] - #[test_case::test_case(&["otel", "tracestate", "managed"], Some("otel.tracestate"); "tracestate_managed")] - #[test_case::test_case(&["otel", "tracestate", "managed", "region"], None; "tracestate_managed_region")] - #[test_case::test_case(&["otel", "tracestate", "other"], None; "tracestate_other")] - #[test_case::test_case(&["otel", "tracestate", "empty"], None; "tracestate_empty")] - fn otel_requirements_project_exact_values_and_lock_only_managed_map_entries( + #[test_case::test_case(&["otel", "environment"], None; "environment_ignored")] + #[test_case::test_case(&["otel", "exporter", "otlp-http", "endpoint"], None; "exporter_ignored")] + #[test_case::test_case(&["otel", "trace_exporter"], None; "trace_exporter_ignored")] + #[test_case::test_case(&["otel", "metrics_exporter"], None; "metrics_exporter_ignored")] + #[test_case::test_case(&["otel", "span_attributes"], None; "span_attributes_ignored")] + #[test_case::test_case(&["otel", "tracestate"], None; "tracestate_ignored")] + fn otel_requirements_project_local_logging_values_and_ignore_exporter_keys( segments: &[&str], expected: Option<&str>, ) -> Result<()> { + // Former exporter keys still parse (for compatibility) but are ignored. let requirements: ConfigRequirementsToml = from_str( r#" [otel] @@ -2709,7 +2623,7 @@ environment = "managed" log_sse_deltas = false exporter = "none" trace_exporter = "none" -metrics_exporter = "none" +metrics_exporter = "statsig" span_attributes = { "service.name" = "managed" } tracestate = { managed = { tenant = "enterprise" }, empty = {} } "#, @@ -2724,8 +2638,6 @@ log_sse_deltas = true exporter = "statsig" trace_exporter = { otlp-grpc = { endpoint = "https://user.example" } } metrics_exporter = "statsig" -span_attributes = { "service.name" = "user", other = "preserved" } -tracestate = { managed = { tenant = "user", region = "us" }, other = { keep = "yes" } } "#, )?; @@ -2737,13 +2649,7 @@ tracestate = { managed = { tenant = "user", region = "us" }, other = { keep = "y [otel] tool_result = { max_bytes = 1024 } log_user_prompt = false -environment = "managed" log_sse_deltas = false -exporter = "none" -trace_exporter = "none" -metrics_exporter = "none" -span_attributes = { "service.name" = "managed", other = "preserved" } -tracestate = { managed = { tenant = "enterprise", region = "us" }, other = { keep = "yes" } } "# )? ); @@ -2758,7 +2664,7 @@ tracestate = { managed = { tenant = "enterprise", region = "us" }, other = { kee for empty in [ "[otel]", "[otel.span_attributes]", - "[otel.tracestate.empty]", + "[otel]\nexporter = \"statsig\"", ] { let requirements: ConfigRequirementsToml = from_str(empty)?; assert!(requirements.is_empty(), "{empty}"); @@ -3441,7 +3347,7 @@ tracestate = { managed = { tenant = "enterprise", region = "us" }, other = { kee plugins: None, marketplaces: None, otel: Some(Box::new(OtelRequirementsToml { - environment: Some("managed".to_string()), + log_user_prompt: Some(true), ..Default::default() })), apps: None, @@ -3539,7 +3445,7 @@ tracestate = { managed = { tenant = "enterprise", region = "us" }, other = { kee marketplaces: None, otel: Some(Box::new(Sourced::new( OtelRequirementsToml { - environment: Some("managed".to_string()), + log_user_prompt: Some(true), ..Default::default() }, source.clone(), diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index ed06a95f..67c23147 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -11,7 +11,6 @@ use crate::browser_use::BrowserUseConfigToml; use crate::computer_use::ComputerUseConfigToml; use crate::permissions_toml::PermissionsToml; use crate::profile_toml::ConfigProfile; -use crate::types::AnalyticsConfigToml; use crate::types::ApprovalsReviewer; use crate::types::AppsConfigToml; use crate::types::AuthCredentialsStoreMode; @@ -535,11 +534,6 @@ pub struct ConfigToml { /// Legacy fallback for `tui.disable_paste_burst`. Prefer the setting under `[tui]`. pub disable_paste_burst: Option, - /// When `enabled` is `false`, disables OpenAI analytics across Codex product surfaces on this machine. - /// Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`. - /// When unset, the default depends on the client. - pub analytics: Option, - /// When `false`, disables feedback collection across Codex product surfaces. /// Defaults to `true`. pub feedback: Option, @@ -552,7 +546,7 @@ pub struct ConfigToml { #[serde(default)] pub desktop: Option>, - /// OTEL configuration. + /// Local logging settings (historical `[otel]` table; nothing is exported). pub otel: Option, /// Windows-specific configuration. diff --git a/codex-rs/config/src/profile_toml.rs b/codex-rs/config/src/profile_toml.rs index 53f32f3f..83f8f2b4 100644 --- a/codex-rs/config/src/profile_toml.rs +++ b/codex-rs/config/src/profile_toml.rs @@ -4,7 +4,6 @@ use serde::Deserialize; use serde::Serialize; use crate::config_toml::ToolsToml; -use crate::types::AnalyticsConfigToml; use crate::types::ApprovalsReviewer; use crate::types::Personality; use crate::types::SessionPickerViewMode; @@ -59,7 +58,6 @@ pub struct ConfigProfile { pub experimental_use_unified_exec_tool: Option, pub tools: Option, pub web_search: Option, - pub analytics: Option, /// TUI settings scoped to this profile. #[serde(default)] pub tui: Option, diff --git a/codex-rs/config/src/requirements_layers/stack_tests.rs b/codex-rs/config/src/requirements_layers/stack_tests.rs index 85b28885..1fec7df7 100644 --- a/codex-rs/config/src/requirements_layers/stack_tests.rs +++ b/codex-rs/config/src/requirements_layers/stack_tests.rs @@ -341,7 +341,7 @@ refresh_interval_ms = 12345 } #[test] -fn otel_requirements_compose_exact_values_atomic_exporters_and_metadata() { +fn otel_requirements_compose_exact_values_and_ignore_legacy_exporter_keys() { let low_dir = tempdir().expect("low-priority requirements directory"); let high_dir = tempdir().expect("high-priority requirements directory"); let low_base = AbsolutePathBuf::from_absolute_path(low_dir.path()).expect("absolute low base"); @@ -421,16 +421,10 @@ tracestate = { shared = { tenant = "replacement", region = "us" }, lower = { ten composed.value, *expected_requirements(expected).otel.unwrap() ); - assert_eq!( - compose(vec![layer( - "mixed", - "Mixed", - "[otel]\nexporter = 'none'\nspan_attributes = {}\ntracestate = { empty = {} }", - )]), - Ok(Some(expected_requirements("[otel]\nexporter = 'none'"))), - ); - + // Legacy exporter/metadata keys are accepted but ignored, so a layer that + // only sets them contributes no OTEL requirements. for empty in [ + "[otel]\nexporter = 'none'\nspan_attributes = {}\ntracestate = { empty = {} }", "[otel]", "[otel.span_attributes]", "[otel.tracestate.empty]", diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 3fbae6e4..d1b17606 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -30,7 +30,6 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::fmt; -use codex_utils_redacted_string::RedactedString; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -53,7 +52,6 @@ pub use crate::tui_keymap::TuiVimOperatorKeymap; pub use crate::tui_keymap::TuiVimSearchKeymap; pub use crate::tui_rendering::TuiRendering; -pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev"; pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 2; pub const DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS: i64 = 10; pub const DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS: i64 = 6; @@ -242,21 +240,10 @@ pub enum HistoryPersistence { None, } -// ===== Analytics configuration ===== - -/// Analytics settings loaded from config.toml. Fields are optional so we can apply defaults. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AnalyticsConfigToml { - /// When `false`, disables OpenAI analytics across Codex product surfaces in this profile. - /// Custom OTLP metrics exporters remain enabled; set `otel.metrics_exporter = "none"` to disable them. - pub enabled: Option, -} - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct FeedbackConfigToml { - /// When `false`, disables feedback uploads and background Guardian review retention. Explicit local exports remain available. + /// When `false`, disables feedback collection and background Guardian review retention. Explicit local exports remain available. pub enabled: Option, } @@ -589,102 +576,29 @@ pub struct AppsConfigToml { // ===== OTEL configuration ===== -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] -#[serde(rename_all = "kebab-case")] -pub enum OtelHttpProtocol { - /// Binary payload - Binary, - /// JSON payload - Json, -} - +/// Local logging settings kept under the historical `[otel]` table. +/// +/// aKode never exports telemetry. The former exporter keys (`exporter`, +/// `trace_exporter`, `metrics_exporter`, `environment`, `span_attributes`, +/// `tracestate`, `log_agent_responses`, `log_guardian_assessments`) are still +/// accepted in `config.toml` for compatibility but are ignored. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -#[serde(rename_all = "kebab-case")] -pub struct OtelTlsConfig { - pub ca_certificate: Option, - pub client_certificate: Option, - pub client_private_key: Option, -} - -/// Which OTEL exporter to use. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] -#[schemars(deny_unknown_fields)] -#[serde(rename_all = "kebab-case")] -pub enum OtelExporterKind { - None, - Statsig, - OtlpHttp { - endpoint: String, - #[serde(default)] - #[schemars(with = "HashMap")] - headers: HashMap, - protocol: OtelHttpProtocol, - #[serde(default)] - tls: Option, - }, - OtlpGrpc { - endpoint: String, - #[serde(default)] - #[schemars(with = "HashMap")] - headers: HashMap, - #[serde(default)] - tls: Option, - }, -} - -/// OTEL settings loaded from config.toml. Fields are optional so we can apply defaults. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] pub struct OtelConfigToml { /// Byte limit for tool-result log output; independent of model-visible output. pub tool_result: Option, /// Log successful SSE events whose kind ends in `.delta`. Defaults to true. - /// Disabling this preserves errors, completion events, and metrics. + /// Disabling this preserves errors and completion events. pub log_sse_deltas: Option, - /// Log user prompt in traces + /// Include the user prompt in local log events. pub log_user_prompt: Option, - /// Opt in to logging final main-agent and spawned-subagent responses to an OTLP log exporter. - /// Defaults to false. Response text can be sensitive and is capped at 64 KiB. - pub log_agent_responses: Option, - /// Opt in to logging completed Guardian assessments to an OTLP log exporter. - /// Defaults to false. Rationales can be sensitive and are capped at 64 KiB. - pub log_guardian_assessments: Option, - - /// Mark traces with environment (dev, staging, prod, test). Defaults to dev. - pub environment: Option, - - /// Optional log exporter - pub exporter: Option, - - /// Optional trace exporter - pub trace_exporter: Option, - - /// Metrics exporter. Defaults to `statsig`, which follows `analytics.enabled`. - /// Custom OTLP exporters are independent of `analytics.enabled`; `none` disables metrics export. - pub metrics_exporter: Option, - - /// Attributes to add to every exported trace span. - pub span_attributes: Option>, - - /// Semicolon-separated `key:value` fields to upsert into W3C tracestate members. - pub tracestate: Option>>, } -/// Effective OTEL settings after defaults are applied. +/// Effective local logging settings after defaults are applied. #[derive(Debug, Clone, PartialEq)] pub struct OtelConfig { pub tool_result: codex_protocol::config_types::ToolResultLogConfig, pub log_sse_deltas: bool, pub log_user_prompt: bool, - pub log_agent_responses: bool, - pub log_guardian_assessments: bool, - pub environment: String, - pub exporter: OtelExporterKind, - pub trace_exporter: OtelExporterKind, - pub metrics_exporter: OtelExporterKind, - pub span_attributes: HashMap, - pub tracestate: BTreeMap>, } impl Default for OtelConfig { @@ -693,38 +607,10 @@ impl Default for OtelConfig { tool_result: Default::default(), log_sse_deltas: true, log_user_prompt: false, - log_agent_responses: false, - log_guardian_assessments: false, - environment: DEFAULT_OTEL_ENVIRONMENT.to_owned(), - exporter: OtelExporterKind::None, - trace_exporter: OtelExporterKind::None, - metrics_exporter: OtelExporterKind::None, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), } } } -impl OtelConfig { - /// Response text requires a separate opt-in and an explicit OTLP log destination. - pub fn agent_response_logging_enabled(&self) -> bool { - self.log_agent_responses - && matches!( - self.exporter, - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } - ) - } - - /// Assessment text requires an explicit opt-in and an OTLP log destination. - pub fn guardian_assessment_logging_enabled(&self) -> bool { - self.log_guardian_assessments - && matches!( - self.exporter, - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } - ) - } -} - #[derive(Serialize, Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)] #[serde(untagged)] pub enum Notifications { diff --git a/codex-rs/core-api/Cargo.toml b/codex-rs/core-api/Cargo.toml index ed1fbff4..c0bb6151 100644 --- a/codex-rs/core-api/Cargo.toml +++ b/codex-rs/core-api/Cargo.toml @@ -16,7 +16,6 @@ workspace = true [dependencies] codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } -codex-analytics = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-extension-api = { workspace = true } diff --git a/codex-rs/core-api/src/lib.rs b/codex-rs/core-api/src/lib.rs index 222b8f2f..bdae7b38 100644 --- a/codex-rs/core-api/src/lib.rs +++ b/codex-rs/core-api/src/lib.rs @@ -2,7 +2,6 @@ #![deny(private_bounds, private_interfaces, unreachable_pub)] -pub use codex_analytics::AnalyticsEventsClient; pub use codex_app_server_protocol::ServerNotification; pub use codex_app_server_protocol::item_event_to_server_notification; pub use codex_arg0::Arg0DispatchPaths; diff --git a/codex-rs/core-plugins/Cargo.toml b/codex-rs/core-plugins/Cargo.toml index 747dec9b..0952f456 100644 --- a/codex-rs/core-plugins/Cargo.toml +++ b/codex-rs/core-plugins/Cargo.toml @@ -16,7 +16,6 @@ workspace = true codex-utils-process = { workspace = true } anyhow = { workspace = true } chrono = { workspace = true } -codex-analytics = { workspace = true } codex-api = { workspace = true } codex-app-server-protocol = { workspace = true } codex-config = { workspace = true } diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 138dfd33..1eb45886 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -22,8 +22,6 @@ mod marketplace_staging; pub mod marketplace_upgrade; mod npm_source; mod plugin_bundle_archive; -mod plugin_metrics; -mod plugin_metrics_sidecar; mod provider; mod recommended_plugin_install; pub mod remote; @@ -107,13 +105,6 @@ pub use marketplace_policy::allowed_configured_marketplace_names; pub use marketplace_upgrade::ConfigLayerReload; pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError; pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome; -pub use plugin_metrics::PluginMeasurementDefinition; -pub use plugin_metrics::PluginMetricsOperation; -pub use plugin_metrics::ResolvedPluginMetricsOperation; -pub use plugin_metrics_sidecar::PLUGIN_METRICS_OUTPUT_ENV_VAR; -pub use plugin_metrics_sidecar::PluginMeasurementBatch; -pub use plugin_metrics_sidecar::PluginMetricsSidecar; -pub use plugin_metrics_sidecar::strip_output_env; pub use provider::PluginListQuery; pub use provider::PluginProvider; pub use provider::PluginProviderError; @@ -124,7 +115,6 @@ pub use remote::RecommendedPlugin; pub use remote::RecommendedPluginsMode; pub use remote_metadata::remote_catalog_metadata_eq; pub use script_attribution::PluginCommandAttribution; -pub use script_attribution::PluginMeasurementTarget; pub use script_attribution::TrustedPluginRoots; pub use script_attribution::command_script_arguments; diff --git a/codex-rs/core-plugins/src/manager.rs b/codex-rs/core-plugins/src/manager.rs index d25ef052..e3b81095 100644 --- a/codex-rs/core-plugins/src/manager.rs +++ b/codex-rs/core-plugins/src/manager.rs @@ -91,8 +91,6 @@ use crate::store::PluginInstallResult as StorePluginInstallResult; use crate::store::PluginStore; use crate::store::PluginStoreError; use crate::tool_suggest_metadata::ToolSuggestMetadataCache; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::PluginInstallSource; use codex_config::ConfigLayerStack; use codex_config::SkillConfigRules; use codex_config::clear_user_plugin; @@ -322,7 +320,7 @@ enum RemoteInstalledPluginsCachePublication { /// remote plugin mutations. /// /// Callers should keep this guard only while mutating the remote plugin cache and backend -/// installed state, then release it before unrelated analytics, OAuth, or runtime refresh work. +/// installed state, then release it before unrelated OAuth or runtime refresh work. struct RemoteInstalledPluginSyncGuard { _permit: OwnedSemaphorePermit, } @@ -595,8 +593,6 @@ pub struct PluginsManager { restriction_product: Option, auth_manager: Arc, runtime_auth: RuntimeAuthSlot, - analytics_events_client: RwLock>, - plugin_install_source: PluginInstallSource, } #[derive(Clone)] @@ -737,7 +733,6 @@ impl PluginsManager { runtime_auth, Arc::clone(&self.skill_root_loader), ) - .with_plugin_install_source(self.plugin_install_source) } pub fn new( @@ -803,16 +798,9 @@ impl PluginsManager { restriction_product, auth_manager, runtime_auth, - analytics_events_client: RwLock::new(None), - plugin_install_source: PluginInstallSource::Manual, } } - pub fn with_plugin_install_source(mut self, source: PluginInstallSource) -> Self { - self.plugin_install_source = source; - self - } - pub fn auth_mode(&self) -> Option { self.auth_manager.get_api_auth_mode() } @@ -821,14 +809,6 @@ impl PluginsManager { config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend) } - pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) { - let mut stored_client = match self.analytics_events_client.write() { - Ok(client_guard) => client_guard, - Err(err) => err.into_inner(), - }; - *stored_client = Some(analytics_events_client); - } - fn restriction_product_matches(&self, products: Option<&[Product]>) -> bool { match products { None => true, @@ -2293,15 +2273,6 @@ impl PluginsManager { error = %err, "plugin install failed while resolving marketplace plugin" ); - self.emit_plugin_install_failed( - PluginTelemetryMetadata { - plugin_id: None, - remote_plugin_id: None, - capability_summary: None, - }, - marketplace_error_type(err), - sub_error_type, - ); } } @@ -2319,31 +2290,6 @@ impl PluginsManager { error = %error_message, "plugin install failed" ); - self.emit_plugin_install_failed( - self.telemetry_metadata_for_plugin_id(plugin_id), - error_type, - sub_error_type, - ); - } - - fn emit_plugin_install_failed( - &self, - plugin: PluginTelemetryMetadata, - error_type: &'static str, - sub_error_type: Option, - ) { - let analytics_events_client = match self.analytics_events_client.read() { - Ok(client) => client.clone(), - Err(err) => err.into_inner().clone(), - }; - if let Some(analytics_events_client) = analytics_events_client { - analytics_events_client.track_plugin_install_failed( - plugin, - self.plugin_install_source, - error_type.to_string(), - sub_error_type, - ); - } } async fn install_resolved_plugin( @@ -2404,17 +2350,6 @@ impl PluginsManager { .await .map_err(anyhow::Error::from)?; - let analytics_events_client = match self.analytics_events_client.read() { - Ok(client) => client.clone(), - Err(err) => err.into_inner().clone(), - }; - if let Some(analytics_events_client) = analytics_events_client { - analytics_events_client.track_plugin_installed( - self.telemetry_metadata_for_installed_plugin(&result.plugin_id) - .await, - ); - } - Ok(PluginInstallOutcome { plugin_id: result.plugin_id, plugin_version: result.plugin_version, @@ -2450,14 +2385,6 @@ impl PluginsManager { } async fn uninstall_plugin_id(&self, plugin_id: PluginId) -> Result<(), PluginUninstallError> { - let plugin_telemetry = if self.store.active_plugin_root(&plugin_id).is_some() { - Some( - self.telemetry_metadata_for_installed_plugin(&plugin_id) - .await, - ) - } else { - None - }; let store = self.store.clone(); let plugin_id_for_store = plugin_id.clone(); tokio::task::spawn_blocking(move || store.uninstall(&plugin_id_for_store)) @@ -2468,16 +2395,6 @@ impl PluginsManager { .await .map_err(anyhow::Error::from)?; - let analytics_events_client = match self.analytics_events_client.read() { - Ok(client) => client.clone(), - Err(err) => err.into_inner().clone(), - }; - if let Some(plugin_telemetry) = plugin_telemetry - && let Some(analytics_events_client) = analytics_events_client - { - analytics_events_client.track_plugin_uninstalled(plugin_telemetry); - } - Ok(()) } diff --git a/codex-rs/core-plugins/src/plugin_metrics.rs b/codex-rs/core-plugins/src/plugin_metrics.rs deleted file mode 100644 index b7df8119..00000000 --- a/codex-rs/core-plugins/src/plugin_metrics.rs +++ /dev/null @@ -1,158 +0,0 @@ -use crate::script_attribution::normalized_relative_script_path; -use codex_plugin::PluginId; -use codex_protocol::items::is_safe_plugin_relative_path; -use codex_utils_absolute_path::AbsolutePathBuf; -use serde::Deserialize; -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::fs::File; -use std::io::Read; - -const ANALYTICS_MANIFEST_FILE: &str = "analytics.yaml"; -const MAX_ANALYTICS_MANIFEST_BYTES: u64 = 64 * 1024; -const MAX_IDENTIFIER_LEN: usize = 64; -const MAX_DIMENSIONS_PER_MEASUREMENT: usize = 8; - -/// The manifest declaration for one numeric measurement. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginMeasurementDefinition { - pub enum_dimensions: BTreeMap>, -} - -/// Custom metrics allowed for one trusted plugin script operation. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginMetricsOperation { - pub operation_name: String, - pub measurements: BTreeMap, -} - -/// A metrics operation bound to identity from a fresh trusted command lookup. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ResolvedPluginMetricsOperation { - pub plugin_id: PluginId, - pub operation: PluginMetricsOperation, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct AnalyticsManifest { - version: u32, - #[serde(with = "serde_with::rust::maps_duplicate_key_is_error")] - operations: BTreeMap, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OperationDeclaration { - path: String, - #[serde(with = "serde_with::rust::maps_duplicate_key_is_error")] - measurements: BTreeMap, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct MeasurementDeclaration { - #[serde(default, with = "serde_with::rust::maps_duplicate_key_is_error")] - dimensions: BTreeMap>, -} - -pub(crate) fn load_plugin_metrics_operations( - plugin_root: &AbsolutePathBuf, -) -> Option> { - let manifest_path = plugin_root.join(ANALYTICS_MANIFEST_FILE); - let canonical_manifest_path = manifest_path.canonicalize().ok()?; - if canonical_manifest_path != manifest_path || !manifest_path.as_path().is_file() { - return None; - } - - let mut contents = Vec::new(); - File::open(manifest_path.as_path()) - .ok()? - .take(MAX_ANALYTICS_MANIFEST_BYTES + 1) - .read_to_end(&mut contents) - .ok()?; - if contents.len() as u64 > MAX_ANALYTICS_MANIFEST_BYTES { - return None; - } - let manifest: AnalyticsManifest = serde_yaml::from_slice(&contents).ok()?; - validate_manifest(manifest, plugin_root) -} - -fn validate_manifest( - manifest: AnalyticsManifest, - plugin_root: &AbsolutePathBuf, -) -> Option> { - if manifest.version != 1 || manifest.operations.is_empty() { - return None; - } - - let mut operations_by_path = BTreeMap::new(); - for (operation_name, operation) in manifest.operations { - if !valid_identifier(&operation_name) || operation.measurements.is_empty() { - return None; - } - let normalized_path = validated_operation_path(plugin_root, &operation.path)?; - let mut measurements = BTreeMap::new(); - for (measurement_name, measurement) in operation.measurements { - if !valid_identifier(&measurement_name) - || measurement.dimensions.len() > MAX_DIMENSIONS_PER_MEASUREMENT - { - return None; - } - let mut enum_dimensions = BTreeMap::new(); - for (dimension_name, values) in measurement.dimensions { - if !valid_identifier(&dimension_name) || values.is_empty() { - return None; - } - let value_count = values.len(); - let values = values.into_iter().collect::>(); - if values.len() != value_count - || values.iter().any(|value| !valid_identifier(value)) - { - return None; - } - enum_dimensions.insert(dimension_name, values); - } - measurements.insert( - measurement_name, - PluginMeasurementDefinition { enum_dimensions }, - ); - } - if operations_by_path - .insert( - normalized_path, - PluginMetricsOperation { - operation_name, - measurements, - }, - ) - .is_some() - { - return None; - } - } - Some(operations_by_path) -} - -fn validated_operation_path(plugin_root: &AbsolutePathBuf, path: &str) -> Option { - let normalized_path = path.strip_prefix("./").unwrap_or(path); - if !is_safe_plugin_relative_path(normalized_path) { - return None; - } - let script = plugin_root.join(normalized_path).canonicalize().ok()?; - if !script.as_path().is_file() { - return None; - } - let canonical_relative_path = script.as_path().strip_prefix(plugin_root.as_path()).ok()?; - (normalized_relative_script_path(canonical_relative_path)?.as_str() == normalized_path) - .then(|| normalized_path.to_string()) -} - -fn valid_identifier(value: &str) -> bool { - let mut chars = value.chars(); - matches!(chars.next(), Some('a'..='z')) - && value.len() <= MAX_IDENTIFIER_LEN - && chars.all(|character| { - character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' - }) -} diff --git a/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs b/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs deleted file mode 100644 index c1302f9e..00000000 --- a/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs +++ /dev/null @@ -1,299 +0,0 @@ -use crate::ResolvedPluginMetricsOperation; -use codex_analytics::PluginMeasurementRow; -use codex_exec_server::CreateDirectoryOptions; -use codex_exec_server::Environment; -use codex_exec_server::ExecutorFileSystem; -use codex_exec_server::FileSystemReadStream; -use codex_exec_server::RemoveOptions; -use codex_exec_server::WriteFileOptions; -use codex_protocol::models::AdditionalPermissionProfile; -use codex_protocol::models::FileSystemPermissions; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_path_uri::PathConvention; -use codex_utils_path_uri::PathUri; -use futures::StreamExt; -use serde::Deserialize; -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::collections::HashMap; -use std::io::Read; -use std::io::Seek; -use std::io::SeekFrom; -use std::sync::Arc; -use tempfile::NamedTempFile; -use uuid::Uuid; - -pub const PLUGIN_METRICS_OUTPUT_ENV_VAR: &str = "CODEX_PLUGIN_METRICS_OUTPUT"; -const MAX_OUTPUT_BYTES: u64 = 64 * 1024; -const MAX_OUTPUT_ROWS: usize = 100; - -#[derive(Debug, PartialEq)] -pub struct PluginMeasurementBatch { - pub plugin_id: String, - pub execution_id: String, - pub operation: String, - pub rows: Vec, -} - -pub struct PluginMetricsSidecar { - output: PluginMetricsOutput, - absolute_output_dir: AbsolutePathBuf, - output_env_value: String, - resolved: ResolvedPluginMetricsOperation, - execution_id: String, -} - -enum PluginMetricsOutput { - Local { - file: NamedTempFile, - _directory: tempfile::TempDir, - }, - Remote { - file_stream: tokio::sync::Mutex, - _directory: RemotePluginMetricsDirectory, - }, -} - -struct RemotePluginMetricsDirectory { - filesystem: Arc, - path: PathUri, -} - -impl Drop for RemotePluginMetricsDirectory { - fn drop(&mut self) { - let Ok(runtime) = tokio::runtime::Handle::try_current() else { - return; - }; - let filesystem = Arc::clone(&self.filesystem); - let path = self.path.clone(); - runtime.spawn(async move { - let _ = filesystem - .remove( - &path, - RemoveOptions { - recursive: true, - force: true, - follow_symlinks: true, - }, - /*sandbox*/ None, - ) - .await; - }); - } -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OutputEnvelope { - version: u32, - measurements: Vec, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OutputMeasurement { - name: String, - value: f64, - #[serde(default)] - dimensions: BTreeMap, -} - -impl PluginMetricsSidecar { - pub fn create(resolved: ResolvedPluginMetricsOperation) -> Option { - let sidecar_dir = tempfile::Builder::new() - .prefix("codex-plugin-metrics-") - .tempdir() - .ok()?; - let output_file = tempfile::Builder::new() - .prefix("measurements-") - .suffix(".json") - .tempfile_in(sidecar_dir.path()) - .ok()?; - let absolute_output_dir = AbsolutePathBuf::from_absolute_path(sidecar_dir.path()).ok()?; - let absolute_output_path = AbsolutePathBuf::from_absolute_path(output_file.path()).ok()?; - let output_env_value = absolute_output_path.as_path().to_str()?.to_string(); - Some(Self { - output: PluginMetricsOutput::Local { - file: output_file, - _directory: sidecar_dir, - }, - absolute_output_dir, - output_env_value, - resolved, - execution_id: Uuid::new_v4().to_string(), - }) - } - - pub async fn create_remote( - environment: &Environment, - resolved: ResolvedPluginMetricsOperation, - ) -> Option { - let temp_dir = environment.info().await.ok()?.temp_dir?; - // Permission overlays still use host-native AbsolutePathBuf roots, so a - // foreign executor path cannot be granted its exact sidecar directory. - if !cfg!(unix) || temp_dir.infer_path_convention() != Some(PathConvention::Posix) { - tracing::debug!( - executor_temp_dir = %temp_dir, - "plugin metrics require POSIX executor paths on a POSIX frontend" - ); - return None; - } - let execution_id = Uuid::new_v4().to_string(); - let directory_path = temp_dir - .join(&format!("codex-plugin-metrics-{execution_id}")) - .ok()?; - let absolute_output_dir = directory_path.to_abs_path().ok()?; - let filesystem = environment.get_filesystem(); - filesystem - .create_directory( - &directory_path, - CreateDirectoryOptions { - recursive: false, - follow_symlinks: true, - }, - /*sandbox*/ None, - ) - .await - .ok()?; - let directory = RemotePluginMetricsDirectory { - filesystem, - path: directory_path, - }; - let output_path = directory.path.join("measurements.json").ok()?; - directory - .filesystem - .write_file( - &output_path, - Vec::new(), - WriteFileOptions::default(), - /*sandbox*/ None, - ) - .await - .ok()?; - let file_stream = directory - .filesystem - .read_file_stream(&output_path, /*sandbox*/ None) - .await - .ok()?; - Some(Self { - output: PluginMetricsOutput::Remote { - file_stream: tokio::sync::Mutex::new(file_stream), - _directory: directory, - }, - absolute_output_dir, - output_env_value: output_path.inferred_native_path_string(), - resolved, - execution_id, - }) - } - - pub fn install_output_env(&self, env: &mut HashMap) { - env.insert( - PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(), - self.output_env_value.clone(), - ); - } - - #[cfg(test)] - fn absolute_output_path(&self) -> AbsolutePathBuf { - AbsolutePathBuf::from_absolute_path(&self.output_env_value).expect("absolute output path") - } - - pub fn additional_permissions(&self) -> AdditionalPermissionProfile { - AdditionalPermissionProfile { - file_system: Some(FileSystemPermissions::from_read_write_roots( - /*read*/ None, - /*write*/ Some(vec![self.absolute_output_dir.clone()]), - )), - ..Default::default() - } - } - - pub async fn finish(mut self, exit_code: i32) -> Option { - if exit_code != 0 { - return None; - } - let mut contents = Vec::new(); - match &mut self.output { - PluginMetricsOutput::Local { file, .. } => { - let output_file = file.as_file_mut(); - output_file.seek(SeekFrom::Start(0)).ok()?; - output_file - .take(MAX_OUTPUT_BYTES + 1) - .read_to_end(&mut contents) - .ok()?; - } - PluginMetricsOutput::Remote { file_stream, .. } => { - let file_stream = file_stream.get_mut(); - while let Some(chunk) = file_stream.next().await { - let chunk = chunk.ok()?; - if contents.len().saturating_add(chunk.len()) > MAX_OUTPUT_BYTES as usize { - return None; - } - contents.extend_from_slice(&chunk); - } - } - } - let rows = parse_output(&contents, &self.resolved)?; - (!rows.is_empty()).then(|| PluginMeasurementBatch { - plugin_id: self.resolved.plugin_id.as_key(), - execution_id: self.execution_id, - operation: self.resolved.operation.operation_name, - rows, - }) - } -} - -pub fn strip_output_env(env: &mut HashMap) { - if cfg!(windows) { - env.retain(|key, _| !key.eq_ignore_ascii_case(PLUGIN_METRICS_OUTPUT_ENV_VAR)); - } else { - env.remove(PLUGIN_METRICS_OUTPUT_ENV_VAR); - } -} - -fn parse_output( - contents: &[u8], - resolved: &ResolvedPluginMetricsOperation, -) -> Option> { - if contents.len() as u64 > MAX_OUTPUT_BYTES { - return None; - } - let output: OutputEnvelope = serde_json::from_slice(contents).ok()?; - if output.version != 1 || output.measurements.len() > MAX_OUTPUT_ROWS { - return None; - } - - let mut seen = BTreeSet::new(); - let mut rows = Vec::new(); - for value in output.measurements { - let Ok(measurement) = serde_json::from_value::(value) else { - continue; - }; - let Some(definition) = resolved.operation.measurements.get(&measurement.name) else { - continue; - }; - if !measurement.value.is_finite() - || measurement.dimensions.len() != definition.enum_dimensions.len() - || !definition.enum_dimensions.iter().all(|(name, allowed)| { - measurement - .dimensions - .get(name) - .is_some_and(|value| allowed.contains(value)) - }) - || !seen.insert((measurement.name.clone(), measurement.dimensions.clone())) - { - continue; - } - rows.push(PluginMeasurementRow { - measurement_name: measurement.name, - number_value: measurement.value, - dimensions: measurement.dimensions, - }); - } - Some(rows) -} - -#[cfg(test)] -#[path = "plugin_metrics_sidecar_tests.rs"] -mod tests; diff --git a/codex-rs/core-plugins/src/plugin_metrics_sidecar_tests.rs b/codex-rs/core-plugins/src/plugin_metrics_sidecar_tests.rs deleted file mode 100644 index 4be61b64..00000000 --- a/codex-rs/core-plugins/src/plugin_metrics_sidecar_tests.rs +++ /dev/null @@ -1,195 +0,0 @@ -use super::*; -use crate::PluginMeasurementDefinition; -use crate::PluginMetricsOperation; -use codex_plugin::PluginId; -use codex_protocol::models::LegacyReadWriteRoots; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn create_sidecar() -> PluginMetricsSidecar { - PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar") -} - -#[test] -fn sidecar_is_created_in_system_temp_with_private_permissions() { - let output_dir = - AbsolutePathBuf::from_absolute_path(std::env::temp_dir()).expect("absolute temp directory"); - let sidecar = PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar"); - - assert_eq!( - sidecar.absolute_output_path().parent(), - Some(sidecar.absolute_output_dir.clone()) - ); - assert_eq!(sidecar.absolute_output_dir.parent(), Some(output_dir)); - assert!(sidecar.absolute_output_dir.as_path().is_dir()); - let roots = sidecar - .additional_permissions() - .file_system - .expect("file system permissions") - .legacy_read_write_roots() - .expect("legacy roots"); - assert_eq!( - roots, - LegacyReadWriteRoots { - read: None, - write: Some(vec![sidecar.absolute_output_dir]), - } - ); -} - -fn resolved_operation() -> ResolvedPluginMetricsOperation { - ResolvedPluginMetricsOperation { - plugin_id: PluginId::parse("security@openai-curated").expect("valid plugin id"), - operation: PluginMetricsOperation { - operation_name: "security_scan".to_string(), - measurements: BTreeMap::from([ - ( - "finding_count".to_string(), - PluginMeasurementDefinition { - enum_dimensions: BTreeMap::from([( - "severity".to_string(), - BTreeSet::from(["high".to_string(), "low".to_string()]), - )]), - }, - ), - ( - "files_scanned".to_string(), - PluginMeasurementDefinition { - enum_dimensions: BTreeMap::new(), - }, - ), - ]), - }, - } -} - -#[tokio::test] -async fn sidecar_keeps_valid_rows_and_first_duplicate_then_cleans_up() { - let sidecar = create_sidecar(); - let path = sidecar.absolute_output_path(); - std::fs::write( - path.as_path(), - json!({ - "version": 1, - "measurements": [ - {"name": "finding_count", "value": 3, "dimensions": {"severity": "high"}}, - {"name": "unknown", "value": 1}, - {"name": "finding_count", "value": 4}, - {"name": "finding_count", "value": 5, "dimensions": {"severity": "critical"}}, - {"name": "finding_count", "value": 6, "dimensions": {"severity": "high", "extra": "x"}}, - {"name": "finding_count", "value": 99, "dimensions": {"severity": "high"}}, - {"name": "files_scanned", "value": 17}, - {"name": "files_scanned", "value": "not-a-number"}, - {"name": "files_scanned", "value": 18, "unknown": true} - ] - }) - .to_string(), - ) - .expect("write output"); - - let batch = sidecar - .finish(/*exit_code*/ 0) - .await - .expect("valid measurements"); - let execution_id = batch.execution_id.clone(); - assert_eq!( - batch, - PluginMeasurementBatch { - plugin_id: "security@openai-curated".to_string(), - execution_id: execution_id.clone(), - operation: "security_scan".to_string(), - rows: vec![ - PluginMeasurementRow { - measurement_name: "finding_count".to_string(), - number_value: 3.0, - dimensions: BTreeMap::from([("severity".to_string(), "high".to_string(),)]), - }, - PluginMeasurementRow { - measurement_name: "files_scanned".to_string(), - number_value: 17.0, - dimensions: BTreeMap::new(), - }, - ], - } - ); - assert_eq!( - Uuid::parse_str(&execution_id) - .expect("execution id UUID") - .get_version(), - Some(uuid::Version::Random) - ); - assert!(!path.exists()); -} - -#[tokio::test] -async fn malformed_oversized_and_nonzero_outputs_are_ignored_and_cleaned_up() { - for output in [ - r#"{"version":2,"measurements":[]}"#.as_bytes().to_vec(), - r#"{"version":1,"measurements":[],"unknown":true}"#.as_bytes().to_vec(), - json!({ - "version": 1, - "measurements": vec![json!({"name": "files_scanned", "value": 1}); MAX_OUTPUT_ROWS + 1] - }) - .to_string() - .into_bytes(), - vec![b' '; MAX_OUTPUT_BYTES as usize + 1], - ] { - let sidecar = create_sidecar(); - let path = sidecar.absolute_output_path(); - std::fs::write(path.as_path(), output).expect("write output"); - assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None); - assert!(!path.exists()); - } - - let sidecar = create_sidecar(); - let path = sidecar.absolute_output_path(); - std::fs::write( - path.as_path(), - r#"{"version":1,"measurements":[{"name":"files_scanned","value":1}]}"#, - ) - .expect("write output"); - assert_eq!(sidecar.finish(/*exit_code*/ 1).await, None); - assert!(!path.exists()); -} - -#[test] -fn reserved_output_env_is_absent_without_sidecar_and_cannot_be_overridden() { - let mut env = HashMap::from([ - ( - PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(), - "/user/path".to_string(), - ), - ("KEEP".to_string(), "value".to_string()), - ]); - strip_output_env(&mut env); - assert_eq!( - env, - HashMap::from([("KEEP".to_string(), "value".to_string())]) - ); - - let sidecar = create_sidecar(); - let path = sidecar.absolute_output_path(); - sidecar.install_output_env(&mut env); - assert_eq!( - env.get(PLUGIN_METRICS_OUTPUT_ENV_VAR).map(String::as_str), - path.as_path().to_str() - ); - drop(sidecar); - assert!(!path.exists()); -} - -#[cfg(unix)] -#[tokio::test] -async fn sidecar_reads_the_original_file_after_path_replacement() { - let sidecar = create_sidecar(); - let path = sidecar.absolute_output_path(); - std::fs::remove_file(path.as_path()).expect("remove original output path"); - std::fs::write( - path.as_path(), - r#"{"version":1,"measurements":[{"name":"files_scanned","value":99}]}"#, - ) - .expect("write replacement output"); - - assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None); - assert!(!path.exists()); -} diff --git a/codex-rs/core-plugins/src/script_attribution.rs b/codex-rs/core-plugins/src/script_attribution.rs index 9a10ea77..66693f29 100644 --- a/codex-rs/core-plugins/src/script_attribution.rs +++ b/codex-rs/core-plugins/src/script_attribution.rs @@ -6,9 +6,6 @@ use crate::loader::curated_plugin_cache_version; use crate::marketplace::MarketplacePluginSource; use crate::marketplace::find_marketplace_plugin; use crate::marketplace_policy::primary_runtime_marketplace_root; -use crate::plugin_metrics::PluginMetricsOperation; -use crate::plugin_metrics::ResolvedPluginMetricsOperation; -use crate::plugin_metrics::load_plugin_metrics_operations; use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; use crate::startup_sync::curated_plugins_api_marketplace_path; use crate::startup_sync::curated_plugins_repo_path; @@ -16,7 +13,6 @@ use crate::startup_sync::read_curated_plugins_sha; use crate::store::DEFAULT_PLUGIN_VERSION; use crate::store::PluginStore; use crate::store::plugin_version_for_source; -use crate::store::validate_plugin_version_segment; use codex_exec_server::ExecutorFileSystem; use codex_exec_server::GetMetadataOptions; use codex_exec_server::ReadFileOptions; @@ -26,9 +22,7 @@ use codex_shell_command::bash::extract_bash_command; use codex_shell_command::bash::parse_shell_lc_plain_commands; use codex_shell_command::parse_command::is_pathish; use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; -use std::collections::BTreeMap; use std::collections::HashSet; use std::path::Component; use std::path::Path; @@ -38,10 +32,9 @@ struct TrustedPluginRoot { plugin_id: PluginId, version: String, root: AbsolutePathBuf, - metrics_operations_by_path: BTreeMap, } -/// Trusted plugin command attribution safe to carry into command analytics. +/// Trusted plugin command attribution carried into local command events. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PluginCommandAttribution { pub plugin_id: PluginId, @@ -66,63 +59,6 @@ pub struct TrustedPluginRoots { roots: Vec, } -/// An untrusted hint from a canonical executor script path, never authorization. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PluginMeasurementTarget { - pub(crate) plugin_id: PluginId, - pub(crate) version: String, - pub(crate) path_convention: PathConvention, -} - -impl PluginMeasurementTarget { - /// Selects one remote plugin using the same command parser as attribution. - /// Skip paths outside the remote plugin cache before consulting the executor. - pub async fn from_command( - command: &[String], - cwd: &PathUri, - file_system: &dyn ExecutorFileSystem, - ) -> Option { - let command = single_plain_command(command)?; - let invocation = script_invocation(&command)?; - let script = cwd.join(invocation.script).ok()?; - Self::from_script_path(&script)?; - let script = file_system - .canonicalize(&script, /*sandbox*/ None) - .await - .ok()?; - Self::from_script_path(&script) - } - - fn from_script_path(script: &PathUri) -> Option { - let path_convention = script.infer_path_convention()?; - let native_path = script.inferred_native_path_string(); - // Normalize only the hint so equivalent Windows paths share preparation. - // Store identities must retain the authenticated catalog's spelling. - let native_path = match path_convention { - PathConvention::Windows => native_path.to_ascii_lowercase(), - PathConvention::Posix => native_path, - }; - let components = path_convention - .path_segments(&native_path) - .collect::>(); - let mut candidates = components.windows(6).filter_map(|parts| { - if parts[..3] != ["plugins", "cache", REMOTE_GLOBAL_MARKETPLACE_NAME] - || parts[4] == DEFAULT_PLUGIN_VERSION - { - return None; - } - validate_plugin_version_segment(parts[4]).ok()?; - Some(Self { - plugin_id: PluginId::new(parts[3].to_owned(), parts[2].to_owned()).ok()?, - version: parts[4].to_owned(), - path_convention, - }) - }); - let target = candidates.next()?; - candidates.next().is_none().then_some(target) - } -} - impl TrustedPluginRoots { /// Adds already-trusted roots, preserving the existing root for each plugin and version. /// Distinct versions remain eligible for exact executor-version matching. @@ -167,8 +103,6 @@ impl TrustedPluginRoots { root.as_path().is_dir().then(|| TrustedPluginRoot { plugin_id, version, - metrics_operations_by_path: load_plugin_metrics_operations(&root) - .unwrap_or_default(), root, }) }) @@ -258,15 +192,6 @@ impl TrustedPluginRoots { .map(|candidate| candidate.attribution()) } - /// Resolves one exact command to one trusted manifest-declared operation. - pub fn resolve_metrics_operation( - &self, - command: &[String], - cwd: &AbsolutePathBuf, - ) -> Option { - self.local_candidate(command, cwd)?.metrics_operation() - } - fn local_candidate( &self, command: &[String], @@ -312,31 +237,16 @@ impl TrustedPluginRoots { cwd: &PathUri, file_system: &dyn ExecutorFileSystem, ) -> Option { - self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Any) + self.executor_candidate(command, cwd, file_system) .await .map(|candidate| candidate.matched.attribution()) } - /// Resolves one trusted executor script to one manifest-declared operation, - /// requiring the executor's version to match the trusted declaration's version. - pub async fn resolve_metrics_operation_in_filesystem( - &self, - command: &[String], - cwd: &PathUri, - file_system: &dyn ExecutorFileSystem, - ) -> Option { - self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Exact) - .await? - .matched - .metrics_operation() - } - async fn executor_candidate( &self, command: &[String], cwd: &PathUri, file_system: &dyn ExecutorFileSystem, - version_match: PluginVersionMatch, ) -> Option> { if self.roots.is_empty() { return None; @@ -349,7 +259,7 @@ impl TrustedPluginRoots { let suffixes = normalized_script_suffixes(&script); if !self.roots.iter().any(|root| { suffixes.iter().any(|suffix| { - executor_plugin_root_matches(&script, root, suffix, PluginVersionMatch::Any) + executor_plugin_root_matches(&script, root, suffix) || root.root.join(suffix).as_path().is_file() }) }) { @@ -359,7 +269,7 @@ impl TrustedPluginRoots { .canonicalize(&script, /*sandbox*/ None) .await .ok()?; - let candidates = self.local_candidates_for_executor_script(&script, version_match); + let candidates = self.local_candidates_for_executor_script(&script); if candidates.is_empty() { return None; } @@ -386,25 +296,21 @@ impl TrustedPluginRoots { .into_iter() .filter(|candidate| contents == candidate.contents); let candidate = matches.next()?; - match version_match { - PluginVersionMatch::Any => matches - .all(|other| other.matched.attribution() == candidate.matched.attribution()) - .then_some(candidate), - PluginVersionMatch::Exact => matches.next().is_none().then_some(candidate), - } + matches + .all(|other| other.matched.attribution() == candidate.matched.attribution()) + .then_some(candidate) } fn local_candidates_for_executor_script( &self, script: &PathUri, - version_match: PluginVersionMatch, ) -> Vec> { let suffixes = normalized_script_suffixes(script); self.roots .iter() .filter_map(|root| { let (script, normalized_relative_path) = suffixes.iter().find_map(|suffix| { - if !executor_plugin_root_matches(script, root, suffix, version_match) { + if !executor_plugin_root_matches(script, root, suffix) { return None; } let script = root.root.join(suffix).canonicalize().ok()?; @@ -439,17 +345,6 @@ impl MatchedPluginScript<'_> { normalized_relative_path: self.normalized_relative_path.clone(), } } - - fn metrics_operation(&self) -> Option { - Some(ResolvedPluginMetricsOperation { - plugin_id: self.root.plugin_id.clone(), - operation: self - .root - .metrics_operations_by_path - .get(&self.normalized_relative_path)? - .clone(), - }) - } } struct ExecutorAttributionCandidate<'a> { @@ -457,12 +352,6 @@ struct ExecutorAttributionCandidate<'a> { contents: Vec, } -#[derive(Clone, Copy)] -enum PluginVersionMatch { - Any, - Exact, -} - fn normalized_script_suffixes(script: &PathUri) -> Vec { let path = script.inferred_native_path_string().replace('\\', "/"); let components = path @@ -481,7 +370,6 @@ fn executor_plugin_root_matches( script: &PathUri, trusted: &TrustedPluginRoot, relative_path: &str, - version_match: PluginVersionMatch, ) -> bool { let relative_depth = relative_path.split('/').count(); let Some(root) = script.ancestors().nth(relative_depth) else { @@ -496,12 +384,7 @@ fn executor_plugin_root_matches( )) else { return false; }; - match version_match { - PluginVersionMatch::Any => root.parent().as_ref() == Some(&plugin_root), - PluginVersionMatch::Exact => plugin_root - .join(&trusted.version) - .is_ok_and(|expected| expected == root), - } + root.parent().as_ref() == Some(&plugin_root) } /// Returns the structurally parsed arguments following a single script command. diff --git a/codex-rs/core-plugins/src/script_attribution_tests.rs b/codex-rs/core-plugins/src/script_attribution_tests.rs index b4fc63ab..7c77cd05 100644 --- a/codex-rs/core-plugins/src/script_attribution_tests.rs +++ b/codex-rs/core-plugins/src/script_attribution_tests.rs @@ -1,6 +1,5 @@ use super::*; use crate::LoadedPlugin; -use crate::PluginMeasurementDefinition; use crate::loader::curated_plugin_cache_version; use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; use crate::startup_sync::curated_plugins_repo_path; @@ -22,8 +21,6 @@ use codex_utils_plugins::SkillDiscoveryMode; use futures::FutureExt; use futures::future::BoxFuture; use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::HashSet; use std::fs; @@ -161,7 +158,6 @@ fn resolves_primary_runtime_scripts_from_the_installed_plugin_cache() { roots: vec![TrustedPluginRoot { plugin_id: plugin_id.clone(), version: "0.1.29".to_string(), - metrics_operations_by_path: BTreeMap::new(), root: plugin_root.canonicalize().expect("canonical plugin root"), }], }; @@ -245,7 +241,6 @@ fn recognizes_windows_executor_plugin_cache_root() { plugin_id: PluginId::parse("presentations@openai-primary-runtime").expect("plugin id"), version: "0.1.29".to_string(), root: path(reference.path()), - metrics_operations_by_path: BTreeMap::new(), }; let relative_path = "skills/presentations/container_tools/mark_artifact_operation_started.mjs"; let script = PathUri::parse( @@ -256,38 +251,18 @@ fn recognizes_windows_executor_plugin_cache_root() { assert!(executor_plugin_root_matches( &script, &trusted, - relative_path, - PluginVersionMatch::Exact, + relative_path )); - let wrong_version = PathUri::parse( - "file:///C:/Users/user/.codex/plugins/cache/openai-primary-runtime/presentations/0.1.28/skills/presentations/container_tools/mark_artifact_operation_started.mjs", + let other_plugin = PathUri::parse( + "file:///C:/Users/user/.codex/plugins/cache/openai-primary-runtime/other/0.1.29/skills/presentations/container_tools/mark_artifact_operation_started.mjs", ) - .expect("other-version Windows script URI"); + .expect("other-plugin Windows script URI"); assert!(!executor_plugin_root_matches( - &wrong_version, + &other_plugin, &trusted, - relative_path, - PluginVersionMatch::Exact, + relative_path )); } -fn assert_invalid_metrics_manifest(codex_home: &Path, root: &AbsolutePathBuf, manifest: &str) { - fs::write(root.join("analytics.yaml"), manifest).expect("write analytics manifest"); - let roots = roots_for( - codex_home, - vec![loaded_plugin( - "sample@openai-curated", - root.as_path(), - ENABLED, - )], - ); - roots - .resolve_attribution(&command(&["scripts/run.py"]), root) - .expect("Part 1 attribution remains enabled"); - assert_eq!( - roots.resolve_metrics_operation(&command(&["scripts/run.py"]), root), - None - ); -} fn assert_untrusted(codex_home: &Path, config_name: &str, root: &Path) { assert!( roots_for(codex_home, vec![loaded_plugin(config_name, root, ENABLED)]) @@ -348,20 +323,17 @@ fn trusted_roots_require_verified_curated_or_remote_cache() { TrustedPluginRoot { plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"), version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA), - metrics_operations_by_path: BTreeMap::new(), root: root.canonicalize().expect("canonical root"), }, TrustedPluginRoot { plugin_id: PluginId::parse("api-sample@openai-api-curated").expect("plugin id"), version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA), - metrics_operations_by_path: BTreeMap::new(), root: api_root.canonicalize().expect("canonical root"), }, TrustedPluginRoot { plugin_id: PluginId::parse("remote-sample@openai-curated-remote") .expect("plugin id"), version: "1.2.3".to_string(), - metrics_operations_by_path: BTreeMap::new(), root: remote_root.canonicalize().expect("canonical root"), }, ] @@ -407,184 +379,6 @@ fn trusted_roots_require_verified_curated_or_remote_cache() { ); } -#[test] -fn resolves_manifest_operation_for_exact_attributed_script() { - let (temp, root, _) = script_fixture(); - fs::write( - root.join("analytics.yaml"), - r#"version: 1 -operations: - security_scan: - path: ./scripts/run.py - measurements: - repository_files: {} - findings: - dimensions: - severity: [critical, high, medium, low] -"#, - ) - .expect("write analytics manifest"); - let roots = roots_for( - temp.path(), - vec![loaded_plugin( - "sample@openai-curated", - root.as_path(), - ENABLED, - )], - ); - assert_eq!( - roots.resolve_metrics_operation(&command(&["scripts/run.py"]), &root), - Some(ResolvedPluginMetricsOperation { - plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"), - operation: PluginMetricsOperation { - operation_name: "security_scan".to_string(), - measurements: BTreeMap::from([ - ( - "findings".to_string(), - PluginMeasurementDefinition { - enum_dimensions: BTreeMap::from([( - "severity".to_string(), - BTreeSet::from([ - "critical".to_string(), - "high".to_string(), - "low".to_string(), - "medium".to_string(), - ]), - )]), - }, - ), - ( - "repository_files".to_string(), - PluginMeasurementDefinition { - enum_dimensions: BTreeMap::new(), - }, - ), - ]), - }, - }) - ); - - let undeclared_script = root.join("scripts/undeclared.py"); - fs::write(undeclared_script.as_path(), "print('ok')\n").expect("write undeclared script"); - roots - .resolve_attribution(&command(&["scripts/undeclared.py"]), &root) - .expect("trusted attribution"); - assert_eq!( - roots.resolve_metrics_operation(&command(&["scripts/undeclared.py"]), &root), - None - ); -} - -#[test] -fn allows_measurement_names_reused_across_operations() { - let (temp, root, _) = script_fixture(); - let other_script = root.join("scripts/other.py"); - fs::write(other_script.as_path(), "#!/usr/bin/env python3\n").expect("write script"); - fs::write( - root.join("analytics.yaml"), - r#"version: 1 -operations: - first: - path: ./scripts/run.py - measurements: - count: {} - second: - path: ./scripts/other.py - measurements: - count: {} -"#, - ) - .expect("write analytics manifest"); - let roots = roots_for( - temp.path(), - vec![loaded_plugin( - "sample@openai-curated", - root.as_path(), - ENABLED, - )], - ); - - for (script, operation_name) in [("scripts/run.py", "first"), ("scripts/other.py", "second")] { - let resolved = roots - .resolve_metrics_operation(&command(&[script]), &root) - .expect("resolved metrics operation"); - assert_eq!(resolved.operation.operation_name, operation_name); - assert!(resolved.operation.measurements.contains_key("count")); - } -} - -#[test] -fn invalid_manifest_disables_metrics_without_disabling_attribution() { - let (temp, root, _) = script_fixture(); - let invalid_manifests = [ - r#"version: 2 -operations: {scan: {path: scripts/run.py, measurements: {count: {}}}} -"#, - r#"version: 1 -unknown: true -operations: {scan: {path: scripts/run.py, measurements: {count: {}}}} -"#, - r#"version: 1 -operations: - scan: {path: scripts/run.py, measurements: {count: {}}} - scan: {path: scripts/run.py, measurements: {count: {}}} -"#, - r#"version: 1 -operations: - scan: - path: scripts/run.py - measurements: - count: {} - count: {} -"#, - r#"version: 1 -operations: - scan: - path: ../outside.py - measurements: - count: {} -"#, - r#"version: 1 -operations: {scan: {path: scripts/run.py, measurements: {count: {dimensions: {status: ["needs review"]}}}}} -"#, - r#"version: 1 -operations: {BadName: {path: scripts/run.py, measurements: {count: {}}}} -"#, - r#"version: 1 -operations: {scan: {path: scripts/run.py, measurements: {count: {}}}, scan_again: {path: ./scripts/run.py, measurements: {count: {}}}} -"#, - ]; - - for manifest in invalid_manifests { - assert_invalid_metrics_manifest(temp.path(), &root, manifest); - } - - let oversized_manifest = format!( - "version: 1\noperations: {{scan: {{path: scripts/run.py, measurements: {{count: {{}}}}}}}}\n#{}", - "x".repeat(64 * 1024) - ); - assert_invalid_metrics_manifest(temp.path(), &root, &oversized_manifest); - - #[cfg(unix)] - { - let outside = temp.path().join("outside.py"); - fs::write(&outside, "print('outside')\n").expect("write outside script"); - std::os::unix::fs::symlink(&outside, root.join("scripts/escape.py")) - .expect("symlink script"); - assert_invalid_metrics_manifest( - temp.path(), - &root, - r#"version: 1 -operations: - scan: - path: scripts/escape.py - measurements: - count: {} -"#, - ); - } -} - #[test] fn resolves_local_attribution_for_safe_interpreters_and_wrappers() { let (temp, root, script) = script_fixture(); @@ -681,13 +475,11 @@ fn rejects_ambiguous_commands_overlaps_and_symlink_escapes() { TrustedPluginRoot { plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"), version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA), - metrics_operations_by_path: BTreeMap::new(), root: root.canonicalize().expect("canonical root"), }, TrustedPluginRoot { plugin_id: PluginId::parse("nested@openai-curated").expect("plugin id"), version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA), - metrics_operations_by_path: BTreeMap::new(), root: root.join("scripts").canonicalize().expect("nested root"), }, ], @@ -722,51 +514,24 @@ fn rejects_ambiguous_commands_overlaps_and_symlink_escapes() { const REFERENCE_HELPER: &str = "scripts/install-dependencies.sh"; -fn reference_metrics_operation(variant: &str) -> PluginMetricsOperation { - PluginMetricsOperation { - operation_name: "dependency_install".to_string(), - measurements: BTreeMap::from([( - "duration_ms".to_string(), - PluginMeasurementDefinition { - enum_dimensions: BTreeMap::from([( - "variant".to_string(), - BTreeSet::from([variant.to_string()]), - )]), - }, - )]), - } -} - -fn reference_identity_fixture(root: &Path, variant: &str, contents: &str) -> AbsolutePathBuf { +fn reference_identity_fixture(root: &Path, contents: &str) -> AbsolutePathBuf { fs::create_dir_all(root.join("scripts")).expect("create reference scripts"); fs::write(root.join(REFERENCE_HELPER), contents).expect("write helper"); - fs::write( - root.join("analytics.yaml"), - format!( - "version: 1\noperations:\n dependency_install:\n path: ./{REFERENCE_HELPER}\n measurements:\n duration_ms:\n dimensions:\n variant: [{variant}]\n" - ), - ) - .expect("write operation manifest"); path(root).canonicalize().expect("canonical reference root") } -fn reference_fixture(bundles: &[(&str, &str, &str, &str)]) -> (TempDir, TrustedPluginRoots) { +fn reference_fixture(bundles: &[(&str, &str, &str)]) -> (TempDir, TrustedPluginRoots) { let home = TempDir::new().expect("references"); let roots = TrustedPluginRoots { roots: bundles .iter() - .map(|(name, version, variant, contents)| { - let root = reference_identity_fixture( - &home.path().join(name).join(version), - variant, - contents, - ); + .map(|(name, version, contents)| { + let root = + reference_identity_fixture(&home.path().join(name).join(version), contents); TrustedPluginRoot { plugin_id: PluginId::parse(&format!("{name}@openai-curated-remote")) .expect("plugin id"), version: version.to_string(), - metrics_operations_by_path: load_plugin_metrics_operations(&root) - .expect("valid fixture analytics"), root, } }) @@ -780,19 +545,16 @@ fn executor_plugin(home: &Path, name: &str, version: &str, contents: &str) -> Ab &home.join(format!( "plugins/cache/openai-curated-remote/{name}/{version}" )), - "untrusted_executor_metadata", contents, ) } -// Check both APIs: ordinary attribution can survive version differences, while -// measurements must use the exact authenticated declaration (never executor YAML). +// Ordinary attribution can survive version differences. async fn assert_executor_resolution( roots: &TrustedPluginRoots, command: &[String], cwd: &PathUri, plugin_id: &PluginId, - variant: Option<&str>, ) { assert_eq!( roots @@ -804,123 +566,15 @@ async fn assert_executor_resolution( }), "attribution for {command:?} at {cwd:?}" ); - assert_eq!( - roots - .resolve_metrics_operation_in_filesystem(command, cwd, LOCAL_FS.as_ref()) - .await, - variant.map(|variant| ResolvedPluginMetricsOperation { - plugin_id: plugin_id.clone(), - operation: reference_metrics_operation(variant), - }), - "measurements for {command:?} at {cwd:?}" - ); -} - -#[test] -fn executor_cache_identity_obeys_windows_and_posix_case_conventions() { - let (_reference, roots) = - reference_fixture(&[("sites", "2.0.0-RC1", "selected", "printf shared\\n\n")]); - let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id"); - for prefix in ["file:///C:/Users/user/.codex", "file://server/share/.codex"] { - let script = PathUri::parse(&format!( - "{prefix}/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc1/{REFERENCE_HELPER}" - )) - .expect("Windows script"); - let target = PluginMeasurementTarget::from_script_path(&script) - .expect("Windows cache preselection follows the resolver's path identity"); - assert_eq!( - target, - PluginMeasurementTarget { - plugin_id: plugin_id.clone(), - version: "2.0.0-rc1".to_string(), - path_convention: PathConvention::Windows, - } - ); - let equivalent = PathUri::parse(&format!( - "{prefix}/plugins/cache/openai-curated-remote/sites/2.0.0-RC1/{REFERENCE_HELPER}" - )) - .expect("equivalent Windows script"); - assert_eq!( - PluginMeasurementTarget::from_script_path(&equivalent), - Some(target) - ); - let candidates = - roots.local_candidates_for_executor_script(&script, PluginVersionMatch::Exact); - let candidate = candidates - .first() - .expect("Windows identity casing must not prevent canonicalization"); - assert_eq!( - candidate.matched.metrics_operation(), - Some(ResolvedPluginMetricsOperation { - plugin_id: plugin_id.clone(), - operation: reference_metrics_operation("selected"), - }) - ); - } - for script in [ - format!( - "file:///home/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc1/{REFERENCE_HELPER}" - ), - format!( - "file:///home/user/.codex/plugins/cache/openai-curated-remote/SITES/2.0.0-RC1/{REFERENCE_HELPER}" - ), - format!( - "file:///C:/Users/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc2/{REFERENCE_HELPER}" - ), - format!( - "file:///C:/Users/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/OTHER/2.0.0-rc1/{REFERENCE_HELPER}" - ), - ] { - let script = PathUri::parse(&script).expect("script"); - let path_convention = script.infer_path_convention().expect("path convention"); - let expected = PluginMeasurementTarget { - plugin_id: plugin_id.clone(), - version: match path_convention { - PathConvention::Windows => "2.0.0-rc1", - PathConvention::Posix => "2.0.0-RC1", - } - .to_string(), - path_convention, - }; - assert_ne!( - PluginMeasurementTarget::from_script_path(&script), - Some(expected), - "preselection must not match a differently cased POSIX identity or another version" - ); - assert!( - roots - .local_candidates_for_executor_script(&script, PluginVersionMatch::Exact) - .is_empty(), - "POSIX casing and different Windows versions must remain distinct" - ); - } - for version in ["2.0.0-RC1", "2.0.0-rc1"] { - let script = PathUri::parse(&format!( - "file:///home/user/.codex/plugins/cache/openai-curated-remote/sites/{version}/{REFERENCE_HELPER}" - )) - .expect("POSIX script"); - let target = - PluginMeasurementTarget::from_script_path(&script).expect("POSIX cache preselection"); - assert_eq!( - target, - PluginMeasurementTarget { - plugin_id: plugin_id.clone(), - version: version.to_string(), - path_convention: PathConvention::Posix, - } - ); - } } #[test] fn extending_trusted_roots_preserves_existing_plugins_and_deduplicates_snapshots() { let contents = "printf shared\\n\n"; - let (_frontend, mut roots) = reference_fixture(&[("sites", "1.2.3", "primary", contents)]); + let (_frontend, mut roots) = reference_fixture(&[("sites", "1.2.3", contents)]); let original = roots.clone(); - let (_snapshot, additional) = reference_fixture(&[ - ("sites", "1.2.3", "copied", contents), - ("other", "1.2.3", "additional", contents), - ]); + let (_snapshot, additional) = + reference_fixture(&[("sites", "1.2.3", contents), ("other", "1.2.3", contents)]); roots.extend(&additional); let expected = TrustedPluginRoots { @@ -931,56 +585,14 @@ fn extending_trusted_roots_preserves_existing_plugins_and_deduplicates_snapshots assert_eq!(roots, expected, "repeated snapshots must remain idempotent"); } -#[tokio::test] -async fn authenticated_v2_reference_coexists_with_loaded_frontend_v1() { - let frontend = TempDir::new().expect("frontend"); - let v1 = installed_remote_plugin_root(frontend.path(), "sites"); - reference_identity_fixture(v1.as_path(), "install_v1", "printf v1\\n\n"); - let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id"); - let mut roots = roots_for( - frontend.path(), - vec![loaded_plugin(&plugin_id.as_key(), v1.as_path(), ENABLED)], - ); - let (_reference, references) = - reference_fixture(&[("sites", "2.0.0", "install_v2", "printf v2\\n\n")]); - roots.extend(&references); - // The operation must stay bound to the selected root when two versions share - // a plugin ID and helper path, for both local and executor resolution. - for (root, variant) in [ - (&v1, "install_v1"), - (&references.roots[0].root, "install_v2"), - ] { - assert_eq!( - roots.resolve_metrics_operation(&command(&["sh", REFERENCE_HELPER]), root), - Some(ResolvedPluginMetricsOperation { - plugin_id: plugin_id.clone(), - operation: reference_metrics_operation(variant), - }) - ); - } - let executor = TempDir::new().expect("executor"); - let root = executor_plugin(executor.path(), "sites", "2.0.0", "printf v2\\n\n"); - let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI"); - assert_executor_resolution( - &roots, - &command(&["sh", REFERENCE_HELPER]), - &cwd, - &plugin_id, - Some("install_v2"), - ) - .await; -} - #[tokio::test] async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() { // Identical bytes: neither suffix nor content identifies a plugin. let contents = "printf shared\\n\n"; - let (_reference, roots) = reference_fixture(&[ - ("sites", "2.0.0", "sites_install", contents), - ("other", "2.0.0", "other_install", contents), - ]); + let (_reference, roots) = + reference_fixture(&[("sites", "2.0.0", contents), ("other", "2.0.0", contents)]); let executor = TempDir::new().expect("executor"); - for (name, variant) in [("sites", "sites_install"), ("other", "other_install")] { + for name in ["sites", "other"] { let root = executor_plugin(executor.path(), name, "2.0.0", contents); let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI"); let plugin_id = @@ -990,96 +602,17 @@ async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() { &command(&["sh", REFERENCE_HELPER]), &cwd, &plugin_id, - Some(variant), ) .await; } } -#[tokio::test] -async fn identical_script_bytes_do_not_authorize_another_executor_version() { - let contents = "printf shared\\n\n"; - let (_reference, roots) = - reference_fixture(&[("sites", "2.0.0", "v2_only_operation", contents)]); - let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id"); - let executor = TempDir::new().expect("executor"); - for version in ["1.2.3", "2.0.0"] { - let root = executor_plugin(executor.path(), "sites", version, contents); - let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI"); - let candidate = command(&["bash", "-lc", &format!("sh {REFERENCE_HELPER}")]); - assert_eq!( - PluginMeasurementTarget::from_command(&candidate, &cwd, LOCAL_FS.as_ref()).await, - Some(PluginMeasurementTarget { - plugin_id: plugin_id.clone(), - version: version.to_string(), - path_convention: PathConvention::native(), - }) - ); - assert_executor_resolution( - &roots, - &command(&["sh", REFERENCE_HELPER]), - &cwd, - &plugin_id, - (version == "2.0.0").then_some("v2_only_operation"), - ) - .await; - } -} - -#[cfg(unix)] -#[tokio::test] -async fn executor_symlink_cannot_change_authenticated_plugin_or_version() { - let contents = "printf shared\\n\n"; - let (_reference, roots) = - reference_fixture(&[("sites", "2.0.0", "v2_only_operation", contents)]); - let executor = TempDir::new().expect("executor"); - let original = executor - .path() - .join("plugins/cache/openai-curated-remote/sites/2.0.0"); - fs::create_dir_all(original.join("scripts")).expect("original scripts directory"); - let cwd = PathUri::from_host_native_path(&original).expect("original executor URI"); - for target_identity in [ - "openai-curated-remote/other/2.0.0", - "openai-curated-remote/sites/1.2.3", - "openai-curated/sites/2.0.0", - "../outside-cache", - ] { - let target = reference_identity_fixture( - &executor.path().join("plugins/cache").join(target_identity), - "ignored_executor_metadata", - contents, - ); - std::os::unix::fs::symlink( - target.join(REFERENCE_HELPER), - original.join(REFERENCE_HELPER), - ) - .expect("redirect helper to another identity"); - assert_eq!( - roots - .resolve_metrics_operation_in_filesystem( - &command(&["sh", REFERENCE_HELPER]), - &cwd, - LOCAL_FS.as_ref(), - ) - .await, - None, - "canonical identity changed to {target_identity}" - ); - fs::remove_file(original.join(REFERENCE_HELPER)).expect("remove helper symlink"); - } -} - #[cfg(unix)] #[tokio::test] async fn executor_aliases_use_canonical_plugin_paths() { let contents = "printf shared\\n\n"; - let (_reference, roots) = reference_fixture(&[ - ("sites", "1.2.3", "older", contents), - ("sites", "2.0.0", "selected", contents), - ]); - let older_roots = TrustedPluginRoots { - roots: vec![roots.roots[0].clone()], - }; + let (_reference, roots) = + reference_fixture(&[("sites", "1.2.3", contents), ("sites", "2.0.0", contents)]); let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id"); let executor = TempDir::new().expect("executor"); let target = executor_plugin(executor.path(), "sites", "2.0.0", contents); @@ -1098,48 +631,10 @@ async fn executor_aliases_use_canonical_plugin_paths() { &command(&["sh", &alias.join(REFERENCE_HELPER).to_string_lossy()]), &cwd, &plugin_id, - Some("selected"), ) .await; let command = command(&["sh", &version_alias.to_string_lossy()]); - assert_eq!( - PluginMeasurementTarget::from_command(&command, &cwd, LOCAL_FS.as_ref()).await, - Some(PluginMeasurementTarget { - plugin_id: plugin_id.clone(), - version: "2.0.0".to_string(), - path_convention: PathConvention::Posix, - }) - ); - assert_executor_resolution(&roots, &command, &cwd, &plugin_id, Some("selected")).await; - assert_eq!( - older_roots - .resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref()) - .await, - None, - "a V1-shaped alias and identical bytes cannot authorize V2 metrics" - ); -} - -#[tokio::test] -async fn measurement_target_rejects_inline_commands_and_local_versions() -> anyhow::Result<()> { - let executor = TempDir::new()?; - let root = reference_identity_fixture( - &executor - .path() - .join("plugins/cache/openai-curated-remote/sites/local"), - "ignored", - "printf fixture\n", - ); - let cwd = PathUri::from_host_native_path(root.as_path())?; - for args in [&["node", "-e", "42"][..], &["sh", REFERENCE_HELPER][..]] { - let command = command(args); - let fs = codex_exec_server::LOCAL_FS.as_ref(); - assert_eq!( - PluginMeasurementTarget::from_command(&command, &cwd, fs).await, - None - ); - } - Ok(()) + assert_executor_resolution(&roots, &command, &cwd, &plugin_id).await; } struct UnusedConnectProvider; @@ -1155,8 +650,7 @@ impl NoiseRendezvousConnectProvider for UnusedConnectProvider { #[tokio::test] async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> { - let (_reference, roots) = - reference_fixture(&[("sites", "2.0.0", "selected", "printf shared\\n\n")]); + let (_reference, roots) = reference_fixture(&[("sites", "2.0.0", "printf shared\\n\n")]); let manager = environment_manager_without_environments(); let pending = manager.materialize_pending_noise_environment( "tools".to_string(), @@ -1167,13 +661,10 @@ async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> { let command = command(&["node", "build.js"]); // An executor lookup waits for provisioning; unrelated scripts must finish immediately. assert_eq!( - futures::future::join3( - roots.resolve_executor_attribution(&command, &cwd, fs.as_ref()), - roots.resolve_metrics_operation_in_filesystem(&command, &cwd, fs.as_ref()), - PluginMeasurementTarget::from_command(&command, &cwd, fs.as_ref()), - ) - .now_or_never(), - Some((None, None, None)), + roots + .resolve_executor_attribution(&command, &cwd, fs.as_ref()) + .now_or_never(), + Some(None), ); Ok(()) } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index a9acbcdf..4d47e8e5 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -19,7 +19,6 @@ async-channel = { workspace = true } base64 = { workspace = true } bm25 = { workspace = true } chrono = { workspace = true, features = ["serde"] } -codex-analytics = { workspace = true } codex-agent-graph-store = { workspace = true } codex-agent-roles = { workspace = true } codex-api = { workspace = true } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index dabd2be1..34ac7d91 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -112,17 +112,6 @@ } ] }, - "AnalyticsConfigToml": { - "additionalProperties": false, - "description": "Analytics settings loaded from config.toml. Fields are optional so we can apply defaults.", - "properties": { - "enabled": { - "description": "When `false`, disables OpenAI analytics across Codex product surfaces in this profile. Custom OTLP metrics exporters remain enabled; set `otel.metrics_exporter = \"none\"` to disable them.", - "type": "boolean" - } - }, - "type": "object" - }, "AppConfig": { "additionalProperties": false, "description": "Config values for a single app/connector.", @@ -784,9 +773,6 @@ "additionalProperties": false, "description": "Collection of common configuration options that a user can define as a unit in `config.toml`.", "properties": { - "analytics": { - "$ref": "#/definitions/AnalyticsConfigToml" - }, "approval_policy": { "$ref": "#/definitions/AskForApproval" }, @@ -1954,7 +1940,7 @@ "additionalProperties": false, "properties": { "enabled": { - "description": "When `false`, disables feedback uploads and background Guardian review retention. Explicit local exports remain available.", + "description": "When `false`, disables feedback collection and background Guardian review retention. Explicit local exports remain available.", "type": "boolean" } }, @@ -3913,52 +3899,16 @@ "type": "object" }, "OtelConfigToml": { - "additionalProperties": false, - "description": "OTEL settings loaded from config.toml. Fields are optional so we can apply defaults.", + "description": "Local logging settings kept under the historical `[otel]` table.\n\naKode never exports telemetry. The former exporter keys (`exporter`, `trace_exporter`, `metrics_exporter`, `environment`, `span_attributes`, `tracestate`, `log_agent_responses`, `log_guardian_assessments`) are still accepted in `config.toml` for compatibility but are ignored.", "properties": { - "environment": { - "description": "Mark traces with environment (dev, staging, prod, test). Defaults to dev.", - "type": "string" - }, - "exporter": { - "allOf": [ - { - "$ref": "#/definitions/OtelExporterKind" - } - ], - "description": "Optional log exporter" - }, - "log_agent_responses": { - "description": "Opt in to logging final main-agent and spawned-subagent responses to an OTLP log exporter. Defaults to false. Response text can be sensitive and is capped at 64 KiB.", - "type": "boolean" - }, - "log_guardian_assessments": { - "description": "Opt in to logging completed Guardian assessments to an OTLP log exporter. Defaults to false. Rationales can be sensitive and are capped at 64 KiB.", - "type": "boolean" - }, "log_sse_deltas": { - "description": "Log successful SSE events whose kind ends in `.delta`. Defaults to true. Disabling this preserves errors, completion events, and metrics.", + "description": "Log successful SSE events whose kind ends in `.delta`. Defaults to true. Disabling this preserves errors and completion events.", "type": "boolean" }, "log_user_prompt": { - "description": "Log user prompt in traces", + "description": "Include the user prompt in local log events.", "type": "boolean" }, - "metrics_exporter": { - "allOf": [ - { - "$ref": "#/definitions/OtelExporterKind" - } - ], - "description": "Metrics exporter. Defaults to `statsig`, which follows `analytics.enabled`. Custom OTLP exporters are independent of `analytics.enabled`; `none` disables metrics export." - }, - "span_attributes": { - "additionalProperties": { - "type": "string" - }, - "description": "Attributes to add to every exported trace span.", - "type": "object" - }, "tool_result": { "allOf": [ { @@ -3966,145 +3916,6 @@ } ], "description": "Byte limit for tool-result log output; independent of model-visible output." - }, - "trace_exporter": { - "allOf": [ - { - "$ref": "#/definitions/OtelExporterKind" - } - ], - "description": "Optional trace exporter" - }, - "tracestate": { - "additionalProperties": { - "additionalProperties": { - "type": "string" - }, - "type": "object" - }, - "description": "Semicolon-separated `key:value` fields to upsert into W3C tracestate members.", - "type": "object" - } - }, - "type": "object" - }, - "OtelExporterKind": { - "description": "Which OTEL exporter to use.", - "oneOf": [ - { - "enum": [ - "none", - "statsig" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "otlp-http": { - "additionalProperties": false, - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "default": {}, - "type": "object" - }, - "protocol": { - "$ref": "#/definitions/OtelHttpProtocol" - }, - "tls": { - "allOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - } - ], - "default": null - } - }, - "required": [ - "endpoint", - "protocol" - ], - "type": "object" - } - }, - "required": [ - "otlp-http" - ], - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "otlp-grpc": { - "additionalProperties": false, - "properties": { - "endpoint": { - "type": "string" - }, - "headers": { - "additionalProperties": { - "type": "string" - }, - "default": {}, - "type": "object" - }, - "tls": { - "allOf": [ - { - "$ref": "#/definitions/OtelTlsConfig" - } - ], - "default": null - } - }, - "required": [ - "endpoint" - ], - "type": "object" - } - }, - "required": [ - "otlp-grpc" - ], - "type": "object" - } - ] - }, - "OtelHttpProtocol": { - "oneOf": [ - { - "description": "Binary payload", - "enum": [ - "binary" - ], - "type": "string" - }, - { - "description": "JSON payload", - "enum": [ - "json" - ], - "type": "string" - } - ] - }, - "OtelTlsConfig": { - "additionalProperties": false, - "properties": { - "ca-certificate": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "client-certificate": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "client-private-key": { - "$ref": "#/definitions/AbsolutePathBuf" } }, "type": "object" @@ -7704,14 +7515,6 @@ "description": "Allow macOS sandbox writable roots at or beneath CODEX_HOME to traverse symlinks. Read only from the host's user config at startup; defaults to false. This grants no write access by itself, but trusts symlink targets even if they change between commands or lie outside CODEX_HOME. This setting has no effect on Linux or Windows.", "type": "boolean" }, - "analytics": { - "allOf": [ - { - "$ref": "#/definitions/AnalyticsConfigToml" - } - ], - "description": "When `enabled` is `false`, disables OpenAI analytics across Codex product surfaces on this machine. Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`. When unset, the default depends on the client." - }, "approval_policy": { "allOf": [ { @@ -8826,7 +8629,7 @@ "$ref": "#/definitions/OtelConfigToml" } ], - "description": "OTEL configuration." + "description": "Local logging settings (historical `[otel]` table; nothing is exported)." }, "permissions": { "allOf": [ diff --git a/codex-rs/core/src/agent/api.rs b/codex-rs/core/src/agent/api.rs index 7664a864..40190b6b 100644 --- a/codex-rs/core/src/agent/api.rs +++ b/codex-rs/core/src/agent/api.rs @@ -43,7 +43,7 @@ pub trait AgentControl: Send + Sync { /// Resolve an ID or a name relative to the caller's captured source, without loading. /// The local backend lazily registers callers with no parent before resolving, including - /// for direct IDs. Keeping resolution separate preserves tool error and analytics ordering. + /// for direct IDs. Keeping resolution separate preserves tool error ordering. fn resolve<'a>( &'a self, caller: ThreadId, diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 7449da55..cf747ec9 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -555,17 +555,8 @@ impl LocalAgentControl { ..Default::default() }) }; - let subagent_analytics = - if let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. }) = &session_source - && let Some(parent_thread_id) = parent_thread_id - && let Ok(parent) = state.get_thread(parent_thread_id).await - { - Some(parent.session.app_server_client_metadata().await) - } else { - None - }; - // Reserving a slot can evict an idle nested parent. Capture its instructions and - // analytics metadata alongside its authority before the live parent can disappear. + // Reserving a slot can evict an idle nested parent. Capture its instructions + // alongside its authority before the live parent can disappear. let residency_slot = self .reserve_v2_residency_slot(&state, &config, &membership, Some(thread_id)) .await?; @@ -598,15 +589,6 @@ impl LocalAgentControl { runtime.registry.clear_evicted_environments(thread_id); residency_slot.commit(reloaded_thread.thread_id); // Register before listeners can forward events from the resumed thread. - if let Some(client_metadata) = subagent_analytics { - reloaded_thread - .thread - .emit_subagent_session_started( - client_metadata, - Some(stored_thread.created_at), - ) - .await; - } state.notify_thread_created(reloaded_thread.thread_id); Ok(residency_pin) }) @@ -812,30 +794,6 @@ impl LocalAgentControl { .map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?; let child_create = child_create_started_at.elapsed(); agent_metadata.agent_id = Some(new_thread.thread_id); - if let Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, .. - })) = notification_source.as_ref() - { - let client_metadata = match state.get_thread(*parent_thread_id).await { - Ok(parent_thread) => parent_thread.session.app_server_client_metadata().await, - Err(error) => { - tracing::warn!( - error = %error, - parent_thread_id = %parent_thread_id, - "skipping subagent thread analytics: failed to load parent thread metadata" - ); - crate::session::session::AppServerClientMetadata { - client_name: None, - client_version: None, - } - } - }; - new_thread - .thread - .emit_subagent_session_started(client_metadata, /*resumed_created_at*/ None) - .await; - } - let durability_wait_started_at = Instant::now(); if options.fork_mode.is_some() { new_thread.thread.ensure_rollout_materialized().await; diff --git a/codex-rs/core/src/agent/control/spawn_publication_tests.rs b/codex-rs/core/src/agent/control/spawn_publication_tests.rs index 785c6392..dc631698 100644 --- a/codex-rs/core/src/agent/control/spawn_publication_tests.rs +++ b/codex-rs/core/src/agent/control/spawn_publication_tests.rs @@ -124,7 +124,6 @@ async fn publication_harness( harness.manager.environment_manager(), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, harness.manager.image_store(), crate::ThreadStoreBuilder::from_config(&harness.config, harness.state_db.clone()).build(), Some(graph.clone()), diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 9c65c797..a8d22605 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -3818,7 +3818,6 @@ async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_onc Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, crate::thread_manager::passthrough_image_store(), crate::ThreadStoreBuilder::from_config(&parent_config, harness.state_db.clone()) .build(), @@ -4979,7 +4978,6 @@ async fn resume_thread_subagent_restores_stored_metadata() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, crate::thread_manager::passthrough_image_store(), thread_store.clone(), /*agent_graph_store*/ None, diff --git a/codex-rs/core/src/agent/host/spawn.rs b/codex-rs/core/src/agent/host/spawn.rs index b0cffc5a..540a04c4 100644 --- a/codex-rs/core/src/agent/host/spawn.rs +++ b/codex-rs/core/src/agent/host/spawn.rs @@ -14,7 +14,6 @@ use crate::agent::history::prepare_forked_history; use crate::agent::types::AgentMetadata; use crate::agent::types::LiveAgent; use crate::codex_thread::CodexThread; -use crate::session::session::AppServerClientMetadata; use crate::thread_manager::StartThreadOptions; use crate::thread_spawn::ChildSpawnSettings; use crate::thread_spawn::ThreadSpawnError; @@ -32,11 +31,7 @@ use std::sync::Arc; async fn prepare_spawn_inputs( parent: &CodexThread, request: ChildSpawnSettings, -) -> Result<( - StartThreadOptions, - PreparedChildInheritance, - AppServerClientMetadata, -)> { +) -> Result<(StartThreadOptions, PreparedChildInheritance)> { let runtime = &parent.session.services.local_agent_runtime; let _membership = runtime.admit_start()?; let state = runtime.upgrade()?; @@ -87,14 +82,13 @@ async fn prepare_spawn_inputs( .thread_extension_init .insert(HostToolInvocationLookup); thread_options.inherited_environments = options.environments; - let client_metadata = parent.session.app_server_client_metadata().await; let inheritance = PreparedChildInheritance { instructions, exec_policy, originator: parent.session.originator().await, attachment_source: options.fork_mode.is_some().then_some(caller), }; - Ok((thread_options, inheritance, client_metadata)) + Ok((thread_options, inheritance)) } pub(super) async fn create_spawn( @@ -104,8 +98,7 @@ pub(super) async fn create_spawn( task_name: AgentPath, reservation: HostThreadSpawnReservation, ) -> std::result::Result { - let (mut options, inheritance, client_metadata) = - Box::pin(prepare_spawn_inputs(parent, request)).await?; + let (mut options, inheritance) = Box::pin(prepare_spawn_inputs(parent, request)).await?; let caller = parent.session.thread_id; let session_id = parent.session.session_id(); if reservation.control.identity() != session_id @@ -157,10 +150,6 @@ pub(super) async fn create_spawn( SpawnOwner::Host, ); child.thread.emit_thread_ready_lifecycle().await; - child - .thread - .emit_subagent_session_started(client_metadata, /*resumed_created_at*/ None) - .await; if child.session_configured.forked_from_id.is_some() { child.thread.ensure_rollout_materialized().await; } diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 31c65b34..0bf2be3f 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -26,7 +26,6 @@ use crate::session::GitEnrichmentPolicy; use crate::session::SUBMISSION_CHANNEL_CAPACITY; use crate::session::SessionIo; use crate::session::SessionSpawnArgs; -use crate::session::emit_subagent_session_started; use crate::session::session::Session; use crate::session::startup::SessionStartup; use crate::session::startup::SessionStartupGuard; @@ -162,7 +161,6 @@ pub(crate) async fn run_codex_thread_interactive( turn_extension_init: Default::default(), client_mcp_extensions: parent_session.services.client_mcp_extensions.clone(), reserved_thread_id: None, - analytics_events_client: Some(parent_session.services.analytics_events_client.clone()), image_store: Arc::clone(&parent_session.services.image_store), thread_store: Arc::clone(&parent_session.services.thread_store), attestation_provider: parent_session.services.attestation_provider.clone(), @@ -184,18 +182,6 @@ pub(crate) async fn run_codex_thread_interactive( return Err(error.into()); } }; - let thread_config = session.thread_config_snapshot().await; - let client_metadata = parent_session.app_server_client_metadata().await; - emit_subagent_session_started( - &session.services.analytics_events_client, - client_metadata, - session.session_id(), - session.thread_id(), - Some(parent_session.thread_id), - thread_config, - subagent_source, - /*resumed_created_at*/ None, - ); let caller_io = forward_session_io(Arc::new(io), cancel_token); startup.release_membership(); startup_guard.disarm(); diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 18719552..ae629bca 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -8,10 +8,8 @@ use crate::elicitation::ElicitationRegistration; use crate::session::SessionIo; use crate::session::SessionSettingsUpdate; use crate::session::Submission; -use crate::session::emit_subagent_session_started; use crate::session::inject::validate_injected_response_item; use crate::session::new_submission_id; -use crate::session::session::AppServerClientMetadata; use crate::session::session::Session; use crate::session::startup_prewarm::PrewarmInput; use crate::session::step_settings::StepSettingsUpdate; @@ -51,7 +49,6 @@ use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::Op; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadMemoryMode; use codex_protocol::protocol::ThreadSettingsOverrides; @@ -308,11 +305,6 @@ impl CodexThread { .await; } - /// Whether analytics is enabled for this thread after configuration and host overrides. - pub fn analytics_enabled(&self) -> bool { - self.session.services.analytics_events_client.is_enabled() - } - /// Looks up a live V2 tool invocation on a runtime with [`crate::HostToolInvocationLookup`]. pub fn tool_invocation( &self, @@ -399,29 +391,6 @@ impl CodexThread { self.io.session_loop_termination.clone().await; } - pub(crate) async fn emit_subagent_session_started( - &self, - client_metadata: AppServerClientMetadata, - resumed_created_at: Option>, - ) { - let SessionSource::SubAgent(source @ SubAgentSource::ThreadSpawn { .. }) = - &self.session_source - else { - return; - }; - let config = self.config_snapshot().await; - emit_subagent_session_started( - &self.session.services.analytics_events_client, - client_metadata, - self.session.session_id(), - self.session.thread_id(), - config.parent_thread_id, - config, - source.clone(), - resumed_created_at, - ); - } - pub(crate) async fn emit_thread_ready_lifecycle(&self) { let contributors = self .session diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index c75de916..5dd632f7 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -1,12 +1,15 @@ use crate::context::UserGoalUpdate; use std::collections::HashSet; use std::sync::Arc; -use std::time::Instant; use crate::Prompt; use crate::client::ModelClientSession; use crate::client_common::ResponseEvent; use crate::compact_pending_input::is_retained_pending_mail; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use crate::context::BaseInstructionsFragment; use crate::context::CompactionSummary; use crate::context::ContextualUserFragment; @@ -27,14 +30,6 @@ use crate::session::turn::get_last_assistant_message_from_turn; use crate::session::turn_context::TurnContext; use crate::state::AutoCompactWindowIds; use crate::util::backoff; -use codex_analytics::CodexCompactionEvent; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionStatus; -use codex_analytics::CompactionStrategy; -use codex_analytics::CompactionTrigger; -use codex_analytics::now_unix_seconds; use codex_context_fragments::AnnotatedContent; use codex_context_fragments::set_annotated_content; use codex_context_fragments::truncate_annotated_text; @@ -184,31 +179,12 @@ async fn run_compact_task_inner( compaction_metadata: CompactionTurnMetadata, ) -> CodexResult<()> { let trigger = compaction_metadata.trigger(); - let reason = compaction_metadata.reason(); let phase = compaction_metadata.phase(); - let attempt = CompactionAnalyticsAttempt::begin( - sess.as_ref(), - turn_context.as_ref(), - trigger, - reason, - CompactionImplementation::Responses, - phase, - ) - .await; let pre_compact_outcome = run_pre_compact_hooks(&sess, &turn_context, trigger).await; match pre_compact_outcome { PreCompactHookOutcome::Continue => {} PreCompactHookOutcome::Stopped => { - let error = CodexErr::TurnAborted; - attempt - .track( - sess.as_ref(), - CompactionStatus::Interrupted, - Some(&error), - CompactionAnalyticsDetails::default(), - ) - .await; - return Err(error); + return Err(CodexErr::TurnAborted); } } let result = run_compact_task_inner_impl( @@ -220,30 +196,12 @@ async fn run_compact_task_inner( compaction_metadata, ) .await; - let status = compaction_status_from_result(&result); - let codex_error = result.as_ref().err(); if result.is_ok() { let post_compact_outcome = run_post_compact_hooks(&sess, &turn_context, trigger).await; if let PostCompactHookOutcome::Stopped = post_compact_outcome { - attempt - .track( - sess.as_ref(), - status, - codex_error, - CompactionAnalyticsDetails::default(), - ) - .await; return Err(CodexErr::TurnAborted); } } - attempt - .track( - sess.as_ref(), - status, - codex_error, - CompactionAnalyticsDetails::default(), - ) - .await; if let Err(err) = &result && !matches!(phase, CompactionPhase::PostTurn) && !matches!( @@ -251,7 +209,6 @@ async fn run_compact_task_inner( CodexErrorDetails::Interrupted | CodexErrorDetails::TurnAborted ) { - sess.track_turn_codex_error(turn_context.as_ref(), err); // Pre-turn failures are reported after preserving the incoming prompt. if !matches!(phase, CompactionPhase::PreTurn) { let event = EventMsg::Error(err.to_error_event(/*message_prefix*/ None)); @@ -476,115 +433,6 @@ async fn run_compact_task_inner_impl( Ok(summary_suffix) } -pub(crate) struct CompactionAnalyticsAttempt { - thread_id: String, - turn_id: String, - trigger: CompactionTrigger, - reason: CompactionReason, - implementation: CompactionImplementation, - phase: CompactionPhase, - active_context_tokens_before: i64, - started_at: u64, - start_instant: Instant, -} - -#[derive(Clone, Copy, Default)] -pub(crate) struct CompactionAnalyticsDetails { - pub(crate) active_context_tokens_before: Option, - pub(crate) retained_image_count: Option, - pub(crate) compaction_summary_tokens: Option, - pub(crate) cached_input_tokens: Option, - pub(crate) cache_write_input_tokens: Option, -} - -impl CompactionAnalyticsAttempt { - pub(crate) async fn begin( - sess: &Session, - turn_context: &TurnContext, - trigger: CompactionTrigger, - reason: CompactionReason, - implementation: CompactionImplementation, - phase: CompactionPhase, - ) -> Self { - let active_context_tokens_before = sess.get_total_token_usage().await; - Self { - thread_id: sess.thread_id.to_string(), - turn_id: turn_context.sub_id.clone(), - trigger, - reason, - implementation, - phase, - active_context_tokens_before, - started_at: now_unix_seconds(), - start_instant: Instant::now(), - } - } - - pub(crate) async fn track( - self, - sess: &Session, - status: CompactionStatus, - codex_error: Option<&CodexErr>, - details: CompactionAnalyticsDetails, - ) { - let CompactionAnalyticsDetails { - active_context_tokens_before, - retained_image_count, - compaction_summary_tokens, - cached_input_tokens, - cache_write_input_tokens, - } = details; - let active_context_tokens_before = - active_context_tokens_before.unwrap_or(self.active_context_tokens_before); - let active_context_tokens_after = sess.get_total_token_usage().await; - sess.services - .analytics_events_client - .track_compaction(CodexCompactionEvent { - thread_id: self.thread_id, - turn_id: self.turn_id, - trigger: self.trigger, - reason: self.reason, - implementation: self.implementation, - phase: self.phase, - strategy: CompactionStrategy::Memento, - status, - codex_error_kind: codex_error.map(Into::into), - codex_error_http_status_code: codex_error - .and_then(CodexErr::http_status_code_value), - usage_limit_window_minutes: codex_error.and_then(|error| match error.details() { - CodexErrorDetails::UsageLimitReached(error) => error.limit_window_minutes, - _ => None, - }), - active_context_tokens_before, - active_context_tokens_after, - retained_image_count, - compaction_summary_tokens, - cached_input_tokens, - cache_write_input_tokens, - started_at: self.started_at, - completed_at: now_unix_seconds(), - duration_ms: Some( - u64::try_from(self.start_instant.elapsed().as_millis()).unwrap_or(u64::MAX), - ), - }); - } -} - -pub(crate) fn compaction_status_from_result(result: &CodexResult) -> CompactionStatus { - match result { - Ok(_) => CompactionStatus::Completed, - Err(err) - if matches!( - err.details(), - CodexErrorDetails::Interrupted | CodexErrorDetails::TurnAborted - ) => - { - CompactionStatus::Interrupted - } - Err(_) => CompactionStatus::Failed, - } -} - pub fn content_items_to_text(content: &[ContentItem]) -> Option { let mut pieces = Vec::new(); for item in content { diff --git a/codex-rs/core/src/compact_model_fallback.rs b/codex-rs/core/src/compact_model_fallback.rs index 7d4c0e25..6be613cd 100644 --- a/codex-rs/core/src/compact_model_fallback.rs +++ b/codex-rs/core/src/compact_model_fallback.rs @@ -1,6 +1,6 @@ +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionReason; use crate::session::turn_context::TurnContext; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionReason; use codex_otel::SessionTelemetry; use codex_protocol::error::CodexErr; use codex_protocol::error::CodexErrorDetails; diff --git a/codex-rs/core/src/compact_remote_v2.rs b/codex-rs/core/src/compact_remote_v2.rs index 5656fb48..30e07ae2 100644 --- a/codex-rs/core/src/compact_remote_v2.rs +++ b/codex-rs/core/src/compact_remote_v2.rs @@ -11,15 +11,16 @@ use crate::client::ModelClientSession; use crate::client::ResponsesHttpExecutor; use crate::client_common::ResponseEvent; use crate::compact::CompactedHistoryMetadata; -use crate::compact::CompactionAnalyticsAttempt; -use crate::compact::CompactionAnalyticsDetails; -use crate::compact::compaction_status_from_result; use crate::compact_model_fallback::record_model_fallback; use crate::compact_model_fallback::should_retry_with_current_model; use crate::compact_pending_input::MAX_RETAINED_AGENT_MESSAGE_TOKENS; use crate::compact_pending_input::is_retained_pending_mail; use crate::compact_remote_history::HistoryItemGroup; use crate::compact_remote_history::history_item_groups; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use crate::context::world_state::WorldState; use crate::context_manager::estimate_item_token_count; use crate::context_manager::estimate_item_token_count_with_audio; @@ -36,10 +37,6 @@ use crate::session::RequestEffortUsage; use crate::session::session::Session; use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionTrigger; use codex_context_fragments::set_annotated_content; use codex_context_fragments::to_annotated_content; use codex_features::Feature; @@ -182,36 +179,12 @@ async fn run_remote_compact_task_inner( ) -> CodexResult { let turn_context = &step_context.turn; let trigger = compaction_metadata.trigger(); - let reason = compaction_metadata.reason(); - let implementation = compaction_metadata.implementation(); let phase = compaction_metadata.phase(); - let mut analytics_details = CompactionAnalyticsDetails { - active_context_tokens_before: Some(sess.get_total_token_usage().await), - ..Default::default() - }; - let attempt = CompactionAnalyticsAttempt::begin( - sess.as_ref(), - turn_context.as_ref(), - trigger, - reason, - implementation, - phase, - ) - .await; let pre_compact_outcome = run_pre_compact_hooks(sess, turn_context, trigger).await; match pre_compact_outcome { PreCompactHookOutcome::Continue => {} PreCompactHookOutcome::Stopped => { - let error = CodexErr::TurnAborted; - attempt - .track( - sess.as_ref(), - codex_analytics::CompactionStatus::Interrupted, - Some(&error), - analytics_details, - ) - .await; - return Err(error); + return Err(CodexErr::TurnAborted); } } let started_item = if candidate.is_none() { @@ -234,7 +207,6 @@ async fn run_remote_compact_task_inner( client_session, &world_state, compaction_metadata, - &mut analytics_details, started_item.as_ref(), candidate.map(|candidate| *candidate), fallback, @@ -246,20 +218,12 @@ async fn run_remote_compact_task_inner( } return Ok(false); } - let status = compaction_status_from_result(&result); - let codex_error = result.as_ref().err(); if result.is_ok() { let post_compact_outcome = run_post_compact_hooks(sess, turn_context, trigger).await; if let PostCompactHookOutcome::Stopped = post_compact_outcome { - attempt - .track(sess.as_ref(), status, codex_error, analytics_details) - .await; return Err(CodexErr::TurnAborted); } } - attempt - .track(sess.as_ref(), status, codex_error, analytics_details) - .await; match result { Ok(installed) => Ok(installed), Err(err) @@ -269,7 +233,6 @@ async fn run_remote_compact_task_inner( Err(err) } Err(err) => { - sess.track_turn_codex_error(turn_context, &err); // Pre-turn failures are reported by run_turn after preserving the incoming prompt. if !matches!(phase, CompactionPhase::PreTurn) { let event = EventMsg::Error( diff --git a/codex-rs/core/src/compact_remote_v2_attempt.rs b/codex-rs/core/src/compact_remote_v2_attempt.rs index ce2063fc..56f3c54f 100644 --- a/codex-rs/core/src/compact_remote_v2_attempt.rs +++ b/codex-rs/core/src/compact_remote_v2_attempt.rs @@ -13,8 +13,11 @@ use super::RemoteCompactionV2Output; use super::run_remote_compaction_request_v2; use crate::Prompt; use crate::client::ModelClientSession; -use crate::compact::CompactionAnalyticsDetails; use crate::compact_remote_history::trim_function_call_history_to_fit_context_window; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use crate::context::world_state::WorldState; use crate::context_manager::ContextManager; use crate::context_manager::rejected_audio; @@ -23,10 +26,6 @@ use crate::responses_metadata::CompactionTurnMetadata; use crate::session::CompactionPrefix; use crate::session::session::Session; use crate::session::step_context::StepContext; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionTrigger; use codex_history::CodexHarnessMetadata; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; @@ -77,7 +76,6 @@ pub(super) async fn run_remote_compact_v2_attempt( step_context: &Arc, compaction_trace: &CompactionTraceContext, compaction_metadata: CompactionTurnMetadata, - analytics_details: &mut CompactionAnalyticsDetails, input: RemoteCompactV2AttemptInput<'_>, ) -> CodexResult { let turn_context = &step_context.turn; @@ -106,7 +104,7 @@ pub(super) async fn run_remote_compact_v2_attempt( } else { sess.get_prompt_base_instructions().await }; - let (rewritten_outputs, estimated_deleted_tokens) = + let (rewritten_outputs, _estimated_deleted_tokens) = trim_function_call_history_to_fit_context_window( &mut history, turn_context, @@ -120,15 +118,6 @@ pub(super) async fn run_remote_compact_v2_attempt( "rewrote history outputs before remote compaction v2" ); } - if estimated_deleted_tokens > 0 { - let max_local_deleted_tokens = sess.estimated_tokens_since_last_usage().await; - analytics_details.active_context_tokens_before = analytics_details - .active_context_tokens_before - .map(|active_context_tokens_before| { - active_context_tokens_before - .saturating_sub(estimated_deleted_tokens.min(max_local_deleted_tokens)) - }); - } let trace_input_history = compaction_trace .is_enabled() .then(|| history.raw_items().cloned().collect()); @@ -355,7 +344,6 @@ pub(crate) async fn run_background_compaction( &step_context, &CompactionTraceContext::disabled(), metadata, - &mut CompactionAnalyticsDetails::default(), RemoteCompactV2AttemptInput::Background(prepared_input), ) .await?; diff --git a/codex-rs/core/src/compact_remote_v2_installation.rs b/codex-rs/core/src/compact_remote_v2_installation.rs index f14c10a0..0326c62d 100644 --- a/codex-rs/core/src/compact_remote_v2_installation.rs +++ b/codex-rs/core/src/compact_remote_v2_installation.rs @@ -21,7 +21,6 @@ pub(super) async fn run_compaction( mut client_session: Option<&mut ModelClientSession>, world_state: &WorldState, compaction_metadata: CompactionTurnMetadata, - analytics_details: &mut CompactionAnalyticsDetails, mut started_item: Option<&TurnItem>, candidate: Option, fallback: CompactionFallback, @@ -34,7 +33,6 @@ pub(super) async fn run_compaction( client_session.as_deref_mut(), world_state, compaction_metadata, - analytics_details, started_item, Some(candidate), ) @@ -62,7 +60,6 @@ pub(super) async fn run_compaction( client_session, world_state, compaction_metadata, - analytics_details, started_item, /*candidate*/ None, ) @@ -77,7 +74,6 @@ async fn build_and_install_compaction( mut client_session: Option<&mut ModelClientSession>, world_state: &WorldState, compaction_metadata: CompactionTurnMetadata, - analytics_details: &mut CompactionAnalyticsDetails, started_item: Option<&TurnItem>, candidate: Option, ) -> CodexResult { @@ -128,7 +124,6 @@ async fn build_and_install_compaction( step_context, &compaction_trace, compaction_metadata, - analytics_details, RemoteCompactV2AttemptInput::Foreground(client_session.as_deref_mut()), ) .await; @@ -153,7 +148,6 @@ async fn build_and_install_compaction( replacement_step_context, &fallback_compaction_trace, compaction_metadata, - analytics_details, RemoteCompactV2AttemptInput::Foreground(client_session), ) .await; @@ -189,9 +183,8 @@ async fn build_and_install_compaction( { sess.record_rollout_budget_usage(&compaction_turn_context.sub_id, token_usage) .await?; - analytics_details.active_context_tokens_before = Some(token_usage.input_tokens); } - let (compacted_history, retained_images) = build_v2_compacted_history( + let (compacted_history, _retained_images) = build_v2_compacted_history( prompt_input, prompt_input_metadata, compaction_output, @@ -264,13 +257,6 @@ async fn build_and_install_compaction( if !installed { return Ok(false); } - // Rejected candidates must not supply analytics for a later foreground attempt. - if let Some(token_usage) = token_usage { - analytics_details.compaction_summary_tokens = Some(token_usage.output_tokens); - analytics_details.cached_input_tokens = Some(token_usage.cached_input_tokens); - analytics_details.cache_write_input_tokens = Some(token_usage.cache_write_input_tokens); - } - analytics_details.retained_image_count = Some(retained_images); if let Some(trace_input_history) = trace_input_history.as_deref() { let replacement_history = sess .clone_history() diff --git a/codex-rs/core/src/compact_remote_v2_installation_tests.rs b/codex-rs/core/src/compact_remote_v2_installation_tests.rs index 6f8caa23..58560782 100644 --- a/codex-rs/core/src/compact_remote_v2_installation_tests.rs +++ b/codex-rs/core/src/compact_remote_v2_installation_tests.rs @@ -150,7 +150,6 @@ async fn prepared_prefix_rejection_respects_caller_intent( }, }; let world_state = WorldState::default(); - let mut analytics = CompactionAnalyticsDetails::default(); let mut compaction = Box::pin(run_compaction( &sess, &step, @@ -163,7 +162,6 @@ async fn prepared_prefix_rejection_respects_caller_intent( CompactionImplementation::ResponsesCompactionV2, CompactionPhase::PreTurn, ), - &mut analytics, /*started_item*/ None, Some(candidate), fallback, @@ -190,20 +188,10 @@ async fn prepared_prefix_rejection_respects_caller_intent( let installed = compaction .await .expect("reject stale result without failing compaction"); - // The foreground response has no usage; stale candidate statistics must not leak. - assert_eq!( - ( - analytics.compaction_summary_tokens, - analytics.cached_input_tokens, - analytics.cache_write_input_tokens - ), - (None, None, None), - ); let after = sess.clone_history().await; match fallback { CompactionFallback::Skip => { assert!(!installed); - assert_eq!(analytics.retained_image_count, None); assert_eq!(requests.requests().len(), 0); assert_eq!(after.annotated_items(), before.annotated_items()); assert_eq!(sess.current_window().await, window_before); diff --git a/codex-rs/core/src/compact_token_budget.rs b/codex-rs/core/src/compact_token_budget.rs index 3d97b686..cacbd561 100644 --- a/codex-rs/core/src/compact_token_budget.rs +++ b/codex-rs/core/src/compact_token_budget.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use crate::compaction_metadata::CompactionTrigger; use crate::context::world_state::WorldState; use crate::hook_runtime::PostCompactHookOutcome; use crate::hook_runtime::PreCompactHookOutcome; @@ -7,7 +8,6 @@ use crate::hook_runtime::run_post_compact_hooks; use crate::hook_runtime::run_pre_compact_hooks; use crate::session::session::Session; use crate::session::step_context::StepContext; -use codex_analytics::CompactionTrigger; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::items::ContextCompactionItem; diff --git a/codex-rs/core/src/compaction_metadata.rs b/codex-rs/core/src/compaction_metadata.rs new file mode 100644 index 00000000..2965727b --- /dev/null +++ b/codex-rs/core/src/compaction_metadata.rs @@ -0,0 +1,42 @@ +//! Compaction descriptors attached to model requests whose purpose is compaction. + +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactionTrigger { + Manual, + Auto, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactionReason { + UserRequested, + ContextLimit, + ModelDownshift, + CompHashChanged, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactionImplementation { + Responses, + ResponsesCompactionV2, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactionPhase { + StandaloneTurn, + PreTurn, + MidTurn, + PostTurn, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactionStrategy { + Memento, + PrefixCompaction, +} diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 9ad00bf6..a7657b86 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -57,8 +57,6 @@ use codex_config::types::Notice; use codex_config::types::NotificationCondition; use codex_config::types::NotificationMethod; use codex_config::types::Notifications; -use codex_config::types::OtelConfigToml; -use codex_config::types::OtelExporterKind; use codex_config::types::ResumeCwdMode; use codex_config::types::SandboxWorkspaceWrite; use codex_config::types::SessionPickerViewMode; @@ -10413,9 +10411,6 @@ fn create_test_fixture() -> std::io::Result { model = "o3" approval_policy = "on-request" -[analytics] -enabled = true - [model_providers.openai-custom] name = "OpenAI custom" base_url = "https://api.openai.com/v1" @@ -10442,9 +10437,6 @@ model = "o3" model_provider = "openai" approval_policy = "on-request" -[profiles.zdr.analytics] -enabled = false - [profiles.gpt5] model = "gpt-5.4" model_provider = "openai" @@ -10499,7 +10491,7 @@ async fn legacy_profile_selection_is_rejected() -> std::io::Result<()> { } #[tokio::test] -async fn metrics_exporter_defaults_to_statsig_when_missing() -> std::io::Result<()> { +async fn otel_defaults_keep_local_logging_only() -> std::io::Result<()> { let fixture = create_test_fixture()?; let config = Config::load_from_base_config_with_overrides( @@ -10512,34 +10504,37 @@ async fn metrics_exporter_defaults_to_statsig_when_missing() -> std::io::Result< ) .await?; - assert_eq!(config.otel.metrics_exporter, OtelExporterKind::None); assert!(config.otel.log_sse_deltas); - assert!(!config.otel.agent_response_logging_enabled()); - assert!(!config.otel.guardian_assessment_logging_enabled()); + assert!(!config.otel.log_user_prompt); Ok(()) } #[tokio::test] -async fn trace_exporter_defaults_to_none_when_log_exporter_is_set() -> std::io::Result<()> { - let fixture = create_test_fixture()?; - let mut cfg = fixture.cfg.clone(); - cfg.otel = Some(OtelConfigToml { - tool_result: Some(toml::from_str("max_bytes = 8192").expect("tool-result logging config")), - log_sse_deltas: Some(false), - log_agent_responses: Some(true), - log_guardian_assessments: Some(true), - exporter: Some(OtelExporterKind::OtlpHttp { - endpoint: "http://localhost:14318/v1/logs".to_string(), - headers: HashMap::new(), - protocol: codex_config::types::OtelHttpProtocol::Binary, - tls: None, - }), - metrics_exporter: Some(OtelExporterKind::None), - ..Default::default() - }); +async fn legacy_otel_exporter_keys_are_accepted_and_ignored() -> std::io::Result<()> { + let mut fixture = create_test_fixture()?; + fixture.cfg = toml::from_str( + r#" +[analytics] +enabled = true - let mut config = Config::load_from_base_config_with_overrides( - cfg, +[otel] +tool_result = { max_bytes = 8192 } +log_sse_deltas = false +log_agent_responses = true +log_guardian_assessments = true +environment = "prod" +exporter = { otlp-http = { endpoint = "http://localhost:14318/v1/logs", protocol = "binary" } } +trace_exporter = "statsig" +metrics_exporter = "statsig" + +[otel.span_attributes] +"example.trace_attr" = "enabled" +"#, + ) + .expect("legacy telemetry config should still deserialize"); + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg.clone(), ConfigOverrides { cwd: Some(fixture.cwd_path()), ..Default::default() @@ -10550,128 +10545,7 @@ async fn trace_exporter_defaults_to_none_when_log_exporter_is_set() -> std::io:: assert_eq!(config.otel.tool_result.max_bytes, 8192); assert!(!config.otel.log_sse_deltas); - assert!(config.otel.agent_response_logging_enabled()); - assert!(config.otel.guardian_assessment_logging_enabled()); - assert!(matches!( - config.otel.exporter, - OtelExporterKind::OtlpHttp { .. } - )); - assert_eq!(config.otel.trace_exporter, OtelExporterKind::None); - config.otel.exporter = OtelExporterKind::None; - assert!(!config.otel.guardian_assessment_logging_enabled()); - Ok(()) -} - -#[tokio::test] -async fn load_config_applies_otel_trace_metadata() -> std::io::Result<()> { - let mut fixture = create_test_fixture()?; - fixture.cfg = toml::from_str( - r#" -[otel.span_attributes] -"example.trace_attr" = "enabled" - -[otel.tracestate.example] -alpha = "one" -beta = "two" -"#, - ) - .expect("TOML deserialization should succeed"); - - let config = Config::load_from_base_config_with_overrides( - fixture.cfg.clone(), - ConfigOverrides { - cwd: Some(fixture.cwd_path()), - ..Default::default() - }, - fixture.codex_home(), - ) - .await?; - - assert_eq!( - config.otel.span_attributes, - HashMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) - ); - assert_eq!( - config.otel.tracestate, - BTreeMap::from([( - "example".to_string(), - BTreeMap::from([ - ("alpha".to_string(), "one".to_string()), - ("beta".to_string(), "two".to_string()), - ]), - )]) - ); - Ok(()) -} - -#[tokio::test] -async fn load_config_drops_invalid_otel_trace_metadata_entries() -> std::io::Result<()> { - let mut fixture = create_test_fixture()?; - fixture.cfg = toml::from_str( - r#" -[otel] -environment = "test" - -[otel.span_attributes] -"" = "missing-key" -"example.trace_attr" = "enabled" - -[otel.tracestate.example] -alpha = "one" -beta = "two\ntoo" - -[otel.tracestate.bad] -alpha = "one\ntwo" -"#, - ) - .expect("TOML deserialization should succeed"); - - let config = Config::load_from_base_config_with_overrides( - fixture.cfg.clone(), - ConfigOverrides { - cwd: Some(fixture.cwd_path()), - ..Default::default() - }, - fixture.codex_home(), - ) - .await?; - - assert_eq!(config.otel.environment, "test"); - assert_eq!( - config.otel.span_attributes, - HashMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) - ); - assert_eq!( - config.otel.tracestate, - BTreeMap::from([( - "example".to_string(), - BTreeMap::from([("alpha".to_string(), "one".to_string())]), - )]) - ); - assert!( - config.startup_warnings.iter().any(|warning| { - warning.contains("Ignoring invalid `otel.span_attributes` config") - && warning.contains("configured span attribute key must not be empty") - }), - "{:?}", - config.startup_warnings - ); - assert!( - config.startup_warnings.iter().any(|warning| { - warning.contains("Ignoring invalid `otel.tracestate` config") - && warning.contains("invalid configured tracestate value for example.beta") - }), - "{:?}", - config.startup_warnings - ); - assert!( - config.startup_warnings.iter().any(|warning| { - warning.contains("Ignoring invalid `otel.tracestate` config") - && warning.contains("invalid configured tracestate value for bad.alpha") - }), - "{:?}", - config.startup_warnings - ); + assert!(!config.otel.log_user_prompt); Ok(()) } @@ -14184,7 +14058,7 @@ tracestate = { vendor = { tenant = "managed", region = "us" }, other = { keep = #[test_case::test_case( "[otel]\nlog_agent_responses = false\nlog_guardian_assessments = true", "[otel]\nlog_agent_responses = true\nlog_guardian_assessments = false", - "[otel]\nlog_agent_responses = true\nlog_guardian_assessments = false", true; "managed_logging_flags" + "[otel]\nlog_agent_responses = true\nlog_guardian_assessments = false", false; "ignored_legacy_logging_flags" )] #[test_case::test_case( "[otel]\nlog_sse_deltas = true", "[otel]\nlog_sse_deltas = false", @@ -14202,10 +14076,9 @@ async fn otel_requirements_resolve_config( let config = load_with_enterprise_requirement(&codex_home, requirements).await?; let expected: ConfigToml = toml::from_str(expected_config).expect("expected OTEL config should deserialize"); - let mut warnings = Vec::new(); assert_eq!( config.otel, - super::otel::resolve_config(expected.otel.unwrap_or_default(), &mut warnings) + super::otel::resolve_config(expected.otel.unwrap_or_default()) ); assert_eq!( config @@ -14227,7 +14100,7 @@ async fn otel_requirements_resolve_config( } #[tokio::test] -async fn analytics_disabled_preserves_managed_metrics_exporter() -> std::io::Result<()> { +async fn legacy_managed_metrics_exporter_requirement_is_ignored() -> std::io::Result<()> { let codex_home = TempDir::new()?; std::fs::write( codex_home.path().join(CONFIG_TOML_FILE), @@ -14246,21 +14119,7 @@ metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/metrics", p ) .await?; - assert!(matches!( - config.otel.metrics_exporter, - OtelExporterKind::OtlpHttp { .. } - )); - assert!( - crate::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - /*default_analytics_enabled*/ true, - ) - .expect("managed metrics configuration should remain valid") - .is_some(), - "analytics.enabled=false should preserve the custom managed metrics exporter" - ); + assert_eq!(config.otel, codex_config::types::OtelConfig::default()); Ok(()) } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 04bb9ee1..06567ea1 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1215,12 +1215,7 @@ pub struct Config { /// or placeholder replacement will occur for fast keypress bursts. pub disable_paste_burst: bool, - /// When `false`, disables OpenAI analytics across Codex product surfaces on this machine. - /// Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`. - /// Voluntarily left as Optional because the default value might depend on the client. - pub analytics_enabled: Option, - - /// When `false`, disables feedback uploads and background Guardian review retention. Explicit local exports remain available. + /// When `false`, disables feedback collection and background Guardian review retention. Explicit local exports remain available. /// Defaults to `true`. pub feedback_enabled: bool, @@ -4607,7 +4602,7 @@ impl Config { profile_workspace_roots, ) .map_err(std::io::Error::from)?; - let otel = otel::resolve_config(cfg.otel.unwrap_or_default(), &mut startup_warnings); + let otel = otel::resolve_config(cfg.otel.unwrap_or_default()); let mut config = Self { plugins: cfg.plugins, prefer_mxc, @@ -4836,7 +4831,6 @@ impl Config { .and_then(|tui| tui.disable_paste_burst) .or(cfg.disable_paste_burst) .unwrap_or(false), - analytics_enabled: cfg.analytics.as_ref().and_then(|a| a.enabled), feedback_enabled: cfg .feedback .as_ref() diff --git a/codex-rs/core/src/config/otel.rs b/codex-rs/core/src/config/otel.rs index 8668ff05..2dcfa6e4 100644 --- a/codex-rs/core/src/config/otel.rs +++ b/codex-rs/core/src/config/otel.rs @@ -1,122 +1,12 @@ -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::fmt::Display; - -use codex_config::types::DEFAULT_OTEL_ENVIRONMENT; use codex_config::types::OtelConfig; use codex_config::types::OtelConfigToml; -use codex_config::types::OtelExporterKind; - -pub(crate) fn resolve_config( - config: OtelConfigToml, - startup_warnings: &mut Vec, -) -> OtelConfig { - let log_user_prompt = config.log_user_prompt.unwrap_or(false); - let environment = config - .environment - .unwrap_or_else(|| DEFAULT_OTEL_ENVIRONMENT.to_string()); - let exporter = config.exporter.unwrap_or(OtelExporterKind::None); - // OTLP HTTP endpoints are signal-specific in our config, so enabling log - // export must not implicitly send spans to a /v1/logs endpoint. - let trace_exporter = config.trace_exporter.unwrap_or(OtelExporterKind::None); - let metrics_exporter = config.metrics_exporter.unwrap_or(OtelExporterKind::None); - // Provider initialization installs process-global OTEL state. Sanitize - // user-editable trace metadata here so malformed config is reported as a - // startup warning instead of making startup fail. - let span_attributes = resolve_span_attributes(config.span_attributes, startup_warnings); - let tracestate = resolve_tracestate(config.tracestate, startup_warnings); +/// Resolves the local logging settings kept under the historical `[otel]` table. +/// Telemetry exporters were removed; their former keys are accepted and ignored. +pub(crate) fn resolve_config(config: OtelConfigToml) -> OtelConfig { OtelConfig { tool_result: config.tool_result.unwrap_or_default(), log_sse_deltas: config.log_sse_deltas.unwrap_or(true), - log_user_prompt, - log_agent_responses: config.log_agent_responses.unwrap_or(false), - log_guardian_assessments: config.log_guardian_assessments.unwrap_or(false), - environment, - exporter, - trace_exporter, - metrics_exporter, - span_attributes, - tracestate, + log_user_prompt: config.log_user_prompt.unwrap_or(false), } } - -fn resolve_span_attributes( - span_attributes: Option>, - startup_warnings: &mut Vec, -) -> HashMap { - let Some(span_attributes) = span_attributes else { - return HashMap::new(); - }; - - let mut valid_attributes = HashMap::new(); - for (key, value) in span_attributes { - let attribute = HashMap::from([(key.clone(), value.clone())]); - if let Err(err) = codex_otel::validate_span_attributes(&attribute) { - push_invalid_config_warning("otel.span_attributes", err, startup_warnings); - continue; - } - valid_attributes.insert(key, value); - } - - valid_attributes -} - -fn resolve_tracestate( - tracestate: Option>>, - startup_warnings: &mut Vec, -) -> BTreeMap> { - let Some(tracestate) = tracestate else { - return BTreeMap::new(); - }; - - let mut valid_entries = BTreeMap::new(); - for (member_key, fields) in tracestate { - let fields = resolve_tracestate_member_fields(&member_key, fields, startup_warnings); - if fields.is_empty() { - continue; - } - if let Err(err) = codex_otel::validate_tracestate_member(&member_key, &fields) { - push_invalid_config_warning("otel.tracestate", err, startup_warnings); - continue; - } - valid_entries.insert(member_key, fields); - } - - // Tracestate members can be valid individually while the combined W3C - // tracestate header is not, so validate the filtered set before handing it - // to provider initialization. - if let Err(err) = codex_otel::validate_tracestate_entries(&valid_entries) { - push_invalid_config_warning("otel.tracestate", err, startup_warnings); - return BTreeMap::new(); - } - - valid_entries -} - -fn resolve_tracestate_member_fields( - member_key: &str, - fields: BTreeMap, - startup_warnings: &mut Vec, -) -> BTreeMap { - let mut valid_fields = BTreeMap::new(); - for (field_key, value) in fields { - let field = BTreeMap::from([(field_key.clone(), value.clone())]); - if let Err(err) = codex_otel::validate_tracestate_member(member_key, &field) { - push_invalid_config_warning("otel.tracestate", err, startup_warnings); - continue; - } - valid_fields.insert(field_key, value); - } - valid_fields -} - -fn push_invalid_config_warning( - config_key: &str, - err: impl Display, - startup_warnings: &mut Vec, -) { - let message = format!("Ignoring invalid `{config_key}` config: {err}"); - tracing::warn!("{message}"); - startup_warnings.push(message); -} diff --git a/codex-rs/core/src/guardian/decision.rs b/codex-rs/core/src/guardian/decision.rs index 372ff1a8..b61ca222 100644 --- a/codex-rs/core/src/guardian/decision.rs +++ b/codex-rs/core/src/guardian/decision.rs @@ -176,8 +176,6 @@ pub(crate) fn decide_approval( // Keep the existing turn-level reporting policy during this ownership move. model: turn.model_info(), telemetry: &turn.session_telemetry, - log_assessments: turn.config.otel.guardian_assessment_logging_enabled(), - analytics: &session.services.analytics_events_client, metrics: Some(crate::session::extension_metrics::from_session_telemetry( turn.session_telemetry.clone(), )), diff --git a/codex-rs/core/src/guardian/decision_timing_tests.rs b/codex-rs/core/src/guardian/decision_timing_tests.rs index 8c2a3ec1..cc7faf54 100644 --- a/codex-rs/core/src/guardian/decision_timing_tests.rs +++ b/codex-rs/core/src/guardian/decision_timing_tests.rs @@ -86,7 +86,8 @@ async fn decision_binds_before_scheduling_and_does_not_follow_reused_ids( crate::guardian::GuardianReviewOptions { require_guardian: true, plugin_attribution_override: None, - approval_request_source: codex_analytics::GuardianApprovalRequestSource::MainTurn, + approval_request_source: + codex_guardian_reviewer::GuardianApprovalRequestSource::MainTurn, external_cancel: Some(cancellation), require_synchronous_review: false, }, @@ -200,7 +201,8 @@ async fn network_review_timing_uses_trigger_owner(owned: bool) { super::GuardianReviewOptions { require_guardian: true, plugin_attribution_override: None, - approval_request_source: codex_analytics::GuardianApprovalRequestSource::MainTurn, + approval_request_source: + codex_guardian_reviewer::GuardianApprovalRequestSource::MainTurn, external_cancel: None, require_synchronous_review: false, }, diff --git a/codex-rs/core/src/guardian/request_budget.rs b/codex-rs/core/src/guardian/request_budget.rs index cd402737..f5aa66df 100644 --- a/codex-rs/core/src/guardian/request_budget.rs +++ b/codex-rs/core/src/guardian/request_budget.rs @@ -149,8 +149,7 @@ pub(crate) async fn prepare_prompt( } restored = session .prepare_annotated_conversation_items_for_history(step.turn.as_ref(), model, messages) - .await - .0; + .await; prompt .input .extend(restored.iter().map(|envelope| envelope.item.clone())); diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 78690d99..97aa7458 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -5,11 +5,11 @@ mod request; pub(super) use request::ReviewAuthorization; -use codex_analytics::GuardianApprovalRequestSource; -use codex_analytics::GuardianReviewAnalyticsResult; use codex_core_plugins::PluginCommandAttribution; use codex_features::Feature; +use codex_guardian_reviewer::GuardianApprovalRequestSource; use codex_guardian_reviewer::GuardianAssessment; +use codex_guardian_reviewer::GuardianReviewDetails; use codex_guardian_reviewer::GuardianReviewError; use codex_guardian_reviewer::GuardianReviewOutcome; #[cfg(test)] @@ -257,13 +257,13 @@ async fn run_guardian_review_session_before_deadline( category: GuardianScope, reasons: ApprovalRequestReasons, options: ReviewAttemptOptions, -) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) { +) -> (GuardianReviewOutcome, GuardianReviewDetails) { let Some(pool) = session.guardian_review_session() else { return ( GuardianReviewOutcome::Error(GuardianReviewError::prompt_build(anyhow::anyhow!( "Guardian extension is not installed for this thread" ))), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); }; let session_config = match run_before_review_deadline( @@ -277,14 +277,11 @@ async fn run_guardian_review_session_before_deadline( Ok(Err(err)) => { return ( GuardianReviewOutcome::Error(GuardianReviewError::prompt_build(err)), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); } Err(outcome) => { - return ( - outcome.into(), - GuardianReviewAnalyticsResult::without_session(), - ); + return (outcome.into(), GuardianReviewDetails::without_session()); } }; let input = ReviewInput { @@ -295,12 +292,12 @@ async fn run_guardian_review_session_before_deadline( reasons, }; let params = input.into_params(session_config, category, options); - let (session_outcome, session_analytics_result) = Box::pin( + let (session_outcome, session_details) = Box::pin( super::review_session::run_guardian_review_session(pool, params), ) .await; - (session_outcome.into(), session_analytics_result) + (session_outcome.into(), session_details) } #[cfg(test)] @@ -311,7 +308,7 @@ pub(super) async fn run_guardian_review_session_with_retry( reasons: ApprovalRequestReasons, external_cancel: Option, max_attempts: i64, -) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) { +) -> (GuardianReviewOutcome, GuardianReviewDetails) { run_guardian_review_session_with_retry_before_deadline( session, context, @@ -334,9 +331,9 @@ async fn run_guardian_review_session_with_retry_before_deadline( reasons: ApprovalRequestReasons, external_cancel: Option, limits: GuardianReviewSessionLimits, -) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) { +) -> (GuardianReviewOutcome, GuardianReviewDetails) { let context = context.into(); - let (outcome, analytics, _) = run_with_retry( + let (outcome, details, _) = run_with_retry( limits, external_cancel.as_ref(), /*telemetry*/ None, @@ -354,11 +351,11 @@ async fn run_guardian_review_session_with_retry_before_deadline( }, ); async move { - let (outcome, analytics) = attempt.await; - (outcome, analytics, None::<()>) + let (outcome, details) = attempt.await; + (outcome, details, None::<()>) } }, ) .await; - (outcome, analytics) + (outcome, details) } diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs index 3e03eb04..e2621f0e 100644 --- a/codex-rs/core/src/guardian/review_request.rs +++ b/codex-rs/core/src/guardian/review_request.rs @@ -213,13 +213,13 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { cancellation: &CancellationToken, ) -> ( GuardianReviewOutcome, - GuardianReviewAnalyticsResult, + GuardianReviewDetails, Option, ) { if self.history_reset.is_cancelled() || cancellation.is_cancelled() { return ( GuardianReviewOutcome::Error(GuardianReviewError::Cancelled), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), None, ); } @@ -238,7 +238,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { { return ( GuardianReviewOutcome::Error(GuardianReviewError::Cancelled), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), None, ); } @@ -264,7 +264,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { root_versions, }); drop(history); - let (outcome, analytics) = run_guardian_review_session_before_deadline( + let (outcome, details) = run_guardian_review_session_before_deadline( Arc::clone(&self.session), prepared.context.clone(), prepared.request.clone(), @@ -289,7 +289,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { GuardianReviewOutcome::Completed(_) => review_evidence, GuardianReviewOutcome::CachedApproval | GuardianReviewOutcome::Error(_) => None, }; - (outcome, analytics, review_evidence) + (outcome, details, review_evidence) } async fn cached_approval_is_current(&self, prepared: &PreparedApproval) -> bool { diff --git a/codex-rs/core/src/guardian/review_session.rs b/codex-rs/core/src/guardian/review_session.rs index c72fd944..e1003413 100644 --- a/codex-rs/core/src/guardian/review_session.rs +++ b/codex-rs/core/src/guardian/review_session.rs @@ -24,13 +24,13 @@ use std::sync::atomic::Ordering; #[cfg(test)] use std::time::Duration; -use codex_analytics::GuardianReviewAnalyticsResult; -use codex_analytics::GuardianReviewSessionAnalyticsParams; -use codex_analytics::GuardianReviewSessionKind; use codex_extension_api::Instructions; #[cfg(test)] use codex_guardian_reviewer::ConversationState; +use codex_guardian_reviewer::GuardianReviewDetails; use codex_guardian_reviewer::GuardianReviewForkSnapshot; +use codex_guardian_reviewer::GuardianReviewSessionDetails; +use codex_guardian_reviewer::GuardianReviewSessionKind; pub use codex_guardian_reviewer::GuardianReviewState; use codex_guardian_reviewer::GuardianTranscriptSource; use codex_guardian_reviewer::PendingNodeReplEvidenceAdmission; @@ -53,7 +53,6 @@ use codex_protocol::protocol::Event; #[cfg(test)] use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; -use codex_protocol::protocol::SubAgentSource; use futures::future::BoxFuture; use serde_json::Value; use tokio::sync::Mutex; @@ -84,7 +83,6 @@ use codex_thread_store::PersistContext; use codex_utils_path_uri::PathUri; use super::ApprovalRequestReasons; -use super::GUARDIAN_REVIEWER_NAME; use super::GuardianApprovalRequest; use super::GuardianReviewContext; use super::feedback::record_failed_review; @@ -259,19 +257,18 @@ async fn run_review_on_session( state.conversation.cursor().is_some(), ) }; - let mut analytics_result = - GuardianReviewAnalyticsResult::from_session(GuardianReviewSessionAnalyticsParams { - guardian_thread_id: review_session.session.thread_id().to_string(), - guardian_session_kind, - guardian_model: review_model.model.clone(), - guardian_reasoning_effort: guardian_reasoning_effort.map(|effort| effort.to_string()), - guardian_default_review_model_id: review_model.default_review_model_id.clone(), - guardian_catalog_contains_auto_review: review_model.catalog_contains_auto_review, - guardian_review_model_overridden: review_model.model_overridden, - guardian_review_model_override: review_model.model_override.clone(), - guardian_model_provider_id: params.spawn_config.model_provider_id.clone(), - had_prior_review_context: had_prior_context, - }); + let mut details = GuardianReviewDetails::from_session(GuardianReviewSessionDetails { + guardian_thread_id: review_session.session.thread_id().to_string(), + guardian_session_kind, + guardian_model: review_model.model.clone(), + guardian_reasoning_effort: guardian_reasoning_effort.map(|effort| effort.to_string()), + guardian_default_review_model_id: review_model.default_review_model_id.clone(), + guardian_catalog_contains_auto_review: review_model.catalog_contains_auto_review, + guardian_review_model_overridden: review_model.model_overridden, + guardian_review_model_override: review_model.model_override.clone(), + guardian_model_provider_id: params.spawn_config.model_provider_id.clone(), + had_prior_review_context: had_prior_context, + }); if prior_review_count > 0 { ensure_guardian_followup_reminder(review_session).await; } @@ -292,14 +289,14 @@ async fn run_review_on_session( retry_at: None, }, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } Err(outcome) => { return ReviewSessionResult { outcome, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } } @@ -320,7 +317,7 @@ async fn run_review_on_session( return ReviewSessionResult { outcome: GuardianReviewSessionOutcome::PromptBuildFailed(error.into()), disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } } @@ -349,14 +346,14 @@ async fn run_review_on_session( retry_at: None, }, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } Err(outcome) => { return ReviewSessionResult { outcome, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } }; @@ -365,7 +362,7 @@ async fn run_review_on_session( &compact_turn_id, deadline, params.external_cancel.as_ref(), - &mut analytics_result, + &mut details, ) .await; execution_attempt.finish(result.turn_completed); @@ -376,7 +373,7 @@ async fn run_review_on_session( return ReviewSessionResult { outcome: result.outcome, disposition: result.disposition, - analytics: analytics_result, + details: details, }; } @@ -410,7 +407,7 @@ async fn run_review_on_session( "Guardian history changed; restart from the parent checkpoint" )), disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } if !reviewer_has_full_transcript { @@ -472,8 +469,7 @@ async fn run_review_on_session( } else { GuardianPromptMode::Full }; - analytics_result.had_prior_review_context = - Some(had_prior_review_context(&prompt_mode)); + details.had_prior_review_context = Some(had_prior_review_context(&prompt_mode)); let prompt_items = prompt_builder::build_guardian_prompt_items( params, review_session, @@ -512,7 +508,7 @@ async fn run_review_on_session( return ReviewSessionResult { outcome, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } }; @@ -522,7 +518,7 @@ async fn run_review_on_session( return ReviewSessionResult { outcome: GuardianReviewSessionOutcome::PromptBuildFailed(err), disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } }; @@ -637,7 +633,7 @@ async fn run_review_on_session( return ReviewSessionResult { outcome, disposition: SessionDisposition::Discard, - analytics: analytics_result, + details: details, }; } }; @@ -654,7 +650,7 @@ async fn run_review_on_session( child_turn_id.as_str(), deadline, params.external_cancel.as_ref(), - &mut analytics_result, + &mut details, ) .await; execution_attempt.finish(turn_result.turn_completed); @@ -677,7 +673,7 @@ async fn run_review_on_session( ); // Failed reviews can still spend tokens on completed inference requests. if let Some(total_token_usage) = review_session.session.total_token_usage().await { - analytics_result.token_usage = Some(token_usage_delta( + details.token_usage = Some(token_usage_delta( &token_usage_at_review_start, &total_token_usage, )); @@ -723,7 +719,7 @@ async fn run_review_on_session( } else { turn_result.disposition }, - analytics: analytics_result, + details: details, } } diff --git a/codex-rs/core/src/guardian/review_session_setup.rs b/codex-rs/core/src/guardian/review_session_setup.rs index 17b7fa3d..05059267 100644 --- a/codex-rs/core/src/guardian/review_session_setup.rs +++ b/codex-rs/core/src/guardian/review_session_setup.rs @@ -183,16 +183,6 @@ impl PreparedGuardianContext { thread_instructions: inherited.thread, ..context }; - crate::session::emit_subagent_session_started( - &self.parent.services.analytics_events_client, - self.parent.app_server_client_metadata().await, - session.session_id(), - session.thread_id(), - Some(self.parent.thread_id()), - session.thread_config_snapshot().await, - SubAgentSource::Other(GUARDIAN_REVIEWER_NAME.to_owned()), - /*resumed_created_at*/ None, - ); GuardianReviewSession { session, io, @@ -290,7 +280,7 @@ impl ReviewerRequest for PreparedReview { .await { let outcome = invalidation.outcome; - result.analytics.context_changed |= invalidation.context_changed; + result.details.context_changed |= invalidation.context_changed; result.disposition = if matches!(outcome, GuardianReviewSessionOutcome::StaleAuthorization) && result.disposition == SessionDisposition::Reusable @@ -326,14 +316,14 @@ impl ReviewerRequest for PreparedReview { pub(crate) async fn run_guardian_review_session( pool: Arc>, params: GuardianReviewSessionParams, -) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult) { +) -> (GuardianReviewSessionOutcome, GuardianReviewDetails) { let context_mode = GuardianContextMode::from_history( params .parent_history .conversation_history_snapshot() .as_ref(), ); - let (outcome, mut analytics) = match prepare_review(params).await { + let (outcome, mut details) = match prepare_review(params).await { Ok(mut prepared) => { let result = pool.review(prepared.clone()).await; if prepared.recovery_requested.load(Ordering::Acquire) { @@ -342,21 +332,21 @@ pub(crate) async fn run_guardian_review_session( Arc::make_mut(&mut prepared.context).reviewer_selection = ReviewerSelection::FreshParentCheckpoint; prepared.recovery_requested = Arc::default(); - let (outcome, mut analytics) = pool.review(prepared).await; - analytics.context_changed |= result.1.context_changed; - (outcome, analytics) + let (outcome, mut details) = pool.review(prepared).await; + details.context_changed |= result.1.context_changed; + (outcome, details) } else { result } } Err(error) => ( GuardianReviewSessionOutcome::PromptBuildFailed(error), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ), }; // Keep the captured mode even when preparation or reviewer startup fails. - analytics.guardian_context_mode = Some(context_mode.as_str()); - (outcome, analytics) + details.guardian_context_mode = Some(context_mode.as_str()); + (outcome, details) } pub(in crate::guardian) async fn prepare_review( diff --git a/codex-rs/core/src/guardian/review_session_tests.rs b/codex-rs/core/src/guardian/review_session_tests.rs index 1a73e40a..aa6bcd81 100644 --- a/codex-rs/core/src/guardian/review_session_tests.rs +++ b/codex-rs/core/src/guardian/review_session_tests.rs @@ -732,7 +732,7 @@ async fn run_review_on_reused_session_waits_for_submitted_turn() { let ReviewSessionResult { outcome, disposition, - analytics: analytics_result, + details, } = review.await.expect("review task should complete"); let GuardianReviewSessionOutcome::Completed(Ok(last_agent_message)) = outcome else { panic!("expected submitted turn completion"); @@ -741,7 +741,7 @@ async fn run_review_on_reused_session_waits_for_submitted_turn() { last_agent_message.as_ref().map(GuardianReviewResponse::raw), Some("fresh") ); - assert_eq!(analytics_result.time_to_first_token_ms, Some(42)); + assert_eq!(details.time_to_first_token_ms, Some(42)); assert_eq!(disposition, SessionDisposition::Reusable); } @@ -823,7 +823,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_errors() { .await .expect("queue current turn completion"); - let mut analytics_result = GuardianReviewAnalyticsResult::without_session(); + let mut details = GuardianReviewDetails::without_session(); let codex_guardian_reviewer::ReviewTurnResult { outcome, disposition, @@ -835,7 +835,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_errors() { tokio::time::Instant::now() + Duration::from_secs(1), ), /*external_cancel*/ None, - &mut analytics_result, + &mut details, ) .await; @@ -843,7 +843,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_errors() { panic!("expected current turn completion"); }; assert!(last_agent_message.is_none()); - assert_eq!(analytics_result.time_to_first_token_ms, Some(42)); + assert_eq!(details.time_to_first_token_ms, Some(42)); assert_eq!(disposition, SessionDisposition::Reusable); assert!(turn_completed); } @@ -872,7 +872,7 @@ async fn wait_for_guardian_review_preserves_structured_session_error() { .await .expect("queue current turn completion"); - let mut analytics_result = GuardianReviewAnalyticsResult::without_session(); + let mut details = GuardianReviewDetails::without_session(); let codex_guardian_reviewer::ReviewTurnResult { outcome, disposition, @@ -884,7 +884,7 @@ async fn wait_for_guardian_review_preserves_structured_session_error() { tokio::time::Instant::now() + Duration::from_secs(1), ), /*external_cancel*/ None, - &mut analytics_result, + &mut details, ) .await; @@ -912,7 +912,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_aborts() { .await .expect("queue current turn completion"); - let mut analytics_result = GuardianReviewAnalyticsResult::without_session(); + let mut details = GuardianReviewDetails::without_session(); let codex_guardian_reviewer::ReviewTurnResult { outcome, disposition, @@ -924,7 +924,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_aborts() { tokio::time::Instant::now() + Duration::from_secs(1), ), /*external_cancel*/ None, - &mut analytics_result, + &mut details, ) .await; @@ -935,7 +935,7 @@ async fn wait_for_guardian_review_ignores_prior_turn_aborts() { last_agent_message.as_ref().map(GuardianReviewResponse::raw), Some("fresh") ); - assert_eq!(analytics_result.time_to_first_token_ms, Some(42)); + assert_eq!(details.time_to_first_token_ms, Some(42)); assert_eq!(disposition, SessionDisposition::Reusable); assert!(turn_completed); } @@ -957,7 +957,7 @@ async fn wait_for_guardian_review_timeout_drains_expected_turn_after_stale_termi .expect("queue current turn abort"); }); - let mut analytics_result = GuardianReviewAnalyticsResult::without_session(); + let mut details = GuardianReviewDetails::without_session(); let codex_guardian_reviewer::ReviewTurnResult { outcome, disposition, @@ -969,7 +969,7 @@ async fn wait_for_guardian_review_timeout_drains_expected_turn_after_stale_termi tokio::time::Instant::now() + Duration::from_millis(10), ), /*external_cancel*/ None, - &mut analytics_result, + &mut details, ) .await; @@ -1000,7 +1000,7 @@ async fn wait_for_guardian_review_cancel_drains_expected_turn_after_stale_termin let external_cancel = CancellationToken::new(); external_cancel.cancel(); - let mut analytics_result = GuardianReviewAnalyticsResult::without_session(); + let mut details = GuardianReviewDetails::without_session(); let codex_guardian_reviewer::ReviewTurnResult { outcome, disposition, @@ -1012,7 +1012,7 @@ async fn wait_for_guardian_review_cancel_drains_expected_turn_after_stale_termin tokio::time::Instant::now() + Duration::from_secs(1), ), Some(&external_cancel), - &mut analytics_result, + &mut details, ) .await; @@ -1043,7 +1043,7 @@ async fn interrupt_and_drain_turn_ignores_prior_turn_completion() { "current-turn", codex_guardian_reviewer::ReviewDeadline::At(tokio::time::Instant::now()), Some(&cancellation), - &mut GuardianReviewAnalyticsResult::without_session(), + &mut GuardianReviewDetails::without_session(), ) .await; assert_eq!(result.disposition, SessionDisposition::Rollback); diff --git a/codex-rs/core/src/guardian/test_host.rs b/codex-rs/core/src/guardian/test_host.rs index a30b96b1..0176b168 100644 --- a/codex-rs/core/src/guardian/test_host.rs +++ b/codex-rs/core/src/guardian/test_host.rs @@ -40,7 +40,6 @@ pub(crate) fn install(session: &Session, config: &Config) { Arc::new(CodexHomeUserInstructionsProvider::new( config.codex_home.clone(), )), - /*analytics_events_client*/ None, crate::passthrough_image_store(), Arc::clone(&session.services.thread_store), /*agent_graph_store*/ None, @@ -64,7 +63,7 @@ pub(crate) fn install(session: &Session, config: &Config) { let (mut options, state) = context.thread_options(kind, snapshot).await; if matches!( kind, - codex_analytics::GuardianReviewSessionKind::EphemeralForked + codex_guardian_reviewer::GuardianReviewSessionKind::EphemeralForked ) { options.config.ephemeral = true; } diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index e18a9acb..8f5c3924 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -14,7 +14,6 @@ use crate::session::session::Session; use crate::session::tests::update_turn_settings_for_test; use crate::session::turn_context::TurnContext; use crate::test_support; -use codex_analytics::GuardianApprovalRequestSource; use codex_config::ConfigLayerStack; use codex_config::NetworkConstraints; use codex_config::NetworkDomainPermissionToml; @@ -27,6 +26,7 @@ use codex_exec_server::LOCAL_FS; use codex_features::Feature; use codex_guardian_context::ConversationTranscriptEntry; use codex_guardian_context::ConversationTranscriptEntryKind; +use codex_guardian_reviewer::GuardianApprovalRequestSource; use codex_guardian_reviewer::guardian_output_contract_prompt; use codex_history::RolloutItem; use codex_model_provider::create_model_provider; @@ -1406,7 +1406,7 @@ async fn guardian_request_model_for_auto_review( String, String, String, - codex_analytics::GuardianReviewAnalyticsResult, + codex_guardian_reviewer::GuardianReviewDetails, )> { let server = start_mock_server().await; let guardian_assessment = serde_json::json!({ @@ -1467,7 +1467,7 @@ async fn guardian_request_model_for_auto_review( let parent_turn_id = turn.sub_id.clone(); seed_guardian_parent_history(&session, &turn).await; - let (outcome, analytics_result) = run_guardian_review_session_for_test( + let (outcome, details) = run_guardian_review_session_for_test( Arc::clone(&session), turn, GuardianApprovalRequest::ExecCommand { @@ -1502,12 +1502,7 @@ async fn guardian_request_model_for_auto_review( .expect("guardian request should include a model") .to_string(); - Ok(( - request_model, - parent_model, - preferred_model, - analytics_result, - )) + Ok((request_model, parent_model, preferred_model, details)) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -1516,7 +1511,7 @@ async fn guardian_review_uses_model_catalog_override_when_preferred_review_model skip_if_no_network!(Ok(())); let override_model = "guardian-review-model-override".to_string(); - let (request_model, parent_model, preferred_model, analytics_result) = + let (request_model, parent_model, preferred_model, details) = guardian_request_model_for_auto_review( Some(override_model.clone()), GuardianTestCatalog::Bundled, @@ -1526,24 +1521,18 @@ async fn guardian_review_uses_model_catalog_override_when_preferred_review_model assert_eq!(request_model, override_model); assert_ne!(request_model, parent_model); assert_ne!(request_model, preferred_model); + assert_eq!(details.guardian_catalog_contains_auto_review, Some(true)); assert_eq!( - analytics_result.guardian_catalog_contains_auto_review, - Some(true) - ); - assert_eq!( - analytics_result.guardian_default_review_model_id.as_deref(), + details.guardian_default_review_model_id.as_deref(), Some(preferred_model.as_str()) ); + assert_eq!(details.guardian_review_model_overridden, Some(true)); assert_eq!( - analytics_result.guardian_review_model_overridden, - Some(true) - ); - assert_eq!( - analytics_result.guardian_review_model_override.as_deref(), + details.guardian_review_model_override.as_deref(), Some(override_model.as_str()) ); assert_eq!( - analytics_result.guardian_model_provider_id.as_deref(), + details.guardian_model_provider_id.as_deref(), Some(OPENAI_PROVIDER_ID) ); @@ -1555,7 +1544,7 @@ async fn guardian_review_uses_preferred_review_model_without_model_catalog_overr -> anyhow::Result<()> { skip_if_no_network!(Ok(())); - let (request_model, parent_model, preferred_model, analytics_result) = + let (request_model, parent_model, preferred_model, details) = guardian_request_model_for_auto_review( /*auto_review_model_override*/ None, GuardianTestCatalog::Explicit, @@ -1564,24 +1553,15 @@ async fn guardian_review_uses_preferred_review_model_without_model_catalog_overr assert_eq!(request_model, preferred_model); assert_ne!(request_model, parent_model); + assert_eq!(details.guardian_catalog_contains_auto_review, Some(true)); assert_eq!( - analytics_result.guardian_catalog_contains_auto_review, - Some(true) - ); - assert_eq!( - analytics_result.guardian_default_review_model_id.as_deref(), + details.guardian_default_review_model_id.as_deref(), Some(preferred_model.as_str()) ); + assert_eq!(details.guardian_review_model_overridden, Some(false)); + assert_eq!(details.guardian_review_model_override.as_deref(), None); assert_eq!( - analytics_result.guardian_review_model_overridden, - Some(false) - ); - assert_eq!( - analytics_result.guardian_review_model_override.as_deref(), - None - ); - assert_eq!( - analytics_result.guardian_model_provider_id.as_deref(), + details.guardian_model_provider_id.as_deref(), Some(OPENAI_PROVIDER_ID) ); @@ -1589,11 +1569,11 @@ async fn guardian_review_uses_preferred_review_model_without_model_catalog_overr } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn guardian_review_records_missing_auto_review_model_in_analytics_metadata() --> anyhow::Result<()> { +async fn guardian_review_records_missing_auto_review_model_in_review_metadata() -> anyhow::Result<()> +{ skip_if_no_network!(Ok(())); - let (request_model, parent_model, preferred_model, analytics_result) = + let (request_model, parent_model, preferred_model, details) = guardian_request_model_for_auto_review( /*auto_review_model_override*/ None, GuardianTestCatalog::ParentOnly, @@ -1602,24 +1582,15 @@ async fn guardian_review_records_missing_auto_review_model_in_analytics_metadata assert_eq!(request_model, parent_model); assert_ne!(request_model, preferred_model); + assert_eq!(details.guardian_catalog_contains_auto_review, Some(false)); assert_eq!( - analytics_result.guardian_catalog_contains_auto_review, - Some(false) - ); - assert_eq!( - analytics_result.guardian_default_review_model_id.as_deref(), + details.guardian_default_review_model_id.as_deref(), Some(preferred_model.as_str()) ); + assert_eq!(details.guardian_review_model_overridden, Some(false)); + assert_eq!(details.guardian_review_model_override.as_deref(), None); assert_eq!( - analytics_result.guardian_review_model_overridden, - Some(false) - ); - assert_eq!( - analytics_result.guardian_review_model_override.as_deref(), - None - ); - assert_eq!( - analytics_result.guardian_model_provider_id.as_deref(), + details.guardian_model_provider_id.as_deref(), Some(OPENAI_PROVIDER_ID) ); @@ -1757,7 +1728,7 @@ async fn guardian_review_request_layout_matches_model_visible_request_snapshot() ThreadId::from_string(guardian_thread_id).expect("guardian thread id should be a valid UUID"); assert!(matches!( metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkNew) )); let request = request_log.single_request(); let turn_metadata: serde_json::Value = serde_json::from_str( @@ -2193,19 +2164,19 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: assert_eq!(fourth_assessment.outcome, GuardianAssessmentOutcome::Allow); assert!(matches!( first_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkNew) )); assert!(matches!( second_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkReused) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkReused) )); assert!(matches!( third_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkNew) )); assert!(matches!( fourth_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkNew) )); ThreadId::from_string( first_metadata @@ -2404,7 +2375,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow:: assert_eq!(first_assessment.rationale, "first guardian rationale"); assert!(matches!( first_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkNew) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkNew) )); session @@ -2458,7 +2429,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow:: assert_eq!(second_assessment.rationale, "second guardian rationale"); assert!(matches!( second_metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkReused) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkReused) )); assert_eq!( @@ -2628,7 +2599,7 @@ async fn guardian_review_retries_transient_session_failure_then_approves() -> an assert_eq!(metadata.attempt_count, 2); assert!(matches!( metadata.guardian_session_kind, - Some(codex_analytics::GuardianReviewSessionKind::TrunkReused) + Some(codex_guardian_reviewer::GuardianReviewSessionKind::TrunkReused) )); assert_eq!(request_log.requests().len(), 2); Ok(()) diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 09235da1..0e8bce0a 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -6,9 +6,7 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; -use codex_analytics::CompactionTrigger; -use codex_analytics::HookRunFact; -use codex_analytics::build_track_events_context; +use crate::compaction_metadata::CompactionTrigger; use codex_hooks::InterruptRequest; use codex_hooks::PermissionRequestDecision; use codex_hooks::PermissionRequestOutcome; @@ -962,7 +960,6 @@ pub(crate) async fn emit_hook_completed_events( for completed in completed_events { emit_hook_completed_metrics(turn_context, &completed); - track_hook_completed_analytics(sess, turn_context, &completed); if should_emit_hook_notification(&completed.run) { sess.send_event(turn_context, EventMsg::HookCompleted(completed)) .await; @@ -986,44 +983,6 @@ fn emit_hook_completed_metrics(turn_context: &TurnContext, completed: &HookCompl } } -fn track_hook_completed_analytics( - sess: &Arc, - turn_context: &Arc, - completed: &HookCompletedEvent, -) { - let (tracking, hook) = - hook_run_analytics_payload(sess.thread_id.to_string(), turn_context, completed); - sess.services - .analytics_events_client - .track_hook_run(tracking, hook); -} - -fn hook_run_analytics_payload( - thread_id: String, - turn_context: &TurnContext, - completed: &HookCompletedEvent, -) -> (codex_analytics::TrackEventsContext, HookRunFact) { - ( - build_track_events_context( - turn_context.model_info().slug.clone(), - thread_id, - completed - .turn_id - .clone() - .unwrap_or_else(|| turn_context.sub_id.clone()), - turn_context.originator.clone(), - /*turn_metadata*/ None, - ), - HookRunFact { - event_name: completed.run.event_name, - hook_source: completed.run.source, - handler_type: completed.run.handler_type, - execution_mode: completed.run.execution_mode, - status: completed.run.status, - }, - ) -} - fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str); 5] { let hook_name = match run.event_name { HookEventName::PreToolUse => "PreToolUse", @@ -1177,9 +1136,7 @@ mod tests { use super::additional_context_messages; use super::emit_hook_completed_events; use super::emit_hook_started_events; - use super::hook_run_analytics_payload; use super::hook_run_metric_tags; - use crate::session::tests::make_session_and_context; use crate::session::tests::make_session_and_context_with_rx; use codex_protocol::protocol::HookCompletedEvent; use codex_protocol::protocol::HookRunSummary; @@ -1329,47 +1286,8 @@ mod tests { ); } - #[tokio::test] - async fn hook_run_analytics_payload_uses_completed_turn_id() { - let (_session, turn_context) = make_session_and_context().await; - let completed = HookCompletedEvent { - turn_id: Some("turn-from-hook".to_string()), - run: sample_hook_run(HookRunStatus::Blocked, HookSource::Project), - }; - - let (tracking, hook) = - hook_run_analytics_payload("thread-123".to_string(), &turn_context, &completed); - - assert_eq!(tracking.thread_id, "thread-123"); - assert_eq!(tracking.turn_id, "turn-from-hook"); - assert_eq!(tracking.model_slug, turn_context.model_info().slug); - assert_eq!(hook.event_name, HookEventName::Stop); - assert_eq!(hook.handler_type, HookHandlerType::Command); - assert_eq!(hook.execution_mode, HookExecutionMode::Sync); - assert_eq!(hook.hook_source, HookSource::Project); - assert_eq!(hook.status, HookRunStatus::Blocked); - } - - #[tokio::test] - async fn hook_run_analytics_payload_falls_back_to_turn_context_id() { - let (_session, turn_context) = make_session_and_context().await; - let mut run = sample_hook_run(HookRunStatus::Failed, HookSource::Unknown); - run.handler_type = HookHandlerType::Prompt; - run.execution_mode = HookExecutionMode::Async; - let completed = HookCompletedEvent { turn_id: None, run }; - - let (tracking, hook) = - hook_run_analytics_payload("thread-123".to_string(), &turn_context, &completed); - - assert_eq!(tracking.turn_id, turn_context.sub_id); - assert_eq!(hook.handler_type, HookHandlerType::Prompt); - assert_eq!(hook.execution_mode, HookExecutionMode::Async); - assert_eq!(hook.hook_source, HookSource::Unknown); - assert_eq!(hook.status, HookRunStatus::Failed); - } - #[test] - fn hook_run_metric_tags_match_analytics_shape() { + fn hook_run_metric_tags_match_expected_shape() { let mut run = sample_hook_run(HookRunStatus::Blocked, HookSource::Project); run.handler_type = HookHandlerType::McpTool; diff --git a/codex-rs/core/src/image_preparation.rs b/codex-rs/core/src/image_preparation.rs index 39915e7a..1e575a9c 100644 --- a/codex-rs/core/src/image_preparation.rs +++ b/codex-rs/core/src/image_preparation.rs @@ -6,8 +6,6 @@ use crate::context::ImageResizeNotice; use crate::context::ImageResizeNoticeSource; use crate::context::ResizedImage; use crate::original_image_detail::can_request_original_image_detail; -use codex_analytics::ImageDetailSetting; -use codex_analytics::ImagePreparationMetadata; use codex_attachment_store::AttachmentStore; use codex_attachment_store::UploadRequest; use codex_attachment_store::UploadResult; @@ -56,8 +54,6 @@ pub(crate) fn unified_image_budget_enabled( struct ImageOrigin<'a> { thread_id: &'a str, ephemeral: bool, - message_role: Option<&'a str>, - item_id: Option<&'a str>, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -76,7 +72,6 @@ struct PreparedImageResize { pub(crate) struct PreparedInlineImage { encoded: EncodedImage, - effective_detail: ImageDetailSetting, resize: Option, } @@ -84,18 +79,6 @@ impl PreparedInlineImage { pub(crate) fn into_data_url(self) -> String { self.encoded.into_data_url() } - - fn metadata(&self, origin: ImageOrigin<'_>) -> ImagePreparationMetadata { - ImagePreparationMetadata { - message_role: origin.message_role.map(str::to_string), - item_id: origin.item_id.map(str::to_string), - effective_detail: self.effective_detail, - source_width: self.encoded.source_width, - source_height: self.encoded.source_height, - prepared_width: self.encoded.width, - prepared_height: self.encoded.height, - } - } } #[derive(Debug, thiserror::Error)] @@ -130,8 +113,7 @@ pub(crate) async fn prepare_response_items( mode: ImagePreparationMode, resize_notice_mode: ImageResizeNoticeMode, image_store: &dyn AttachmentStore, -) -> Vec { - let mut metadata = Vec::new(); +) { let mut prepared_items = Vec::with_capacity(items.len()); for mut item in std::mem::take(items) { let mut annotated_content = to_annotated_content(&mut item); @@ -145,15 +127,12 @@ pub(crate) async fn prepare_response_items( ImageOrigin { thread_id, ephemeral, - message_role: Some(role.as_str()), - item_id: None, }, if role.as_str() == "user" { resize_notice_mode } else { ImageResizeNoticeMode::Disabled }, - &mut metadata, mode, image_store, ) @@ -163,31 +142,23 @@ pub(crate) async fn prepare_response_items( ImageResizeNotice::new(ImageResizeNoticeSource::UserMessage, resized_images) }) } - ResponseItem::FunctionCallOutput { - call_id, output, .. - } => { + ResponseItem::FunctionCallOutput { output, .. } => { prepare_tool_output( thread_id, ephemeral, output, - call_id.as_deref(), resize_notice_mode, - &mut metadata, mode, image_store, ) .await } - ResponseItem::CustomToolCallOutput { - call_id, output, .. - } => { + ResponseItem::CustomToolCallOutput { output, .. } => { prepare_tool_output( thread_id, ephemeral, output, - Some(call_id.as_str()), resize_notice_mode, - &mut metadata, mode, image_store, ) @@ -215,7 +186,6 @@ pub(crate) async fn prepare_response_items( } } *items = prepared_items; - metadata } #[allow(clippy::too_many_arguments)] @@ -223,9 +193,7 @@ async fn prepare_tool_output( thread_id: &str, ephemeral: bool, output: &mut FunctionCallOutputPayload, - item_id: Option<&str>, resize_notice_mode: ImageResizeNoticeMode, - metadata: &mut Vec, mode: ImagePreparationMode, image_store: &dyn AttachmentStore, ) -> Option { @@ -235,11 +203,8 @@ async fn prepare_tool_output( ImageOrigin { thread_id, ephemeral, - message_role: None, - item_id, }, resize_notice_mode, - metadata, mode, image_store, ) @@ -258,7 +223,6 @@ async fn prepare_message_content( items: &mut [AnnotatedContent], origin: ImageOrigin<'_>, resize_notice_mode: ImageResizeNoticeMode, - metadata: &mut Vec, mode: ImagePreparationMode, image_store: &dyn AttachmentStore, ) -> Vec { @@ -273,7 +237,7 @@ async fn prepare_message_content( for item in items { if let ContentItem::InputImage { image, detail } = item.content_mut() { image_number += 1; - match prepare_image(image, detail, origin, metadata, mode, image_store).await { + match prepare_image(image, detail, origin, mode, image_store).await { Ok(Some(resize)) if resize_notice_mode == ImageResizeNoticeMode::Enabled => { resized_images.push(ResizedImage { image_number, @@ -303,7 +267,6 @@ async fn prepare_tool_output_content( items: &mut [FunctionCallOutputContentItem], origin: ImageOrigin<'_>, resize_notice_mode: ImageResizeNoticeMode, - metadata: &mut Vec, mode: ImagePreparationMode, image_store: &dyn AttachmentStore, ) -> Vec { @@ -316,7 +279,7 @@ async fn prepare_tool_output_content( for item in items { if let FunctionCallOutputContentItem::InputImage { image, detail } = item { image_number += 1; - match prepare_image(image, detail, origin, metadata, mode, image_store).await { + match prepare_image(image, detail, origin, mode, image_store).await { Ok(Some(resize)) if resize_notice_mode == ImageResizeNoticeMode::Enabled => { resized_images.push(ResizedImage { image_number, @@ -356,7 +319,6 @@ async fn prepare_image( image: &mut ImageReference, detail: &mut Option, origin: ImageOrigin<'_>, - metadata: &mut Vec, mode: ImagePreparationMode, image_store: &dyn AttachmentStore, ) -> Result, ImagePreparationError> { @@ -366,7 +328,6 @@ async fn prepare_image( let Some(prepared) = resize_image(image_url, detail, mode)? else { return Ok(None); }; - metadata.push(prepared.metadata(origin)); let resize = prepared.resize; let request = UploadRequest { thread_id: origin.thread_id.to_owned(), @@ -402,19 +363,11 @@ pub(crate) fn resize_image( return Ok(None); } - let (effective_detail, image_mode) = match mode { - ImagePreparationMode::UnifiedBudget => ( - ImageDetailSetting::Original, - PromptImageMode::ORIGINAL_DETAIL, - ), + let image_mode = match mode { + ImagePreparationMode::UnifiedBudget => PromptImageMode::ORIGINAL_DETAIL, ImagePreparationMode::DetailBased => match detail { - None | Some(ImageDetail::Auto | ImageDetail::High) => { - (ImageDetailSetting::High, PromptImageMode::HIGH_DETAIL) - } - Some(ImageDetail::Original) => ( - ImageDetailSetting::Original, - PromptImageMode::ORIGINAL_DETAIL, - ), + None | Some(ImageDetail::Auto | ImageDetail::High) => PromptImageMode::HIGH_DETAIL, + Some(ImageDetail::Original) => PromptImageMode::ORIGINAL_DETAIL, Some(ImageDetail::Low) => return Err(ImagePreparationError::UnsupportedLowDetail), }, }; @@ -431,11 +384,7 @@ pub(crate) fn resize_image( // image detail field. Responses Lite removes this compatibility hint before sending. *detail = Some(ImageDetail::Original); } - Ok(Some(PreparedInlineImage { - encoded, - effective_detail, - resize, - })) + Ok(Some(PreparedInlineImage { encoded, resize })) } #[cfg(test)] diff --git a/codex-rs/core/src/image_preparation_tests.rs b/codex-rs/core/src/image_preparation_tests.rs index 75a0e2f7..9f9b3803 100644 --- a/codex-rs/core/src/image_preparation_tests.rs +++ b/codex-rs/core/src/image_preparation_tests.rs @@ -161,32 +161,12 @@ async fn preparation_preserves_small_image_bytes_and_replaces_remote_urls() { #[tokio::test(flavor = "multi_thread")] async fn detail_policies_apply_the_expected_budgets() { - for (detail, effective_detail, input_dimensions, expected_dimensions) in [ - ( - Some(ImageDetail::High), - ImageDetailSetting::High, - (2048, 2048), - (1600, 1600), - ), - ( - Some(ImageDetail::Original), - ImageDetailSetting::Original, - (6401, 100), - (6000, 94), - ), - ( - Some(ImageDetail::Original), - ImageDetailSetting::Original, - (3201, 3201), - (3200, 3200), - ), - ( - Some(ImageDetail::Auto), - ImageDetailSetting::High, - (2048, 2048), - (1600, 1600), - ), - (None, ImageDetailSetting::High, (2048, 2048), (1600, 1600)), + for (detail, input_dimensions, expected_dimensions) in [ + (Some(ImageDetail::High), (2048, 2048), (1600, 1600)), + (Some(ImageDetail::Original), (6401, 100), (6000, 94)), + (Some(ImageDetail::Original), (3201, 3201), (3200, 3200)), + (Some(ImageDetail::Auto), (2048, 2048), (1600, 1600)), + (None, (2048, 2048), (1600, 1600)), ] { let (image_url, _) = png_data_url(input_dimensions.0, input_dimensions.1); let mut items = vec![ResponseItem::Message { @@ -202,7 +182,7 @@ async fn detail_policies_apply_the_expected_budgets() { internal_chat_message_metadata_passthrough: None, }]; - let metadata = prepare_response_items( + prepare_response_items( "image-preparation-thread", /*ephemeral*/ false, &mut items, @@ -225,62 +205,9 @@ async fn detail_policies_apply_the_expected_budgets() { panic!("expected image"); }; assert_eq!(decoded_image(image_url).1.dimensions(), expected_dimensions); - assert_eq!( - metadata, - vec![ImagePreparationMetadata { - message_role: Some("user".to_string()), - item_id: None, - effective_detail, - source_width: input_dimensions.0, - source_height: input_dimensions.1, - prepared_width: expected_dimensions.0, - prepared_height: expected_dimensions.1, - }] - ); } } -#[tokio::test(flavor = "multi_thread")] -async fn preparation_reports_tool_output_item_id() { - let call_id = "call-image"; - let (image_url, _) = png_data_url(/*width*/ 64, /*height*/ 32); - let mut items = vec![ResponseItem::FunctionCallOutput { - id: None, - call_id: Some(call_id.to_string()), - name: None, - namespace: None, - output: FunctionCallOutputPayload::from_content_items(vec![ - FunctionCallOutputContentItem::InputImage { - image: ImageReference::Inline { image_url }, - detail: Some(ImageDetail::High), - }, - ]), - internal_chat_message_metadata_passthrough: None, - }]; - let metadata = prepare_response_items( - "image-preparation-thread", - /*ephemeral*/ false, - &mut items, - ImagePreparationMode::DetailBased, - ImageResizeNoticeMode::Disabled, - &InlineAttachmentStore, - ) - .await; - - assert_eq!( - metadata, - vec![ImagePreparationMetadata { - message_role: None, - item_id: Some(call_id.to_string()), - effective_detail: ImageDetailSetting::High, - source_width: 64, - source_height: 32, - prepared_width: 64, - prepared_height: 32, - }] - ); -} - #[tokio::test(flavor = "multi_thread")] async fn upload_failure_keeps_resized_image_inline() { let (image_url, _) = png_data_url(/*width*/ 2048, /*height*/ 2048); diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 0030b398..85442e70 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -42,6 +42,7 @@ mod compact_remote_history; mod compact_remote_v2; mod compact_retained_tool_outputs; mod compact_token_budget; +pub mod compaction_metadata; mod thread_startup_metadata; pub use codex_network_proxy::EnvironmentNetworkPolicy; pub use codex_network_proxy::NetworkDomainPermission; @@ -285,7 +286,6 @@ pub use exec_policy::format_exec_policy_error_with_source; pub use exec_policy::load_exec_policy; pub mod compact; mod memory_usage; -pub mod otel_init; // Captured environment bindings can be passed back to ThreadManager by internal reviewers. pub use environment_selection::TurnEnvironmentSnapshot; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 7e3e4723..659792bd 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -25,11 +25,6 @@ use crate::tools::lifecycle::process_mcp_tool_result; use crate::tools::sandboxing::ApprovalAction; use crate::tools::sandboxing::ToolError; use crate::turn_metadata::ExecutionMetadata; -use codex_analytics::AppInvocation; -use codex_analytics::ElicitationType; -use codex_analytics::InvocationType; -use codex_analytics::McpToolCallElicitation; -use codex_analytics::build_track_events_context; use codex_config::ConfigLayerSource; use codex_config::types::AppToolApproval; use codex_connectors::AppToolPolicy; @@ -48,7 +43,6 @@ use codex_mcp::SandboxState; use codex_mcp::ToolInfo; use codex_mcp::auth_elicitation_completed_result; use codex_mcp::build_auth_elicitation_plan; -use codex_mcp::is_connector_auth_failure_from_tool_result; use codex_mcp::mcp_permission_prompt_is_auto_approved; use codex_prompts::ResolvedModelMessages; use codex_protocol::approvals::ElicitationRequest; @@ -517,7 +511,6 @@ async fn handle_approved_mcp_tool_call( tool_input, }; } - let mut elicitation_type = None; let mut request_error_code = None; let result = async { let result = async { @@ -669,8 +662,6 @@ async fn handle_approved_mcp_tool_call( &tool_input, &result, ); - // Capture trusted server metadata before result callbacks or model-facing rewrites. - elicitation_type = mcp_tool_call_auth_elicitation_type(&server, connector_id, &result); let mcp_tool = McpToolContext::from_prepared_call( &prepared_call, turn_context.config.mcp_servers.get().get(&server), @@ -720,9 +711,6 @@ async fn handle_approved_mcp_tool_call( tracing::warn!("MCP tool call error: {error:?}"); } let duration = start.elapsed(); - if let Some(elicitation_type) = elicitation_type { - track_mcp_tool_call_elicitation(sess, turn_context, call_id, elicitation_type); - } // Direct and Code Mode calls share this boundary. Once an approved call enters // it, conservatively attribute returned errors too: they may contain peer data. let source_connector_id = prepared_call @@ -748,7 +736,6 @@ async fn handle_approved_mcp_tool_call( truncate_mcp_tool_result_for_event(&result), ) .await; - maybe_track_codex_app_used(sess, step_context, &server, &metadata, elicitation_type).await; let outcome = mcp_call_metric_outcome(&result).with_request_error_code(request_error_code); emit_mcp_call_metrics( @@ -1183,74 +1170,6 @@ async fn notify_mcp_tool_call_completed( sess.emit_turn_item_completed(turn_context, item).await; } -async fn maybe_track_codex_app_used( - sess: &Session, - step_context: &StepContext, - server: &str, - metadata: &McpToolApprovalMetadata, - elicitation_type: Option, -) { - if server != CODEX_APPS_MCP_SERVER_NAME { - return; - } - let connector_id = metadata.connector_id.clone(); - let app_name = metadata.connector_name.clone(); - let invocation_type = if let Some(connector_id) = connector_id.as_deref() { - let mentioned_connector_ids = sess.get_connector_selection().await; - if mentioned_connector_ids.contains(connector_id) { - InvocationType::Explicit - } else { - InvocationType::Implicit - } - } else { - InvocationType::Implicit - }; - - let turn_context = &step_context.turn; - let tracking = build_track_events_context( - step_context.settings.model_info.slug.clone(), - sess.thread_id.to_string(), - turn_context.sub_id.clone(), - turn_context.originator.clone(), - Some(turn_context.turn_metadata_state.clone()), - ); - sess.services.analytics_events_client.track_app_used( - tracking, - AppInvocation { - connector_id, - app_name, - invocation_type: Some(invocation_type), - }, - elicitation_type, - ); -} - -fn track_mcp_tool_call_elicitation( - sess: &Session, - turn_context: &TurnContext, - call_id: &str, - elicitation_type: ElicitationType, -) { - sess.services - .analytics_events_client - .track_mcp_tool_call_elicitation(McpToolCallElicitation { - thread_id: sess.thread_id.to_string(), - turn_id: turn_context.sub_id.clone(), - item_id: call_id.to_string(), - elicitation_type, - }); -} - -fn mcp_tool_call_auth_elicitation_type( - server: &str, - connector_id: Option<&str>, - result: &CallToolResult, -) -> Option { - (server == CODEX_APPS_MCP_SERVER_NAME - && is_connector_auth_failure_from_tool_result(result, connector_id)) - .then_some(ElicitationType::AuthOrLink) -} - #[derive(Clone, Copy)] struct McpToolApprovalPolicy { mode: AppToolApproval, @@ -1842,7 +1761,8 @@ pub(crate) async fn request_mcp_tool_user_approval( .as_ref() .map(|rendered_template| rendered_template.question.as_str()), ); - let (request_dispatched, decision, cancellation_reason) = if tool_call_mcp_elicitation_enabled { + let (_request_dispatched, decision, cancellation_reason) = if tool_call_mcp_elicitation_enabled + { let metadata = sess .mcp_tool_approval_metadata(server, id) .map(|context| context.metadata) @@ -1936,14 +1856,6 @@ pub(crate) async fn request_mcp_tool_user_approval( ) }; let decision = normalize_approval_decision_for_mode(decision, *approval_mode); - if request_dispatched - && matches!( - decision, - ReviewDecision::Denied { .. } | ReviewDecision::TimedOut | ReviewDecision::Abort - ) - { - track_mcp_tool_call_elicitation(sess, turn_context, call_id, ElicitationType::Approval); - } ApprovalResolution { cancellation_reason: if decision == ReviewDecision::Abort { cancellation_reason diff --git a/codex-rs/core/src/mcp_tool_call/conversation_history.rs b/codex-rs/core/src/mcp_tool_call/conversation_history.rs index 7a68a956..da6e2969 100644 --- a/codex-rs/core/src/mcp_tool_call/conversation_history.rs +++ b/codex-rs/core/src/mcp_tool_call/conversation_history.rs @@ -167,7 +167,6 @@ impl<'call> ToolExecutor> for HistoryTool { Ok(Box::new(McpToolOutput { result, tool_input: arguments, - result_metadata_capture_allowed: false, wall_time: started.elapsed(), original_image_detail_supported: false, truncation_policy, diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index edee128e..415bad94 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1666,28 +1666,6 @@ fn codex_apps_auth_failure_metadata() -> McpToolApprovalMetadata { ) } -#[test] -fn codex_apps_auth_classification_requires_the_trusted_server_and_connector() { - let result = codex_apps_auth_failure_result(); - - assert_eq!( - mcp_tool_call_auth_elicitation_type( - "untrusted_mcp_server", - Some("connector_calendar"), - &result, - ), - None - ); - assert_eq!( - mcp_tool_call_auth_elicitation_type( - CODEX_APPS_MCP_SERVER_NAME, - Some("connector_drive"), - &result, - ), - None - ); -} - #[tokio::test] async fn codex_apps_auth_elicitation_feature_disabled_returns_original_result() { let (session, mut turn_context, rx_event) = make_session_and_context_with_rx().await; diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs deleted file mode 100644 index 1fc9a05a..00000000 --- a/codex-rs/core/src/otel_init.rs +++ /dev/null @@ -1,113 +0,0 @@ -use crate::config::Config; -use codex_config::types::OtelExporterKind as Kind; -use codex_config::types::OtelHttpProtocol as Protocol; -use codex_features::Feature; -use codex_login::default_client::originator; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; -use codex_otel::OtelTlsConfig as OtelTlsSettings; -use std::error::Error; - -/// Build an OpenTelemetry provider from the app Config. -/// -/// Returns `None` when OTEL export is disabled. -pub fn build_provider( - config: &Config, - service_version: &str, - service_name_override: Option<&str>, - default_analytics_enabled: bool, -) -> Result, Box> { - let to_otel_exporter = |kind: &Kind| match kind { - Kind::None => OtelExporter::None, - Kind::Statsig => OtelExporter::Statsig, - Kind::OtlpHttp { - endpoint, - headers, - protocol, - tls, - } => { - let protocol = match protocol { - Protocol::Json => OtelHttpProtocol::Json, - Protocol::Binary => OtelHttpProtocol::Binary, - }; - - OtelExporter::OtlpHttp { - endpoint: endpoint.clone(), - headers: headers - .iter() - .map(|(name, value)| (name.clone(), value.as_str().to_owned())) - .collect(), - protocol, - tls: tls.as_ref().map(|config| OtelTlsSettings { - ca_certificate: config.ca_certificate.clone(), - client_certificate: config.client_certificate.clone(), - client_private_key: config.client_private_key.clone(), - }), - } - } - Kind::OtlpGrpc { - endpoint, - headers, - tls, - } => OtelExporter::OtlpGrpc { - endpoint: endpoint.clone(), - headers: headers - .iter() - .map(|(name, value)| (name.clone(), value.as_str().to_owned())) - .collect(), - tls: tls.as_ref().map(|config| OtelTlsSettings { - ca_certificate: config.ca_certificate.clone(), - client_certificate: config.client_certificate.clone(), - client_private_key: config.client_private_key.clone(), - }), - }, - }; - - let exporter = to_otel_exporter(&config.otel.exporter); - let trace_exporter = to_otel_exporter(&config.otel.trace_exporter); - // Analytics consent controls the built-in exporter, not explicit OTLP collectors. - let metrics_exporter = if matches!(config.otel.metrics_exporter, Kind::Statsig) - && !config - .analytics_enabled - .unwrap_or(default_analytics_enabled) - { - OtelExporter::None - } else { - to_otel_exporter(&config.otel.metrics_exporter) - }; - - let originator = originator(); - let service_name = service_name_override.unwrap_or(originator.value.as_str()); - let runtime_metrics = config.features.enabled(Feature::RuntimeMetrics); - - OtelProvider::try_new(&OtelSettings { - http_client_factory: config.http_client_factory(), - service_name: service_name.to_string(), - service_version: service_version.to_string(), - codex_home: config.codex_home.to_path_buf(), - environment: config.otel.environment.to_string(), - exporter, - trace_exporter, - metrics_exporter, - runtime_metrics, - span_attributes: config.otel.span_attributes.clone(), - tracestate: config.otel.tracestate.clone(), - }) -} - -pub fn record_process_start(otel: Option<&OtelProvider>, originator: &str) { - let Some(metrics) = otel.and_then(OtelProvider::metrics) else { - return; - }; - let _ = codex_otel::record_process_start_once(metrics, originator); -} - -pub fn install_sqlite_telemetry(otel: Option<&OtelProvider>, originator: &str) { - let Some(metrics) = otel.and_then(OtelProvider::metrics) else { - return; - }; - let telemetry = codex_rollout::sqlite_telemetry_recorder(metrics.clone(), originator); - let _ = codex_state::install_process_db_telemetry(telemetry); -} diff --git a/codex-rs/core/src/plugins/metrics.rs b/codex-rs/core/src/plugins/metrics.rs deleted file mode 100644 index c6e7063c..00000000 --- a/codex-rs/core/src/plugins/metrics.rs +++ /dev/null @@ -1,62 +0,0 @@ -use crate::session::session::Session; -use crate::session::turn_context::TurnContext; -use crate::tools::sandboxing::ToolCtx; -use codex_analytics::PluginMeasurementsInput; -use codex_core_plugins::PluginMetricsSidecar; -use codex_exec_server::Environment; -use codex_protocol::items::ModelInvocationContext; -use codex_utils_path_uri::PathUri; - -/// Creates a metrics sidecar for one plugin command. -pub(crate) async fn sidecar_for_command( - ctx: &ToolCtx, - command: &[String], - cwd: &PathUri, - environment: &Environment, -) -> Option { - if !ctx.session.services.analytics_events_client.is_enabled() { - return None; - } - let resolved = ctx - .step_context - .turn - .plugin_metrics_operation_for_command(command, cwd, environment) - .await?; - if environment.is_remote() { - PluginMetricsSidecar::create_remote(environment, resolved).await - } else { - PluginMetricsSidecar::create(resolved) - } -} - -/// Finishes a metrics sidecar and publishes any valid rows. -pub(crate) async fn finish_and_track_measurements( - metrics_sidecar: Option, - exit_code: i32, - session: &Session, - turn: &TurnContext, - model_context: &ModelInvocationContext, - item_id: &str, -) { - let Some(metrics_sidecar) = metrics_sidecar else { - return; - }; - let Some(batch) = metrics_sidecar.finish(exit_code).await else { - return; - }; - session - .services - .analytics_events_client - .track_plugin_measurements(PluginMeasurementsInput { - thread_id: session.thread_id().to_string(), - turn_id: turn.sub_id.clone(), - item_id: item_id.to_string(), - originator: turn.originator.clone(), - model_slug: Some(model_context.model_slug.clone()), - reasoning_effort: model_context.reasoning_effort.clone(), - plugin_id: batch.plugin_id, - execution_id: batch.execution_id, - operation: batch.operation, - rows: batch.rows, - }); -} diff --git a/codex-rs/core/src/plugins/mod.rs b/codex-rs/core/src/plugins/mod.rs index 856083aa..d20464a3 100644 --- a/codex-rs/core/src/plugins/mod.rs +++ b/codex-rs/core/src/plugins/mod.rs @@ -1,7 +1,6 @@ mod discoverable; mod injection; mod mentions; -pub(crate) mod metrics; mod render; #[cfg(test)] #[path = "skill_snapshot_tests.rs"] diff --git a/codex-rs/core/src/prompt_debug.rs b/codex-rs/core/src/prompt_debug.rs index 9a8b6d82..7a595cc0 100644 --- a/codex-rs/core/src/prompt_debug.rs +++ b/codex-rs/core/src/prompt_debug.rs @@ -67,7 +67,6 @@ pub async fn build_prompt_input( ), extensions, user_instructions_provider, - /*analytics_events_client*/ None, crate::thread_manager::passthrough_image_store(), thread_store, crate::local_agent_graph_store_from_state_db(state_db.as_ref()), diff --git a/codex-rs/core/src/responses_metadata.rs b/codex-rs/core/src/responses_metadata.rs index 8f886779..840b27ea 100644 --- a/codex-rs/core/src/responses_metadata.rs +++ b/codex-rs/core/src/responses_metadata.rs @@ -2,11 +2,11 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::io::ErrorKind; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionStrategy; -use codex_analytics::CompactionTrigger; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionStrategy; +use crate::compaction_metadata::CompactionTrigger; use codex_git_utils::SanitizedGitUrl; use codex_protocol::ContextWindowId; use codex_protocol::ThreadId; @@ -43,7 +43,9 @@ pub(crate) const LEGACY_CODE_MODE_TOOL_NAMES_KEY: &str = "code_mode_tool_names"; pub(crate) const TOOL_NAMESPACES_INFO_KEY: &str = "tool_namespaces_info"; pub(crate) const TURN_STARTED_AT_UNIX_MS_KEY: &str = "turn_started_at_unix_ms"; pub(crate) const HISTORY_INGEST_REQUESTED_KEY: &str = "history_ingest_requested"; -pub(crate) const ANALYTICS_ENABLED_KEY: &str = "analytics_enabled"; +// Formerly reported the session's usage-data collection state. Usage-data reporting was removed; +// the key stays reserved so configured or client metadata cannot reintroduce it. +pub(crate) const LEGACY_USAGE_DATA_ENABLED_KEY: &str = "analytics_enabled"; pub(crate) const HISTORY_INITIALIZATION_KEY: &str = "history_initialization"; pub(crate) const MCP_ATTRIBUTION_CLIENT_METADATA_KEY: &str = "mcp_attribution"; pub(crate) const MAX_MCP_ATTRIBUTION_BYTES: usize = 16 * 1024; @@ -88,7 +90,7 @@ const RESERVED_METADATA_KEYS: &[&str] = &[ TOOL_NAMESPACES_INFO_KEY, TURN_STARTED_AT_UNIX_MS_KEY, HISTORY_INGEST_REQUESTED_KEY, - ANALYTICS_ENABLED_KEY, + LEGACY_USAGE_DATA_ENABLED_KEY, HISTORY_INITIALIZATION_KEY, FORKED_FROM_THREAD_ID_KEY, FORKED_FROM_ORDINAL_EXCLUSIVE_KEY, @@ -112,7 +114,7 @@ const BACKWARD_COMPATIBLE_RESERVED_METADATA_KEYS: &[&str] = &[ "guardian_recorded_items", WINDOW_NUMBER_KEY, FORKED_FROM_ORDINAL_EXCLUSIVE_KEY, - ANALYTICS_ENABLED_KEY, + LEGACY_USAGE_DATA_ENABLED_KEY, ]; const MAX_EXTRA_METADATA_ENTRIES: usize = 16; const MAX_EXTRA_METADATA_KEY_BYTES: usize = 64; @@ -122,7 +124,7 @@ pub(crate) const MAX_EXTRA_METADATA_VALUE_BYTES: usize = 128; /// /// This covers both local and remote compaction requests sent through the `/responses` path. These /// fields describe the operation at dispatch time. Post-response outcomes such as status, error, -/// duration, and token deltas remain in compaction analytics events. +/// duration, and token deltas are not reported anywhere. #[derive(Clone, Copy, Debug, Serialize)] pub(crate) struct CompactionTurnMetadata { trigger: CompactionTrigger, @@ -269,9 +271,6 @@ pub struct CodexResponsesMetadata { pub(crate) tool_namespaces_info: Option, pub(crate) turn_started_at_unix_ms: Option, pub(crate) history_ingest_requested: Option, - /// Selected session analytics client's collection state, independent of event eligibility or delivery. - /// Absent when the request has no initialized session analytics context. - pub(crate) analytics_enabled: Option, /// Cumulative MCP attribution for this logical request; body-only and model-invisible. pub(crate) mcp_attribution: Option, pub(crate) extra: BTreeMap, @@ -317,7 +316,6 @@ impl CodexResponsesMetadata { tool_namespaces_info: None, turn_started_at_unix_ms: None, history_ingest_requested: None, - analytics_enabled: None, mcp_attribution: None, extra: BTreeMap::new(), } @@ -460,7 +458,6 @@ impl CodexResponsesMetadata { tool_namespaces_info: self.tool_namespaces_info.as_ref(), turn_started_at_unix_ms: self.turn_started_at_unix_ms, history_ingest_requested: self.history_ingest_requested, - analytics_enabled: self.analytics_enabled, compaction, // Extra metadata enriches the Codex turn metadata blob, not literal top-level // Responses client_metadata. Product metadata is validated while loading config; @@ -612,8 +609,6 @@ struct CodexTurnMetadataPayload<'a> { #[serde(default, skip_serializing_if = "Option::is_none")] history_ingest_requested: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - analytics_enabled: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] compaction: Option, #[serde(flatten)] extra: &'a BTreeMap, diff --git a/codex-rs/core/src/session/active_plugin_inventory_tests.rs b/codex-rs/core/src/session/active_plugin_inventory_tests.rs deleted file mode 100644 index 4c143368..00000000 --- a/codex-rs/core/src/session/active_plugin_inventory_tests.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! Tests source-aware plugin telemetry selection and complete-inventory bounds. - -use crate::session::tests::make_session_and_context; -use codex_extension_api::SelectedPluginIdentity; -use codex_extension_api::SelectedPluginSnapshot; -use codex_utils_plugins::PluginIdentity; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn active_plugin_ids_select_and_validate_by_source() { - let (_session, mut turn_context) = make_session_and_context().await; - for (name, identities, selected_ids, expected) in [ - ( - "remote wins even when the package fallback is invalid", - vec![ - ("box@local", Some("plugins~Plugin_box")), - ("selected-root", Some("plugin_box-1")), - ], - vec![], - Some(vec!["plugin_box-1", "plugins~Plugin_box"]), - ), - ( - "package fallback", - vec![("my.tool@123", None)], - vec!["executor-demo@1"], - Some(vec!["executor-demo@1", "my.tool@123"]), - ), - ( - "blank present remote", - vec![("box@local", Some(""))], - vec![], - None, - ), - ( - "remote is not trimmed", - vec![("box@local", Some(" plugin_box "))], - vec![], - None, - ), - ( - "package key is not a remote ID", - vec![("box@local", Some("box@local"))], - vec![], - None, - ), - ( - "remote-looking selected root is still a fallback", - vec![], - vec!["plugins~Plugin_box"], - None, - ), - ( - "one invalid identity makes the inventory unknown", - vec![("box@local", Some("plugin_box")), ("bad..name@1", None)], - vec![], - None, - ), - ( - "exact deduplication retains aliases and distinct remote objects", - vec![ - ("box@local", Some("plugins~Plugin_b")), - ("box@local", None), - ("box@local", Some("plugins~Plugin_a")), - ("box@other", Some("plugins~Plugin_a")), - ], - vec!["box@local", "box@local"], - Some(vec!["box@local", "plugins~Plugin_a", "plugins~Plugin_b"]), - ), - ("empty observation", vec![], vec![], Some(vec![])), - ] { - let identities = identities - .into_iter() - .map(|(plugin_id, remote_plugin_id)| PluginIdentity { - plugin_id: plugin_id.to_string(), - remote_plugin_id: remote_plugin_id.map(str::to_string), - }) - .collect(); - let selected_plugins = selected_ids - .into_iter() - .map(|plugin_id| SelectedPluginIdentity { - selected_root_id: Some("capability-root".to_string()), - plugin_id: codex_core_plugins::PluginIdentity::Local { - plugin_id: plugin_id.to_string(), - }, - }) - .collect::>(); - turn_context.active_host_plugin_identities = Some(identities); - let selected_plugins = SelectedPluginSnapshot { - plugins: selected_plugins, - ..Default::default() - }; - assert_eq!( - turn_context.active_plugin_ids_for_telemetry(Some(&selected_plugins)), - expected.map(|ids| ids.into_iter().map(str::to_string).collect::>()), - "{name}" - ); - } -} - -#[tokio::test] -async fn active_plugin_ids_enforce_bounds_after_selection_and_deduplication() { - let (_session, mut turn_context) = make_session_and_context().await; - for length in [128, 129] { - for remote in [false, true] { - let id = if remote { - "r".repeat(length) - } else { - format!("{}@local", "p".repeat(length - 6)) - }; - // A remote ID also wins over an overlong package key. - let plugin_id = if remote { - format!("{}@local", "p".repeat(/*n*/ 128)) - } else { - id.clone() - }; - let identities = vec![PluginIdentity { - plugin_id, - remote_plugin_id: remote.then_some(id.clone()), - }]; - turn_context.active_host_plugin_identities = Some(identities); - assert_eq!( - turn_context.active_plugin_ids_for_telemetry(/*selected*/ None), - (length == 128).then_some(vec![id]), - "length={length}, remote={remote}" - ); - } - let id = format!("{}@local", "p".repeat(length - 6)); - let selected_plugin = SelectedPluginIdentity { - selected_root_id: Some("capability-root".to_string()), - plugin_id: codex_core_plugins::PluginIdentity::Local { - plugin_id: id.clone(), - }, - }; - turn_context.active_host_plugin_identities = Some(Vec::new()); - let selected_plugins = SelectedPluginSnapshot { - plugins: vec![selected_plugin], - ..Default::default() - }; - assert_eq!( - turn_context.active_plugin_ids_for_telemetry(Some(&selected_plugins)), - (length == 128).then_some(vec![id]), - "selected length={length}" - ); - } - - for count in [512, 513] { - let ids = (0..count) - .map(|index| format!("plugin_{index:03}@local")) - .collect::>(); - let identities = ids[..count / 2] - .iter() - .map(|id| PluginIdentity { - plugin_id: id.clone(), - remote_plugin_id: None, - }) - .collect(); - let selected_plugins = ids[count / 2 - 1..] - .iter() - .map(|id| SelectedPluginIdentity { - selected_root_id: Some("capability-root".to_string()), - plugin_id: codex_core_plugins::PluginIdentity::Local { - plugin_id: id.clone(), - }, - }) - .collect::>(); - turn_context.active_host_plugin_identities = Some(identities); - let selected_plugins = SelectedPluginSnapshot { - plugins: selected_plugins, - ..Default::default() - }; - assert_eq!( - turn_context.active_plugin_ids_for_telemetry(Some(&selected_plugins)), - (count == 512).then_some(ids), - "{count} distinct IDs across host and selected inputs, with one overlap" - ); - } -} diff --git a/codex-rs/core/src/session/async_compaction.rs b/codex-rs/core/src/session/async_compaction.rs index 98a28dba..6ce37156 100644 --- a/codex-rs/core/src/session/async_compaction.rs +++ b/codex-rs/core/src/session/async_compaction.rs @@ -8,12 +8,12 @@ use std::sync::Arc; use crate::compact_remote_v2::BackgroundCompactionCandidate; use crate::compact_remote_v2::capture_background_input; use crate::compact_remote_v2::run_background_compaction; +use crate::compaction_metadata::CompactionPhase; use crate::context::world_state::WorldState; use crate::session::context_window::ContextWindowTokenStatus; use crate::session::session::Session; use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; -use codex_analytics::CompactionPhase; use codex_features::Feature; use codex_model_provider::RemoteCompactionSupport; use codex_otel::auth_storage::AuthStorageOriginator; diff --git a/codex-rs/core/src/session/async_compaction_tests.rs b/codex-rs/core/src/session/async_compaction_tests.rs index 90bae90d..84b0ed51 100644 --- a/codex-rs/core/src/session/async_compaction_tests.rs +++ b/codex-rs/core/src/session/async_compaction_tests.rs @@ -1,8 +1,8 @@ //! Background compaction eligibility and cancellation. use super::*; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionTrigger; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use codex_login::CodexAuth; use codex_protocol::models::AudioReference; use codex_protocol::models::ContentItem; diff --git a/codex-rs/core/src/session/extension_interruption_tests.rs b/codex-rs/core/src/session/extension_interruption_tests.rs index 319da2a2..fda290ad 100644 --- a/codex-rs/core/src/session/extension_interruption_tests.rs +++ b/codex-rs/core/src/session/extension_interruption_tests.rs @@ -26,7 +26,7 @@ async fn interrupt_with_warning_exports_turn_profile_under_caller_span() -> anyh tracing_opentelemetry::layer() .with_tracer(provider.tracer("guardian-interrupt-test")) .with_filter(tracing_subscriber::filter::filter_fn( - codex_otel::OtelProvider::trace_export_filter, + codex_otel::trace_export_filter, )), ); let _interest_cache_guard = diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs index dab028d7..ccbd548b 100644 --- a/codex-rs/core/src/session/inject.rs +++ b/codex-rs/core/src/session/inject.rs @@ -1,7 +1,6 @@ use super::TurnInput as PendingTurnInput; use super::session::Session; use super::turn_context::TurnContext; -use codex_analytics::ImagePreparationMetadata; use codex_features::Feature; use codex_history::ResponseItemEnvelope; use codex_protocol::error::CodexErr; @@ -153,16 +152,11 @@ impl Session { return; } - let (annotated_items, image_preparations) = self + let annotated_items = self .prepare_annotated_conversation_items_for_history(turn_context, model_info, items) .await; - self.record_prepared_conversation_items( - turn_context, - model_info, - annotated_items, - image_preparations, - ) - .await; + self.record_prepared_conversation_items(turn_context, model_info, annotated_items) + .await; } pub(crate) async fn prepare_annotated_conversation_items_for_history( @@ -170,18 +164,16 @@ impl Session { turn_context: &TurnContext, model_info: &ModelInfo, items: Vec, - ) -> (Vec, Vec) { + ) -> Vec { let mut annotated_items = Vec::with_capacity(items.len()); - let mut image_preparations = Vec::new(); for envelope in items { - let (prepared_items, prepared_images) = self + let prepared_items = self .prepare_conversation_items_for_history( turn_context, model_info, std::slice::from_ref(&envelope.item), ) .await; - image_preparations.extend(prepared_images); let mut metadata = envelope.metadata; annotated_items.extend(prepared_items.into_iter().map(|item| ResponseItemEnvelope { @@ -189,7 +181,7 @@ impl Session { metadata: metadata.take(), })); } - (annotated_items, image_preparations) + annotated_items } /// Injects items into active work, or records them without starting a turn. diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index c1e6f2ba..8be464e6 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -1209,7 +1209,8 @@ async fn review_guardian_mcp_elicitation( crate::guardian::GuardianReviewOptions { require_guardian: strict_auto_review, plugin_attribution_override: None, - approval_request_source: codex_analytics::GuardianApprovalRequestSource::MainTurn, + approval_request_source: + codex_guardian_reviewer::GuardianApprovalRequestSource::MainTurn, external_cancel: Some(cancellation_token), require_synchronous_review, }, diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 814799a5..ff5fb698 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -62,15 +62,8 @@ use crate::turn_metadata::TurnMetadataState; use crate::turn_timing::now_unix_timestamp_ms; use async_channel::Receiver; use async_channel::Sender; -use chrono::DateTime; use chrono::Local; use chrono::Utc; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::ImagePreparationFact; -use codex_analytics::ImagePreparationMetadata; -use codex_analytics::SubAgentThreadStartedInput; -use codex_analytics::ThreadInitializationMode; -use codex_analytics::TurnCodexErrorFact; use codex_async_utils::OrCancelExt; use codex_attachment_store::AttachmentStore; use codex_attachment_store::InlineAttachmentStore; @@ -111,7 +104,6 @@ use codex_otel::set_parent_from_w3c_trace_context; use codex_prompts::ResolvedModelMessages; use codex_prompts::render_model_instructions; use codex_protocol::ResponseUsageMetadata; -use codex_protocol::SessionId; use codex_protocol::ThreadId; use codex_protocol::approvals::ElicitationRequest; use codex_protocol::approvals::ElicitationRequestEvent; @@ -236,7 +228,6 @@ use crate::config::StartedNetworkProxy; use crate::config::resolve_web_search_mode_for_turn; use crate::context_manager::ContextManager; use crate::context_manager::HistoryReplacement; -use crate::thread_rollout_truncation::initial_history_has_prior_user_turns; use codex_config::CONFIG_TOML_FILE; use codex_config::ConfigLayerSource; use codex_config::types::McpServerConfig; @@ -303,7 +294,6 @@ pub(crate) use self::input_queue::TurnInput; pub(crate) use self::input_queue::TurnInputQueue; pub(crate) use self::input_queue::UserInputMetadata; use self::review::spawn_review_thread; -use self::session::AppServerClientMetadata; use self::session::Session; use self::session::SessionConfiguration; use self::session::SessionSettingsCommit; @@ -553,7 +543,6 @@ pub(crate) struct SessionSpawnArgs { pub(crate) turn_extension_init: ExtensionDataInit, pub(crate) client_mcp_extensions: ClientMcpExtensions, pub(crate) reserved_thread_id: Option, - pub(crate) analytics_events_client: Option, pub(crate) image_store: Arc, pub(crate) thread_store: Arc, pub(crate) attestation_provider: Option>, @@ -719,7 +708,6 @@ impl Session { turn_extension_init, client_mcp_extensions, reserved_thread_id, - analytics_events_client, image_store, thread_store, attestation_provider, @@ -1087,7 +1075,6 @@ impl Session { reserved_thread_id, environment_manager, inherited_environments, - analytics_events_client, image_store, thread_store, resume_preparation, @@ -1381,17 +1368,6 @@ async fn thread_title_from_thread_store( } impl Session { - pub(crate) async fn app_server_client_metadata(&self) -> AppServerClientMetadata { - let state = self.state.lock().await; - AppServerClientMetadata { - client_name: state.session_configuration.app_server_client_name.clone(), - client_version: state - .session_configuration - .app_server_client_version - .clone(), - } - } - fn managed_network_proxy_active_for_permission_profile( permission_profile: &PermissionProfile, ) -> bool { @@ -1664,11 +1640,6 @@ impl Session { state.auto_compact_window_snapshot() } - pub(crate) async fn estimated_tokens_since_last_usage(&self) -> i64 { - let state = self.state.lock().await; - state.history.estimated_tokens_since_last_usage() - } - pub(crate) async fn total_token_usage(&self) -> Option { let state = self.state.lock().await; state.token_info().map(|info| info.total_token_usage) @@ -1736,11 +1707,6 @@ impl Session { } // Returns the connector IDs currently selected for this session. - pub(crate) async fn get_connector_selection(&self) -> HashSet { - let state = self.state.lock().await; - state.get_connector_selection() - } - // Clears connector IDs that were accumulated for explicit selection. pub(crate) async fn clear_connector_selection(&self) { let mut state = self.state.lock().await; @@ -1762,11 +1728,6 @@ impl Session { ), ) }; - let has_prior_user_turns = initial_history_has_prior_user_turns(&conversation_history); - { - let mut state = self.state.lock().await; - state.set_next_turn_is_first(!has_prior_user_turns); - } let turn_context = match conversation_history { InitialHistory::New | InitialHistory::Cleared => { // Defer initial context insertion until the first real turn starts so @@ -2644,17 +2605,6 @@ impl Session { } } - /// Record a terminal CodexErr before the app-server completion notification is reduced. - pub(crate) fn track_turn_codex_error(&self, turn_context: &TurnContext, error: &CodexErr) { - self.services - .analytics_events_client - .track_turn_codex_error(TurnCodexErrorFact::from_codex_err( - self.thread_id.to_string(), - turn_context.sub_id.clone(), - error, - )); - } - /// Returns the reviewer pool installed by the Guardian extension. pub(crate) fn guardian_review_session(&self) -> Option> { self.services @@ -2737,24 +2687,6 @@ impl Session { id: turn_context.sub_id.clone(), msg, }; - // Private reviewers have no app-server listener; publicly resumed Guardian threads do. - if matches!( - &turn_context.session_source, - SessionSource::SubAgent(SubAgentSource::Other(name)) - if name == crate::guardian::GUARDIAN_REVIEWER_NAME - ) && self.services.analytics_events_client.is_enabled() - && turn_context.parent_thread_id.is_some() - && self - .state - .lock() - .await - .session_configuration - .trusted_guardian_reviewer - { - self.services - .analytics_events_client - .track_guardian_session_event(self.thread_id, &event); - } self.send_event_raw(event).await; self.maybe_publish_terminal_agent_result(turn_context, &legacy_source) .await; @@ -3916,7 +3848,7 @@ impl Session { turn_context: &TurnContext, model_info: &ModelInfo, items: &[ResponseItem], - ) -> (Vec, Vec) { + ) -> Vec { let mut items = items.to_vec(); let image_preparation_mode = if unified_image_budget_enabled(&turn_context.config.features, model_info) { @@ -3934,7 +3866,7 @@ impl Session { ImageResizeNoticeMode::Disabled }; // Keep nested image-upload futures out of every caller's future frame. - let image_preparations = Box::pin(prepare_image_response_items( + Box::pin(prepare_image_response_items( &self.thread_id.to_string(), turn_context.config.ephemeral, &mut items, @@ -3949,7 +3881,7 @@ impl Session { Self::stamp_response_item_for_history(item, &turn_context.sub_id); self.assign_missing_response_item_id(item); } - (items, image_preparations) + items } pub(crate) fn assign_missing_response_item_id(&self, item: &mut ResponseItem) { @@ -4010,17 +3942,12 @@ impl Session { model_info: &ModelInfo, items: &[ResponseItem], ) { - let (items, image_preparations) = self + let items = self .prepare_conversation_items_for_history(turn_context, model_info, items) .await; let items = items.into_iter().map(ResponseItemEnvelope::new).collect(); - self.record_prepared_conversation_items( - turn_context, - model_info, - items, - image_preparations, - ) - .await; + self.record_prepared_conversation_items(turn_context, model_info, items) + .await; } async fn record_prepared_conversation_items( @@ -4028,7 +3955,6 @@ impl Session { turn_context: &TurnContext, model_info: &ModelInfo, mut items: Vec, - image_preparations: Vec, ) { // Save the originating history budget for replay. // Preserve any existing tool-specific override. @@ -4125,14 +4051,6 @@ impl Session { .history .record_annotated_items(&mut items, model_info.truncation_policy.into()); } - for image in image_preparations { - self.services - .analytics_events_client - .track_image_preparation(ImagePreparationFact { - turn_id: turn_context.sub_id.clone(), - metadata: image, - }); - } let settings_guard = if force_mcp_checkpoint && self.reference_context_item().await.is_none() { Some(thread_settings::acquire_persistence_lock(self).await) @@ -4603,7 +4521,7 @@ impl Session { ] }); } - let (items, _) = self + let items = self .prepare_conversation_items_for_history( turn_context, model_info, @@ -5877,7 +5795,7 @@ impl Session { codex_history::HEARTBEAT_CONTENT_KIND.to_owned(), )]); } - let (prepared_items, image_preparations) = self + let prepared_items = self .prepare_annotated_conversation_items_for_history( turn_context, model_info, @@ -5896,13 +5814,8 @@ impl Session { &prepared_items, &user_image_content_indices, ); - self.record_prepared_conversation_items( - turn_context, - model_info, - prepared_items, - image_preparations, - ) - .await; + self.record_prepared_conversation_items(turn_context, model_info, prepared_items) + .await; user_message_item.client_id = client_id; let turn_item = TurnItem::UserMessage(user_message_item); self.emit_turn_item_started(turn_context, &turn_item).await; @@ -6026,54 +5939,6 @@ fn apply_prepared_image_file_ids( } } -#[allow(clippy::too_many_arguments)] -pub(crate) fn emit_subagent_session_started( - analytics_events_client: &AnalyticsEventsClient, - client_metadata: AppServerClientMetadata, - session_id: SessionId, - thread_id: ThreadId, - parent_thread_id: Option, - thread_config: ThreadConfigSnapshot, - subagent_source: SubAgentSource, - resumed_created_at: Option>, -) { - let initialization_mode = if resumed_created_at.is_some() { - ThreadInitializationMode::Resumed - } else { - ThreadInitializationMode::New - }; - let created_at = - u64::try_from(resumed_created_at.unwrap_or_else(Utc::now).timestamp()).unwrap_or_default(); - let AppServerClientMetadata { - client_name, - client_version, - } = client_metadata; - if (client_name.is_none() || client_version.is_none()) - && subagent_source.kind() != crate::guardian::GUARDIAN_REVIEWER_NAME - { - tracing::warn!("skipping subagent thread analytics: missing inherited client metadata"); - return; - } - let input = SubAgentThreadStartedInput { - session_id: session_id.to_string(), - thread_id: thread_id.to_string(), - parent_thread_id: parent_thread_id.map(|thread_id| thread_id.to_string()), - forked_from_thread_id: thread_config - .forked_from_thread_id - .map(|thread_id| thread_id.to_string()), - product_client_id: thread_config.originator.clone(), - client_name, - client_version, - model: thread_config.model, - ephemeral: thread_config.ephemeral, - thread_source: thread_config.thread_source, - subagent_source, - initialization_mode, - created_at, - }; - analytics_events_client.track_subagent_thread_started(input); -} - /// Builds hook configuration for one config snapshot, including any enabled plugin hooks. async fn build_hooks_config( config: &Config, diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index fae3bab5..2e5d1b0f 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -26,7 +26,6 @@ use crate::shell_snapshot::ShellSnapshot; use crate::shell_snapshot::SnapshotCredentialBrokerState; use crate::state::ActiveTurn; use crate::turn_metadata::ExecutionMetadata; -use codex_analytics::ThreadProductUpdate; use codex_attachment_store::AttachmentStore; use codex_extension_api::ExtensionDataInit; use codex_login::auth::AgentIdentityAuthPolicy; @@ -179,9 +178,9 @@ pub(crate) struct SessionConfiguration { pub(super) forked_from_thread_id: Option, /// Immediate control/spawn parent for this thread, when it has one. pub(super) parent_thread_id: Option, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub(super) thread_source: Option, - /// Effective originator used for this thread's Responses requests and analytics events. + /// Effective originator used for this thread's Responses requests. pub(super) originator: String, /// Active tools used to build the next model request. pub(crate) dynamic_tools: Arc<[DynamicToolSpec]>, @@ -685,11 +684,6 @@ pub(crate) struct SessionSettingsUpdate { pub(crate) disabled_plugin_ids: Option>, } -pub(crate) struct AppServerClientMetadata { - pub(crate) client_name: Option, - pub(crate) client_version: Option, -} - async fn warm_plugins_and_skills_for_session_init( config: Arc, plugins_manager: Arc, @@ -874,7 +868,6 @@ impl Session { window_number: Some(window_number), context_window_id: Some(context_window_id), mcp_attribution: Some(self.services.executed_tool_calls.mcp_attribution_snapshot()), - analytics_enabled: Some(self.services.analytics_events_client.is_enabled()), history_ingest_requested: turn_context .config .token_budget @@ -922,7 +915,6 @@ impl Session { reserved_thread_id: Option, environment_manager: Arc, inherited_environments: Option, - analytics_events_client: Option, image_store: Arc, thread_store: Arc, resume_preparation: Option, @@ -1740,7 +1732,9 @@ impl Session { config.permissions.permission_profile(), config.effective_local_windows_sandbox_type(), network_policy_decider.as_ref().map(Arc::clone), - Some(build_blocked_request_observer(Arc::clone(&network_approval))), + Some(build_blocked_request_observer(Arc::clone( + &network_approval, + ))), managed_network_requirements_configured, network_proxy_audit_metadata.clone(), ) @@ -1795,45 +1789,6 @@ impl Session { }); } - let analytics_events_client = if config.analytics_enabled == Some(false) { - if let Some(client) = &analytics_events_client { - client.update_thread_product_sku(thread_id, ThreadProductUpdate::Clear); - } - AnalyticsEventsClient::disabled() - } else { - analytics_events_client.unwrap_or_else(|| { - let api_key_headers = if codex_model_provider::provider_uses_first_party_auth_path( - &config.model_provider, - ) { - match config.model_provider.build_header_map() { - Ok(headers) => headers, - Err(error) => { - tracing::warn!(%error, "failed to resolve analytics resource selectors"); - return AnalyticsEventsClient::disabled(); - } - } - } else { - Default::default() - }; - AnalyticsEventsClient::new_with_runtime( - Arc::clone(&auth_manager), - config.chatgpt_backend_url(), - config.analytics_enabled, - config - .features - .enabled(Feature::RuntimeAgentInstances) - .then(|| (Arc::clone(&runtime_auth), config.runtime_auth_mode)), - api_key_headers, - ) - }) - }; - analytics_events_client.update_thread_product_sku( - thread_id, - match &config.apps_mcp_product_sku { - Some(product) => ThreadProductUpdate::Set(product.clone()), - None => ThreadProductUpdate::Clear, - }, - ); for item in initial_history.get_rollout_items() { match item { RolloutItem::Compacted(compacted) => { @@ -1857,7 +1812,6 @@ impl Session { } let session_extension_data = codex_extension_api::ExtensionData::new(session_id.to_string()); - session_extension_data.insert(analytics_events_client.clone()); session_extension_data.insert(session_telemetry.clone()); let mcp_resource_client = Arc::new(McpResourceClient::new(Arc::clone(&mcp_runtime))); let extension_metrics = @@ -1986,7 +1940,6 @@ impl Session { config.background_terminal_max_timeout, ), elicitations: crate::elicitation::ElicitationService::new(), - analytics_events_client, hooks: arc_swap::ArcSwap::from_pointee(hooks), rollout_thread_trace, user_shell: Arc::new(default_shell), diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 54e4a1c8..a800a3a5 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -25,6 +25,10 @@ use super::*; mod config_refresh_tests; use crate::agents_md_manager::AgentsMdManager; use crate::agents_md_manager::SessionInstructions; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::RuntimeConfigRefresh; @@ -44,10 +48,6 @@ use crate::shell_snapshot::ShellSnapshot; use crate::test_support::models_manager_with_provider; use crate::tools::format_exec_output_str; use crate::tools::registry::ToolRegistry; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionTrigger; use codex_config::ConfigLayerStack; use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID; use codex_config::LoaderOverrides; @@ -386,7 +386,7 @@ async fn default_turn_context_assigns_missing_response_item_ids() { tools: Arc::from([]), }, ]; - let (items, _) = session + let items = session .prepare_conversation_items_for_history(&turn_context, turn_context.model_info(), &items) .await; @@ -6786,11 +6786,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { config.background_terminal_max_timeout, ), elicitations: crate::elicitation::ElicitationService::new(), - analytics_events_client: AnalyticsEventsClient::new( - Arc::clone(&auth_manager), - config.chatgpt_base_url.trim_end_matches('/').to_string(), - config.analytics_enabled, - ), hooks: arc_swap::ArcSwap::from_pointee(hooks), rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(), user_shell: Arc::new(default_user_shell()), @@ -7096,7 +7091,6 @@ async fn make_session_with_config_and_rx( /*reserved_thread_id*/ None, environment_manager, /*inherited_environments*/ None, - /*analytics_events_client*/ None, crate::passthrough_image_store(), Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), @@ -7236,7 +7230,6 @@ async fn make_session_with_history_source_and_agent_control_and_rx( /*reserved_thread_id*/ None, environment_manager, /*inherited_environments*/ None, - /*analytics_events_client*/ None, crate::passthrough_image_store(), Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), @@ -9125,11 +9118,6 @@ where config.background_terminal_max_timeout, ), elicitations: crate::elicitation::ElicitationService::new(), - analytics_events_client: AnalyticsEventsClient::new( - Arc::clone(&auth_manager), - config.chatgpt_base_url.trim_end_matches('/').to_string(), - config.analytics_enabled, - ), hooks: arc_swap::ArcSwap::from_pointee(hooks), rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(), user_shell: Arc::new(default_user_shell()), diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index 24df4e9d..7d252d9b 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -1373,7 +1373,6 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { turn_extension_init: Default::default(), client_mcp_extensions: ClientMcpExtensions::default(), reserved_thread_id: None, - analytics_events_client: None, image_store: crate::thread_manager::passthrough_image_store(), thread_store, attestation_provider: None, diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 1fdf62fa..70ee8ba8 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -13,6 +13,8 @@ use crate::compact::AutoCompactionDisabled; use crate::compact::run_inline_auto_compact_task; use crate::compact_remote_v2::BackgroundCompactionCandidate; use crate::compact_remote_v2::run_inline_remote_auto_compact_task as run_inline_remote_auto_compact_task_v2; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; use crate::connectors; use crate::context::ContextualUserFragment; use crate::context::UserVerificationNotice; @@ -71,12 +73,6 @@ use crate::tools::spec_plan::tool_suggest_enabled; use crate::turn_diff_tracker::TurnDiffTracker; use crate::turn_timing::record_turn_ttft_metric; use crate::util::error_or_panic; -use codex_analytics::AppInvocation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::InvocationType; -use codex_analytics::TurnResolvedConfigFact; -use codex_analytics::build_track_events_context; use codex_async_utils::OrCancelExt; use codex_connectors::AppToolPolicyEvaluator; use codex_core_plugins::RecommendedPluginCandidatesInput; @@ -95,7 +91,6 @@ use codex_model_provider::RemoteCompactionSupport; use codex_protocol::ResponseItemId; use codex_protocol::config_types::AutoCompactTokenLimitScope; use codex_protocol::config_types::ModeKind; -use codex_protocol::config_types::ServiceTier; use codex_protocol::error::CodexErr; use codex_protocol::error::CodexErrorDetails; use codex_protocol::error::Result as CodexResult; @@ -521,7 +516,6 @@ pub(crate) async fn run_turn( ) .await; } - track_turn_resolved_config_analytics(&sess, &first_step_context, &input).await; let mut last_agent_message: Option = None; let mut stop_hook_active = false; @@ -954,7 +948,6 @@ pub(crate) async fn run_turn( CodexErrorDetails::InvalidImageRequest() ) => { - sess.track_turn_codex_error(turn_context.as_ref(), &codex_error); let error = CodexErrorInfo::BadRequest; sess.emit_turn_error_lifecycle( turn_context.as_ref(), @@ -983,7 +976,6 @@ pub(crate) async fn run_turn( let error = e.to_codex_protocol_error(); sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone(), e.details()) .await; - sess.track_turn_codex_error(turn_context.as_ref(), &e); let mut error_event = e.to_error_event(/*message_prefix*/ None); if let Some(rejected) = turn_context .extension_data @@ -1271,13 +1263,6 @@ async fn build_skills_and_plugins( return Some((Vec::new(), HashSet::new())); } - let tracking = build_track_events_context( - turn_context.model_info().slug.clone(), - sess.thread_id.to_string(), - turn_context.sub_id.clone(), - turn_context.originator.clone(), - Some(turn_context.turn_metadata_state.clone()), - ); let connector_snapshot = step_context.mcp.config().connector_snapshot.clone(); let mcp_tools = if turn_context.apps_enabled() || !mentioned_plugins.is_empty() { // Plugin mentions need raw MCP/app inventory even when app tools @@ -1335,14 +1320,8 @@ async fn build_skills_and_plugins( } = skills_snapshot .load_skill_prompts(&mentioned_skills, &accessors) .await; - emit_explicit_skill_invocations( - sess, - turn_context, - &mentioned_skills, - &injected_host_skills, - tracking.clone(), - ) - .await; + emit_explicit_skill_invocations(sess, turn_context, &mentioned_skills, &injected_host_skills) + .await; for message in host_skill_warnings { sess.send_event(turn_context, EventMsg::Warning(WarningEvent { message })) .await; @@ -1365,34 +1344,6 @@ async fn build_skills_and_plugins( ); let mut explicitly_enabled_connectors = collect_explicit_app_ids(user_input); explicitly_enabled_connectors.extend(skill_connector_ids); - let connector_names_by_id = available_connectors - .iter() - .map(|connector| (connector.id.as_str(), connector.name.as_str())) - .collect::>(); - let mentioned_app_invocations = explicitly_enabled_connectors - .iter() - .map(|connector_id| AppInvocation { - connector_id: Some(connector_id.clone()), - app_name: connector_names_by_id - .get(connector_id.as_str()) - .map(|name| (*name).to_string()), - invocation_type: Some(InvocationType::Explicit), - }) - .collect::>(); - sess.services - .analytics_events_client - .track_app_mentioned(tracking.clone(), mentioned_app_invocations); - for summary in mentioned_plugins { - if let Some(plugin) = sess - .services - .plugins_manager - .telemetry_metadata_for_capability_summary(summary) - { - sess.services - .analytics_events_client - .track_plugin_used(tracking.clone(), plugin); - } - } let mut injection_items = match injected_host_skill_prompts { Some(injected_host_skill_prompts) => skill_items @@ -1472,78 +1423,6 @@ async fn build_extension_turn_input_items( Some(items) } -#[tracing::instrument( - level = "trace", - skip_all, - fields(input_count = input.len()) -)] -async fn track_turn_resolved_config_analytics( - sess: &Session, - first_step: &StepContext, - input: &[TurnInput], -) { - let turn_context = &first_step.turn; - let thread_config = sess.thread_config_snapshot().await; - let is_first_turn = { - let mut state = sess.state.lock().await; - state.take_next_turn_is_first() - }; - sess.services - .analytics_events_client - .track_turn_resolved_config(TurnResolvedConfigFact { - turn_id: turn_context.sub_id.clone(), - thread_id: sess.thread_id.to_string(), - turn_metadata: turn_context.turn_metadata_state.clone(), - active_plugin_ids_at_turn_start: turn_context.active_plugin_ids_for_telemetry( - first_step - .extension_data - .get::() - .as_deref(), - ), - num_input_images: input - .iter() - .filter_map(|item| match item { - TurnInput::UserInput { content, .. } => Some(content.as_slice()), - TurnInput::ResponseItem(_) - | TurnInput::FunctionCallOutput(_) - | TurnInput::InterAgentCommunication(_) => None, - }) - .flatten() - .filter(|item| { - matches!(item, UserInput::Image { .. } | UserInput::LocalImage { .. }) - }) - .count(), - submission_type: None, - ephemeral: thread_config.ephemeral, - session_source: thread_config.session_source, - model: turn_context.model_info().slug.clone(), - model_provider: turn_context.config.model_provider_id.clone(), - permission_profile: turn_context.permission_profile(), - #[allow(deprecated)] - permission_profile_cwd: turn_context.cwd.to_path_buf(), - reasoning_effort: turn_context.reasoning_effort().cloned(), - reasoning_summary: Some(turn_context.reasoning_summary()), - service_tier: turn_context - .config - .service_tier - .as_deref() - .and_then(ServiceTier::from_request_value), - approval_policy: turn_context.approval_policy(), - approvals_reviewer: turn_context.config.approvals_reviewer, - guardian_v2_enabled: sess - .services - .thread_extension_data - .get::() - .is_some(), - sandbox_network_access: turn_context.network_sandbox_policy().is_enabled(), - multi_agent_version: turn_context.multi_agent_version, - collaboration_mode: turn_context.mode(), - personality: turn_context.personality(), - workspace_kind: turn_context.turn_metadata_state.workspace_kind(), - is_first_turn, - }); -} - #[instrument(level = "trace", skip_all)] async fn run_pre_sampling_compact( sess: &Arc, @@ -3042,8 +2921,6 @@ async fn try_run_sampling_request( )> = None; let mut should_emit_turn_diff = false; let mut should_emit_token_count = false; - const MAX_ANALYTICS_TOOL_CALL_IDS_PER_RESPONSE: usize = 256; - let mut analytics_tool_call_ids = Vec::new(); let reasoning_effort = step_context .settings .reasoning_effort() @@ -3214,22 +3091,6 @@ async fn try_run_sampling_request( sess.assign_missing_response_item_id(&mut item); sess.reserve_assistant_message_order(&turn_context, &item) .await; - if analytics_tool_call_ids.len() < MAX_ANALYTICS_TOOL_CALL_IDS_PER_RESPONSE { - let call_id = match &item { - ResponseItem::FunctionCall { call_id, .. } - | ResponseItem::CustomToolCall { call_id, .. } => Some(call_id.as_str()), - ResponseItem::ToolSearchCall { call_id, .. } - | ResponseItem::LocalShellCall { call_id, .. } => call_id.as_deref(), - ResponseItem::WebSearchCall { id, .. } - | ResponseItem::ImageGenerationCall { id, .. } => { - id.as_ref().map(codex_protocol::ResponseItemId::as_str) - } - _ => None, - }; - if let Some(call_id) = call_id { - analytics_tool_call_ids.push(call_id.to_string()); - } - } if let Some((_, mut consumer)) = active_tool_argument_diff_consumer.take() && let Ok(Some(event)) = consumer.finish() { @@ -3543,16 +3404,6 @@ async fn try_run_sampling_request( .get_or_insert_default() .add_assign(usage); } - sess.services - .analytics_events_client - .track_code_mode_tool_call( - codex_analytics::CodeModeToolCallFact::SamplingResponseCompleted { - thread_id: sess.thread_id.to_string(), - turn_id: turn_context.sub_id.clone(), - response_id: response_id.clone(), - tool_call_ids: std::mem::take(&mut analytics_tool_call_ids), - }, - ); flush_assistant_text_segments_all( &sess, &turn_context, diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index 63c2ac38..2e04aa30 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -16,10 +16,8 @@ use crate::tools::sandboxing::configured_windows_sandbox_selection; use crate::tools::sandboxing::executor_windows_sandbox_selection; use arc_swap::ArcSwap; use codex_core_plugins::PluginCommandAttribution; -use codex_core_plugins::ResolvedPluginMetricsOperation; use codex_core_plugins::TrustedPluginRoots; use codex_exec_server::ExecutorFileSystem; -use codex_extension_api::SelectedPluginSnapshot; use codex_file_system::EnvironmentAccess; use codex_file_system::FileSystemEnvironmentAccessor; use codex_file_system::FileSystemSandboxContext; @@ -645,62 +643,6 @@ impl TurnContext { self.initial_settings.effective_collaboration_mode() } - /// Combines setup-time host identities with the first step's ready selected packages. - /// Keeps the complete observation or marks it unknown; never truncates membership. - pub(super) fn active_plugin_ids_for_telemetry( - &self, - selected: Option<&SelectedPluginSnapshot>, - ) -> Option> { - const MAX_TELEMETRY_PLUGIN_IDS: usize = 512; - const MAX_TELEMETRY_PLUGIN_ID_BYTES: usize = 128; - - let mut identities = self.active_host_plugin_identities.clone()?; - // Selected catalogs preserve local package keys or canonical remote identities. - if let Some(selected) = selected { - identities.extend( - selected - .plugins - .iter() - .map(|plugin| match &plugin.plugin_id { - codex_core_plugins::PluginIdentity::Local { plugin_id } => PluginIdentity { - plugin_id: plugin_id.clone(), - remote_plugin_id: None, - }, - codex_core_plugins::PluginIdentity::Remote { remote_plugin_id } => { - PluginIdentity { - plugin_id: String::new(), - remote_plugin_id: Some(remote_plugin_id.clone()), - } - } - }), - ); - } - let mut ids = Vec::with_capacity(identities.len()); - for identity in identities { - let id = match identity.remote_plugin_id { - Some(remote_id) => { - if !codex_core_plugins::remote::is_valid_remote_plugin_id(&remote_id) { - return None; - } - remote_id - } - None => { - if codex_plugin::PluginId::parse(&identity.plugin_id).is_err() { - return None; - } - identity.plugin_id - } - }; - if id.len() > MAX_TELEMETRY_PLUGIN_ID_BYTES { - return None; - } - ids.push(id); - } - ids.sort_unstable(); - ids.dedup(); - (ids.len() <= MAX_TELEMETRY_PLUGIN_IDS).then_some(ids) - } - pub(crate) fn plugin_attribution_for_command( &self, command: &[String], @@ -749,26 +691,6 @@ impl TurnContext { } } - pub(crate) async fn plugin_metrics_operation_for_command( - &self, - command: &[String], - cwd: &PathUri, - environment: &Environment, - ) -> Option { - let trusted_roots = self.extension_data.get::()?; - if environment.is_remote() { - trusted_roots - .resolve_metrics_operation_in_filesystem( - command, - cwd, - environment.get_filesystem().as_ref(), - ) - .await - } else { - trusted_roots.resolve_metrics_operation(command, &cwd.to_abs_path().ok()?) - } - } - /// Returns the selected environment's permissions, or the thread's permissions when none is ready. pub(crate) fn permission_profile(&self) -> PermissionProfile { self.initial_environments @@ -791,6 +713,7 @@ impl TurnContext { }) } + #[cfg(test)] pub(crate) fn network_sandbox_policy(&self) -> NetworkSandboxPolicy { self.permission_profile().network_sandbox_policy() } @@ -1609,7 +1532,3 @@ impl Session { state.session_configuration.clone() } } - -#[cfg(test)] -#[path = "active_plugin_inventory_tests.rs"] -mod tests; diff --git a/codex-rs/core/src/skills.rs b/codex-rs/core/src/skills.rs index 5be89463..322a1d91 100644 --- a/codex-rs/core/src/skills.rs +++ b/codex-rs/core/src/skills.rs @@ -3,11 +3,6 @@ use crate::environment_selection::TurnEnvironmentSnapshot; use crate::session::session::Session; use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnEnvironment; -use codex_analytics::InvocationType; -use codex_analytics::SkillInvocation; -use codex_analytics::SkillInvocationLocation; -use codex_analytics::TrackEventsContext; -use codex_analytics::build_track_events_context; use codex_core_plugins::PluginsManager; use codex_extension_api::SkillInvocationInput; use codex_extension_api::SkillInvocationKind; @@ -21,6 +16,7 @@ use codex_skills::SkillMetadata; use codex_skills_extension::HostSkillsLoadInput; use codex_skills_extension::HostSkillsSnapshot; use codex_skills_extension::InjectedHostSkillPrompts; +use codex_skills_extension::SkillInvocationLocation; use codex_skills_extension::detect_implicit_skill_invocation; use codex_skills_extension::record_plugin_turn_usage; use codex_utils_absolute_path::AbsolutePathBuf; @@ -147,7 +143,6 @@ pub(crate) async fn emit_explicit_skill_invocations( turn_context: &TurnContext, mentioned_skills: &[SkillMetadata], injected_skills: &[SkillMetadata], - tracking: TrackEventsContext, ) { let injected_skill_paths = injected_skills .iter() @@ -215,23 +210,6 @@ pub(crate) async fn emit_explicit_skill_invocations( .await; } } - - let invocations = injected_skills - .iter() - .map(|skill| SkillInvocation { - skill_name: skill.name.clone(), - location: SkillInvocationLocation::Host { - path: skill.path_to_skills_md.clone(), - scope: skill.scope, - }, - plugin_id: skill.plugin_id.clone(), - remote_plugin_id: skill.remote_plugin_id.clone(), - invocation_type: InvocationType::Explicit, - }) - .collect(); - sess.services - .analytics_events_client - .track_skill_invocations(tracking, invocations); } pub(crate) async fn maybe_emit_implicit_skill_invocation( @@ -325,16 +303,4 @@ pub(crate) async fn maybe_emit_implicit_skill_invocation( ("reasoning_effort", reasoning_effort.as_str()), ], ); - sess.services - .analytics_events_client - .track_skill_invocations( - build_track_events_context( - turn_context.model_info().slug.clone(), - sess.thread_id.to_string(), - turn_context.sub_id.clone(), - turn_context.originator.clone(), - Some(turn_context.turn_metadata_state.clone()), - ), - vec![invocation], - ); } diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 1ca8297e..98842ca5 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -24,7 +24,6 @@ use crate::tools::sandboxing::ApprovalStore; use crate::unified_exec::UnifiedExecProcessManager; use arc_swap::ArcSwap; use arc_swap::ArcSwapOption; -use codex_analytics::AnalyticsEventsClient; use codex_attachment_store::AttachmentStore; use codex_core_plugins::PluginsManager; use codex_extension_api::ExtensionData; @@ -55,7 +54,6 @@ pub(crate) struct SessionServices { pub(crate) mcp_handler_cache: McpHandlerCache, pub(crate) unified_exec_manager: UnifiedExecProcessManager, pub(crate) elicitations: ElicitationService, - pub(crate) analytics_events_client: AnalyticsEventsClient, pub(crate) hooks: ArcSwap, pub(crate) rollout_thread_trace: ThreadTraceContext, pub(crate) user_shell: Arc, diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index e90bd010..2bf99aa4 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -118,7 +118,6 @@ pub(crate) struct SessionState { pub(crate) current_time_reminder: CurrentTimeReminderState, pub(crate) active_connector_selection: HashSet, pub(crate) pending_session_start_sources: VecDeque, - next_turn_is_first: bool, initial_settings_pending: bool, } @@ -170,7 +169,6 @@ impl SessionState { current_time_reminder: CurrentTimeReminderState::default(), active_connector_selection: HashSet::new(), pending_session_start_sources: VecDeque::new(), - next_turn_is_first: true, initial_settings_pending: true, } } @@ -185,17 +183,6 @@ impl SessionState { self.previous_turn_settings = previous_turn_settings; } - pub(crate) fn set_next_turn_is_first(&mut self, value: bool) { - self.next_turn_is_first = value; - self.initial_settings_pending = value; - } - - pub(crate) fn take_next_turn_is_first(&mut self) -> bool { - let is_first_turn = self.next_turn_is_first; - self.next_turn_is_first = false; - is_first_turn - } - pub(crate) fn take_initial_settings_pending(&mut self) -> bool { let pending = self.initial_settings_pending; self.initial_settings_pending = false; @@ -450,6 +437,7 @@ impl SessionState { } // Returns the current connector selection tracked on session state. + #[cfg(test)] pub(crate) fn get_connector_selection(&self) -> HashSet { self.active_connector_selection.clone() } diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index ad1df3f0..a4d82dd0 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -111,22 +111,6 @@ pub(crate) async fn record_completed_response_item_with_finalized_facts( }], ) .await; - if turn_context.config.otel.agent_response_logging_enabled() { - turn_context - .extension_data - .get_or_init(codex_otel::AgentResponseLogger::default) - .record( - &step_context.session_telemetry, - item, - codex_otel::AgentResponseContext { - turn_id: &turn_context.sub_id, - session_source: &turn_context.session_source, - parent_turn_id: turn_context.turn_metadata_state.parent_turn_id(), - root_turn_id: turn_context.turn_metadata_state.root_turn_id(), - initiating_agent_path: turn_context.turn_metadata_state.initiating_agent_path(), - }, - ); - } let defers_mailbox_delivery = finalized_facts.map_or_else( || { completed_item_defers_mailbox_delivery_to_next_turn( diff --git a/codex-rs/core/src/tasks/lifecycle.rs b/codex-rs/core/src/tasks/lifecycle.rs index 9fab93cd..8952a954 100644 --- a/codex-rs/core/src/tasks/lifecycle.rs +++ b/codex-rs/core/src/tasks/lifecycle.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use codex_analytics::TurnAnalyticsMetadata; use codex_extension_api::ExtensionData; use codex_extension_api::ThreadIdleCause; use codex_extension_api::TurnStartPhase; @@ -20,8 +19,6 @@ impl Session { token_usage_at_turn_start: Option<&TokenUsage>, phase: TurnStartPhase, ) { - let metadata: Arc = turn_context.turn_metadata_state.clone(); - turn_context.extension_data.insert(metadata); turn_context .extension_data .insert(turn_context.session_telemetry.clone()); diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index af0f10df..874033aa 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -40,8 +40,6 @@ use crate::state::ActiveTurn; use crate::state::RunningTask; use crate::state::TaskKind; use crate::state::TurnState; -use codex_analytics::TurnProfileFact; -use codex_analytics::TurnTokenUsageFact; use codex_context_fragments::RenderedFragment; use codex_otel::SessionTelemetry; use codex_otel::TURN_E2E_DURATION_METRIC; @@ -804,7 +802,6 @@ impl Session { err.details(), ) .await; - self.track_turn_codex_error(turn_context.as_ref(), &err); self.send_event( turn_context.as_ref(), EventMsg::Error(err.to_error_event(/*message_prefix*/ None)), @@ -895,13 +892,6 @@ impl Session { "codex.turn.token_usage.total_tokens", turn_token_usage.total_tokens, ); - self.services - .analytics_events_client - .track_turn_token_usage(TurnTokenUsageFact { - turn_id: turn_context.sub_id.clone(), - thread_id: self.thread_id.to_string(), - token_usage: turn_token_usage, - }); token_usage_by_model.emit(turn_telemetry, tmp_mem); } emit_turn_memory_metric( @@ -921,12 +911,6 @@ impl Session { .complete_profile_and_duration_ms() .await; crate::turn_timing::record_terminal_turn_profile(self.thread_id, &turn_context, &profile); - self.services - .analytics_events_client - .track_turn_profile(TurnProfileFact { - turn_id: turn_context.sub_id.clone(), - profile, - }); let idle_cause = if matches!( abort_reason.as_ref(), Some(TurnAbortReason::Interrupted | TurnAbortReason::BudgetLimited) @@ -1153,12 +1137,6 @@ impl Session { &task.turn_context, &profile, ); - self.services - .analytics_events_client - .track_turn_profile(TurnProfileFact { - turn_id: task.turn_context.sub_id.clone(), - profile, - }); self.emit_turn_abort_lifecycle(reason.clone(), task.turn_context.extension_data.as_ref()) .await; let event = EventMsg::TurnAborted(TurnAbortedEvent { diff --git a/codex-rs/core/src/tasks/mod_tests.rs b/codex-rs/core/src/tasks/mod_tests.rs index 701607eb..44993b2d 100644 --- a/codex-rs/core/src/tasks/mod_tests.rs +++ b/codex-rs/core/src/tasks/mod_tests.rs @@ -666,8 +666,8 @@ async fn hard_abort_drops_timing_guards_before_profile_completion() { #[tokio::test] async fn turn_critical_path_metrics_count_each_capture_once() { - use codex_analytics::TurnCriticalPath; - use codex_analytics::TurnCriticalPathDurations; + use crate::turn_timing::TurnCriticalPath; + use crate::turn_timing::TurnCriticalPathDurations; let (session, mut context, _rx) = make_session_and_context_with_rx().await; let context = Arc::get_mut(&mut context).unwrap(); diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index af6c2401..165d4ec6 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -42,7 +42,6 @@ use crate::tasks::interrupted_turn_history_marker; use crate::thread_startup_metadata::ThreadStartupMetadata; use codex_agent_graph_store::AgentGraphStore; use codex_agent_graph_store::LocalAgentGraphStore; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::TurnStatus; use codex_attachment_store::AttachmentStore; @@ -559,7 +558,6 @@ pub(crate) struct ThreadManagerState { external_time_provider: Option>, session_source: SessionSource, installation_id: String, - analytics_events_client: Option, // Captures submitted ops for testing purpose when test mode is enabled. ops_log: Option, } @@ -592,7 +590,6 @@ impl ThreadManager { environment_manager: Arc, extensions: Arc>, user_instructions_provider: Arc, - analytics_events_client: Option, image_store: Arc, thread_store: Arc, agent_graph_store: Option>, @@ -662,7 +659,6 @@ impl ThreadManager { runtime_auth, session_source, installation_id, - analytics_events_client, ops_log: should_use_test_thread_manager_behavior() .then(|| Arc::new(std::sync::Mutex::new(Vec::new()))), }), @@ -887,7 +883,6 @@ impl ThreadManager { auth_manager, session_source: SessionSource::Exec, installation_id, - analytics_events_client: None, ops_log: should_use_test_thread_manager_behavior() .then(|| Arc::new(std::sync::Mutex::new(Vec::new()))), }), @@ -2720,14 +2715,10 @@ impl ThreadManagerState { codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile }; // A resumed actor and its descendants share an owner, not the harness default's credentials. - let (runtime_auth, plugins_manager, analytics_events_client) = if Arc::ptr_eq( - &auth_manager, - &self.auth_manager, - ) { + let (runtime_auth, plugins_manager) = if Arc::ptr_eq(&auth_manager, &self.auth_manager) { ( inherited_runtime_auth.unwrap_or_else(|| Arc::clone(&self.runtime_auth)), Arc::clone(&self.plugins_manager), - self.analytics_events_client.clone(), ) } else { let threads = self.threads.read().await; @@ -2740,7 +2731,6 @@ impl ThreadManagerState { inherited_runtime_auth .unwrap_or_else(|| Arc::clone(&parent.session.services.runtime_auth)), Arc::clone(&parent.session.services.plugins_manager), - Some(parent.session.services.analytics_events_client.clone()), ) } else { let runtime_auth = inherited_runtime_auth.unwrap_or_default(); @@ -2748,35 +2738,7 @@ impl ThreadManagerState { self.plugins_manager .for_auth_context(Arc::clone(&auth_manager), Arc::clone(&runtime_auth)), ); - let runtime_provider = config - .features - .enabled(Feature::RuntimeAgentInstances) - .then(|| (Arc::clone(&runtime_auth), config.runtime_auth_mode)); - let analytics = self.analytics_events_client.as_ref().map(|client| { - let api_key_headers = if codex_model_provider::provider_uses_first_party_auth_path( - &config.model_provider, - ) { - match config.model_provider.build_header_map() { - Ok(headers) => headers, - Err(error) => { - tracing::warn!(%error, "failed to resolve analytics resource selectors"); - return codex_analytics::AnalyticsEventsClient::disabled(); - } - } - } else { - Default::default() - }; - client.for_auth_context( - Arc::clone(&auth_manager), - config.chatgpt_base_url.clone(), - runtime_provider, - api_key_headers, - ) - }); - if let Some(client) = &analytics { - plugins.set_analytics_events_client(client.clone()); - } - (runtime_auth, plugins, analytics) + (runtime_auth, plugins) } }; let mcp_manager = if Arc::ptr_eq(&plugins_manager, &self.plugins_manager) { @@ -2851,7 +2813,6 @@ impl ThreadManagerState { turn_extension_init, client_mcp_extensions, reserved_thread_id, - analytics_events_client, image_store: Arc::clone(&self.image_store), thread_store: Arc::clone(&self.thread_store), attestation_provider: self.attestation_provider.clone(), diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 7167756c..61ac744f 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -1343,7 +1343,6 @@ async fn mcp_invalidation_refreshes_threads_that_are_still_starting() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), Arc::new(extensions.build()), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -2016,7 +2015,6 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors() Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), Arc::new(extensions.build()), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -2456,7 +2454,6 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -2619,7 +2616,6 @@ async fn explicit_installation_id_skips_codex_home_file() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), thread_store, local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -2666,7 +2662,6 @@ async fn resume_active_thread_from_rollout_returns_running_thread() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -2735,7 +2730,6 @@ async fn resume_stopped_thread_from_rollout_spawns_new_thread() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -2811,7 +2805,6 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), thread_store, local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -2901,7 +2894,6 @@ async fn subtree_listing_uses_injected_graph_store_without_state_db() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), Some(agent_graph_store), @@ -2952,7 +2944,6 @@ async fn rollout_path_resume_and_fork_read_history_through_thread_store() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), thread_store.clone(), local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -3065,7 +3056,6 @@ async fn metadata_update_without_result_reads_only_when_the_caller_needs_the_thr Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), thread_store.clone(), /*agent_graph_store*/ None, @@ -3201,7 +3191,6 @@ async fn new_uses_active_provider_for_model_refresh(with_cache: bool) { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -3357,7 +3346,6 @@ async fn startup_catalog_cache_policy_controls_refresh() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, @@ -3642,7 +3630,6 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, state_db.clone()).build(), local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -3757,7 +3744,6 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, state_db.clone()).build(), local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -3865,7 +3851,6 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, passthrough_image_store(), ThreadStoreBuilder::from_config(&config, state_db.clone()).build(), local_agent_graph_store_from_state_db(state_db.as_ref()), diff --git a/codex-rs/core/src/thread_rollout_truncation.rs b/codex-rs/core/src/thread_rollout_truncation.rs index 5dde1d13..11cc03ac 100644 --- a/codex-rs/core/src/thread_rollout_truncation.rs +++ b/codex-rs/core/src/thread_rollout_truncation.rs @@ -3,10 +3,12 @@ //! In core, "user turns" are detected by scanning `ResponseItem::Message` items and //! interpreting them via `event_mapping::parse_turn_item(...)`. +#[cfg(test)] use crate::context_manager::is_user_turn_boundary; use crate::event_mapping; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::build_turns_from_rollout_items; +#[cfg(test)] use codex_history::InitialHistory; use codex_history::RolloutItem; use codex_protocol::error::CodexErr; @@ -15,10 +17,12 @@ use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::EventMsg; +#[cfg(test)] pub(crate) fn initial_history_has_prior_user_turns(conversation_history: &InitialHistory) -> bool { conversation_history.scan_rollout_items(rollout_item_is_user_turn_boundary) } +#[cfg(test)] fn rollout_item_is_user_turn_boundary(item: &RolloutItem) -> bool { match item { RolloutItem::ResponseItem(item) => is_user_turn_boundary(item), diff --git a/codex-rs/core/src/tools/approvals.rs b/codex-rs/core/src/tools/approvals.rs index 2f63fe70..390fef5e 100644 --- a/codex-rs/core/src/tools/approvals.rs +++ b/codex-rs/core/src/tools/approvals.rs @@ -22,8 +22,8 @@ use crate::tools::sandboxing::ExecApprovalRequirement; use crate::tools::sandboxing::PermissionRequestPayload; use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::with_cached_approval; -use codex_analytics::GuardianApprovalRequestSource; use codex_config::types::AppToolApproval; +use codex_guardian_reviewer::GuardianApprovalRequestSource; use codex_hooks::PermissionRequestDecision; use codex_otel::ToolDecisionSource; use codex_prompts::ResolvedModelMessages; diff --git a/codex-rs/core/src/tools/code_mode/execute_handler.rs b/codex-rs/core/src/tools/code_mode/execute_handler.rs index 756c8057..04d824cc 100644 --- a/codex-rs/core/src/tools/code_mode/execute_handler.rs +++ b/codex-rs/core/src/tools/code_mode/execute_handler.rs @@ -96,15 +96,6 @@ impl CodeModeExecuteHandler { let cell_id = started_cell.cell_id.clone(); tracing::Span::current().record("cell.id", trace_id(cell_id.as_str())); telemetry.cell_id = Some(cell_id.to_string()); - exec.session - .services - .analytics_events_client - .track_code_mode_tool_call(codex_analytics::CodeModeToolCallFact::CellStarted { - thread_id: exec.session.thread_id.to_string(), - turn_id: exec.turn.sub_id.clone(), - call_id: call_id.clone(), - cell_id: cell_id.to_string(), - }); exec.session .services .executed_tool_calls @@ -148,14 +139,6 @@ impl CodeModeExecuteHandler { .services .code_mode_service .finish_cell_dispatch(&cell_id); - exec.session - .services - .analytics_events_client - .track_code_mode_tool_call(codex_analytics::CodeModeToolCallFact::CellClosed { - thread_id: exec.session.thread_id.to_string(), - turn_id: exec.turn.sub_id.clone(), - cell_id: cell_id.to_string(), - }); } exec.session.services.elicitations.wait_until_clear().await; let wall_time = response @@ -223,7 +206,6 @@ impl CodeModeExecuteHandler { let mut telemetry = CodeModeToolCallGuard::new( &session, turn.sub_id.clone(), - turn.turn_metadata_state.clone(), call_id.clone(), PUBLIC_TOOL_NAME, handler_span, diff --git a/codex-rs/core/src/tools/code_mode/mod.rs b/codex-rs/core/src/tools/code_mode/mod.rs index 0dc3655e..fd47de2e 100644 --- a/codex-rs/core/src/tools/code_mode/mod.rs +++ b/codex-rs/core/src/tools/code_mode/mod.rs @@ -399,15 +399,6 @@ fn submit_nested_tool( encrypted_function_args: None, native_call: None, }; - session - .services - .analytics_events_client - .track_code_mode_tool_call(codex_analytics::CodeModeToolCallFact::ChildStarted { - thread_id: session.thread_id.to_string(), - turn_id: step_context.turn.sub_id.clone(), - call_id: call.call_id.clone(), - cell_id: cell_id.to_string(), - }); let result = tool_runtime.handle_tool_call_with_source( step_context, call, diff --git a/codex-rs/core/src/tools/code_mode/telemetry.rs b/codex-rs/core/src/tools/code_mode/telemetry.rs index 910ae0a3..46bf454d 100644 --- a/codex-rs/core/src/tools/code_mode/telemetry.rs +++ b/codex-rs/core/src/tools/code_mode/telemetry.rs @@ -1,24 +1,16 @@ -//! Code-mode tool analytics and tracing for handlers and queued nested dispatch. +//! Code-mode local tracing for handlers and queued nested dispatch. -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::CodeModeToolCallFact; -use codex_analytics::CodeModeToolCallStatus; -use codex_analytics::TurnAnalyticsMetadata; use codex_protocol::ThreadId; use std::sync::Arc; use std::time::Duration; use tracing::Span; pub(super) struct CodeModeToolCallGuard { - analytics: AnalyticsEventsClient, thread_id: String, turn_id: String, - turn_metadata: Arc, call_id: String, pub(super) cell_id: Option, tool_name: &'static str, - started_at_ms: u64, - status: CodeModeToolCallStatus, handler_span: Span, extensions: Arc>, } @@ -27,34 +19,23 @@ impl CodeModeToolCallGuard { pub(super) fn new( session: &crate::session::session::Session, turn_id: String, - turn_metadata: Arc, call_id: String, tool_name: &'static str, handler_span: Span, ) -> Self { Self { - analytics: session.services.analytics_events_client.clone(), thread_id: session.thread_id.to_string(), turn_id, - turn_metadata, call_id, cell_id: None, tool_name, - started_at_ms: codex_analytics::now_unix_millis(), - status: CodeModeToolCallStatus::Interrupted, handler_span, extensions: Arc::clone(&session.services.extensions), } } pub(super) fn finish(&mut self, success: bool) { - let mut outcome = "failed"; - self.status = if success { - outcome = "completed"; - CodeModeToolCallStatus::Completed - } else { - CodeModeToolCallStatus::Failed - }; + let outcome = if success { "completed" } else { "failed" }; self.handler_span.record("outcome", outcome); } @@ -104,23 +85,6 @@ impl CodeModeToolCallGuard { } } -impl Drop for CodeModeToolCallGuard { - fn drop(&mut self) { - self.analytics - .track_code_mode_tool_call(CodeModeToolCallFact::Completed { - thread_id: self.thread_id.clone(), - turn_id: self.turn_id.clone(), - turn_metadata: self.turn_metadata.clone(), - call_id: self.call_id.clone(), - cell_id: self.cell_id.clone(), - tool_name: self.tool_name.to_string(), - started_at_ms: self.started_at_ms, - completed_at_ms: codex_analytics::now_unix_millis(), - status: self.status, - }); - } -} - pub(super) struct NestedToolDispatchTrace { thread_id: ThreadId, pub(super) call_id: String, diff --git a/codex-rs/core/src/tools/code_mode/wait_handler.rs b/codex-rs/core/src/tools/code_mode/wait_handler.rs index 1d3bc564..b447fd47 100644 --- a/codex-rs/core/src/tools/code_mode/wait_handler.rs +++ b/codex-rs/core/src/tools/code_mode/wait_handler.rs @@ -109,7 +109,6 @@ impl CodeModeWaitHandler { let mut telemetry = CodeModeToolCallGuard::new( &session, turn.sub_id.clone(), - turn.turn_metadata_state.clone(), call_id.clone(), WAIT_TOOL_NAME, handler_span, @@ -186,16 +185,6 @@ impl CodeModeWaitHandler { .services .code_mode_service .finish_cell_dispatch(runtime_cell_id); - exec.session - .services - .analytics_events_client - .track_code_mode_tool_call( - codex_analytics::CodeModeToolCallFact::CellClosed { - thread_id: exec.session.thread_id.to_string(), - turn_id: exec.turn.sub_id.clone(), - cell_id: runtime_cell_id.to_string(), - }, - ); } } else { telemetry.record_cell_timing(&cell_id, CodeModeCellTiming::CellUnavailable); diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 252ca66b..00da9d32 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -170,8 +170,6 @@ impl ToolInvocation { pub struct McpToolOutput { pub result: CallToolResult, pub tool_input: JsonValue, - // Keep the original metadata for hooks; this flag only controls analytics capture. - pub(crate) result_metadata_capture_allowed: bool, pub wall_time: Duration, pub original_image_detail_supported: bool, pub truncation_policy: TruncationPolicy, @@ -209,13 +207,6 @@ impl ToolOutput for McpToolOutput { self.result.code_mode_result(payload) } - fn tool_result_metadata(&self) -> Option<&JsonValue> { - if !self.result_metadata_capture_allowed { - return None; - } - self.result.meta.as_ref() - } - fn post_tool_use_input(&self, _payload: &ToolPayload) -> Option { Some(self.tool_input.clone()) } diff --git a/codex-rs/core/src/tools/context_tests.rs b/codex-rs/core/src/tools/context_tests.rs index aa9a5f37..c4c1e45d 100644 --- a/codex-rs/core/src/tools/context_tests.rs +++ b/codex-rs/core/src/tools/context_tests.rs @@ -99,7 +99,6 @@ fn mcp_tool_output_response_item_includes_wall_time() { meta: None, }, tool_input: json!({}), - result_metadata_capture_allowed: false, wall_time: std::time::Duration::from_millis(1250), original_image_detail_supported: false, truncation_policy: TruncationPolicy::Bytes(1024), @@ -146,7 +145,6 @@ fn mcp_tool_output_response_item_truncates_large_structured_content() { meta: None, }, tool_input: json!({}), - result_metadata_capture_allowed: false, wall_time: std::time::Duration::from_millis(1250), original_image_detail_supported: false, truncation_policy: TruncationPolicy::Bytes(128), @@ -197,7 +195,6 @@ fn mcp_tool_output_response_item_preserves_content_items() { meta: None, }, tool_input: json!({}), - result_metadata_capture_allowed: false, wall_time: std::time::Duration::from_millis(500), original_image_detail_supported: false, truncation_policy: TruncationPolicy::Bytes(1024), @@ -259,7 +256,6 @@ fn mcp_tool_output_code_mode_result_preserves_content_without_private_metadata( })), }, tool_input: json!({}), - result_metadata_capture_allowed: false, wall_time: std::time::Duration::from_millis(1250), original_image_detail_supported: false, truncation_policy, diff --git a/codex-rs/core/src/tools/control_tool_analytics.rs b/codex-rs/core/src/tools/control_tool_analytics.rs deleted file mode 100644 index dd9602ab..00000000 --- a/codex-rs/core/src/tools/control_tool_analytics.rs +++ /dev/null @@ -1,58 +0,0 @@ -use crate::tools::context::ToolCallSource; -use crate::tools::context::ToolInvocation; -use codex_analytics::ControlToolCallFact; -use codex_analytics::ControlToolCallStatus; - -pub(crate) struct ControlToolCallGuard<'a> { - invocation: &'a ToolInvocation, - started_at_ms: u64, - completed_at_ms: Option, - status: ControlToolCallStatus, -} - -impl<'a> ControlToolCallGuard<'a> { - pub(crate) fn new(invocation: &'a ToolInvocation) -> Self { - Self { - invocation, - started_at_ms: codex_analytics::now_unix_millis(), - completed_at_ms: None, - status: ControlToolCallStatus::Interrupted, - } - } - - pub(crate) fn finish(&mut self, status: ControlToolCallStatus) { - self.completed_at_ms = Some(codex_analytics::now_unix_millis()); - self.status = status; - } -} - -impl Drop for ControlToolCallGuard<'_> { - fn drop(&mut self) { - let invocation = self.invocation; - invocation - .session - .services - .analytics_events_client - .track_control_tool_call(ControlToolCallFact { - thread_id: invocation.session.thread_id.to_string(), - turn_id: invocation.turn.sub_id.clone(), - turn_metadata: invocation.turn.turn_metadata_state.clone(), - call_id: invocation.call_id.clone(), - cell_id: match &invocation.source { - ToolCallSource::CodeMode { cell_id, .. } => Some(cell_id.clone()), - ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage => None, - }, - tool_name: match invocation.tool_name.namespace.as_deref() { - Some(namespace) if !invocation.tool_name.is_default_namespace() => { - format!("{namespace}.{}", invocation.tool_name.name) - } - None | Some(_) => invocation.tool_name.name.clone(), - }, - started_at_ms: self.started_at_ms, - completed_at_ms: self - .completed_at_ms - .unwrap_or_else(codex_analytics::now_unix_millis), - status: self.status, - }); - } -} diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 2d5262ee..17abb812 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -3,9 +3,6 @@ use crate::session::session::Session; use crate::session::turn_context::TurnContext; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::sandboxing::ToolError; -use codex_analytics::ArtifactOperation; -use codex_analytics::ArtifactOperationLifecycle; -use codex_analytics::build_track_events_context; use codex_apply_patch::AppliedPatchDelta; use codex_core_plugins::PluginCommandAttribution; use codex_core_plugins::recognize_artifact_operation; @@ -140,31 +137,6 @@ async fn emit_exec_command_begin(ctx: ToolEventCtx<'_>, exec_input: &ExecCommand i64::from(operation.expected_output_count), &metric_tags, ); - ctx.session - .services - .analytics_events_client - .track_artifact_operation( - build_track_events_context( - ctx.model_info.slug.clone(), - ctx.session.thread_id.to_string(), - ctx.turn.sub_id.clone(), - ctx.turn.originator.clone(), - /*turn_metadata*/ None, - ), - ArtifactOperation { - item_id: ctx.call_id.to_string(), - lifecycle: ArtifactOperationLifecycle::Started, - occurred_at_ms: codex_analytics::now_unix_millis(), - plugin_id: attribution.plugin_id.as_key(), - script_path: operation.script_path.to_string(), - skill: operation.plugin_name.to_string(), - artifact_type: operation.artifact_type.to_string(), - operation_kind: operation.operation_kind.to_string(), - expected_output_count: operation.expected_output_count, - output_format: operation.output_format.to_string(), - execution_backend: "unified_exec".to_string(), - }, - ); } let (plugin_id, script_path) = plugin_attribution_fields(exec_input.plugin_attribution); ctx.session diff --git a/codex-rs/core/src/tools/handlers/current_time.rs b/codex-rs/core/src/tools/handlers/current_time.rs index d00b1492..65e090af 100644 --- a/codex-rs/core/src/tools/handlers/current_time.rs +++ b/codex-rs/core/src/tools/handlers/current_time.rs @@ -128,8 +128,4 @@ impl ToolExecutor for CurrentTimeHandler { } } -impl CoreToolRuntime for CurrentTimeHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for CurrentTimeHandler {} diff --git a/codex-rs/core/src/tools/handlers/extension_tools.rs b/codex-rs/core/src/tools/handlers/extension_tools.rs index fbe65a70..d83115fa 100644 --- a/codex-rs/core/src/tools/handlers/extension_tools.rs +++ b/codex-rs/core/src/tools/handlers/extension_tools.rs @@ -132,30 +132,6 @@ impl CoreToolRuntime for ExtensionToolAdapter { .map(ToolEnvironments::Arguments) } - fn is_builtin_control_tool(&self) -> bool { - let tool_name = self.0.tool_name(); - if tool_name.is_default_namespace() { - return matches!( - tool_name.name.as_str(), - "get_goal" | "create_goal" | "update_goal" - ); - } - matches!( - (tool_name.namespace.as_deref(), tool_name.name.as_str()), - ( - Some("notes"), - "list_files_by_prefix" - | "read_file" - | "search_contents" - | "append_to_file" - | "write_file" - ) | ( - Some("history"), - "list_windows" | "list_items" | "read_item" | "search_contents" - ) - ) - } - fn matches_kind(&self, payload: &ToolPayload) -> bool { match payload { ToolPayload::Function { .. } => true, diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index 33350bb3..2c561acc 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -234,12 +234,6 @@ impl McpHandler { .await; let prepared = prepared_mcp_call.as_ref().ok(); // Use the executed call's binding; a later catalog refresh must not change eligibility. - let result_metadata_capture_allowed = invocation - .session - .services - .analytics_events_client - .is_enabled() - && prepared.is_some_and(codex_mcp::PreparedMcpCall::is_host_owned_apps); let mcp_tool = prepared.map(|call| { McpToolContext::from_prepared_call( call, @@ -299,7 +293,6 @@ impl McpHandler { Ok(boxed_tool_output(McpToolOutput { result: result.result, tool_input: result.tool_input, - result_metadata_capture_allowed, wall_time: started.elapsed(), original_image_detail_supported: can_request_original_image_detail( &step_context.settings.model_info, @@ -796,7 +789,6 @@ mod tests { "file_id": "file_123" } }), - result_metadata_capture_allowed: false, wall_time: Duration::from_millis(42), original_image_detail_supported: true, truncation_policy: codex_utils_output_truncation::TruncationPolicy::Bytes(1024), @@ -850,7 +842,8 @@ mod tests { }) ); - // Nested MCP result metadata still reaches the owning Code Mode cell. + // Nested MCP calls are still attributed to the owning Code Mode cell; raw MCP + // result metadata is never captured. let cell_id = codex_code_mode::CellId::new("mcp-cell".to_string()); recorder.start_cell(&cell_id, "exec-mcp-post"); let mut invocation = invocation; @@ -860,7 +853,6 @@ mod tests { }; let mut output = output; output.result.meta = Some(json!({ "provider/custom": { "items": [1, null] } })); - output.result_metadata_capture_allowed = true; recorder.record_tool_call( &crate::tools::router::ToolCall { tool_name: invocation.tool_name.clone(), @@ -883,7 +875,6 @@ mod tests { json!([{ "name": codex_tools::code_mode_name_for_tool_name(&invocation.tool_name), "arguments": { "path": "/tmp/notes.txt" }, - "tool_result_metadata": { "provider/custom": { "items": [1, null] } }, }]), ); } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index c8fb0da5..8c551e89 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -4331,7 +4331,6 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(crate::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, crate::thread_manager::passthrough_image_store(), ThreadStoreBuilder::from_config(&config, state_db.clone()).build(), local_agent_graph_store_from_state_db(state_db.as_ref()), diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2.rs index 8333a10d..4c0d5462 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2.rs @@ -32,7 +32,6 @@ pub(crate) use send_message::Handler as SendMessageHandler; pub(crate) use spawn::Handler as SpawnAgentHandler; pub(crate) use wait::Handler as WaitAgentHandler; -mod analytics; mod followup_task; mod interrupt_agent; mod list_agents; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/analytics.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/analytics.rs deleted file mode 100644 index a8a0ea6b..00000000 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/analytics.rs +++ /dev/null @@ -1,62 +0,0 @@ -use codex_analytics::AnalyticsEventsClient; -use codex_protocol::ThreadId; -use codex_protocol::items::CollabAgentTool; -use codex_protocol::items::CollabAgentToolCallItem; -use codex_protocol::items::CollabAgentToolCallStatus; - -use crate::tools::context::ToolInvocation; -use crate::turn_timing::now_unix_timestamp_ms; - -/// Records private collaborator analytics without emitting another public tool item. -pub(super) struct ToolCallAnalytics { - client: AnalyticsEventsClient, - turn_id: String, - item: CollabAgentToolCallItem, - started_at_ms: i64, -} - -impl ToolCallAnalytics { - pub(super) fn new(invocation: &ToolInvocation, tool: CollabAgentTool) -> Self { - Self { - client: invocation.session.services.analytics_events_client.clone(), - turn_id: invocation.turn.sub_id.clone(), - item: CollabAgentToolCallItem { - // Activity and analytics must use the same ID for turn-count deduplication. - id: invocation.call_id.clone(), - tool, - status: CollabAgentToolCallStatus::Interrupted, - sender_thread_id: invocation.session.thread_id, - receiver_thread_ids: Vec::new(), - receiver_agents: Vec::new(), - prompt: None, - model: None, - reasoning_effort: None, - agents_states: Default::default(), - }, - started_at_ms: now_unix_timestamp_ms(), - } - } - - pub(super) fn set_receiver(&mut self, thread_id: ThreadId) { - self.item.receiver_thread_ids = vec![thread_id]; - } - - pub(super) fn finish(mut self, result: &Result) { - self.item.status = if result.is_ok() { - CollabAgentToolCallStatus::Completed - } else { - CollabAgentToolCallStatus::Failed - }; - } -} - -impl Drop for ToolCallAnalytics { - fn drop(&mut self) { - self.client.track_collab_tool_call( - self.turn_id.clone(), - self.item.clone(), - self.started_at_ms, - now_unix_timestamp_ms(), - ); - } -} diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs index fa129704..cec35f54 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs @@ -1,4 +1,3 @@ -use super::analytics::ToolCallAnalytics; use super::message_tool::FollowupTaskArgs; use super::message_tool::handle_message_string_tool; use super::*; @@ -21,12 +20,7 @@ impl ToolExecutor for Handler { where ToolInvocation: 'a, { - Box::pin(async move { - let mut analytics = ToolCallAnalytics::new(&invocation, CollabAgentTool::FollowupTask); - let result = self.handle_call(invocation, &mut analytics).await; - analytics.finish(&result); - result - }) + Box::pin(async move { self.handle_call(invocation).await }) } } @@ -34,7 +28,6 @@ impl Handler { async fn handle_call( &self, invocation: ToolInvocation, - analytics: &mut ToolCallAnalytics, ) -> Result, FunctionCallError> { let arguments = function_arguments(invocation.payload.clone())?; let args: FollowupTaskArgs = parse_arguments(&arguments)?; @@ -43,7 +36,6 @@ impl Handler { MessageDeliveryMode::TriggerTurn, args.target, args.message, - analytics, ) .await .map(boxed_tool_output) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/interrupt_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/interrupt_agent.rs index e78b3629..b19a5272 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/interrupt_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/interrupt_agent.rs @@ -1,4 +1,3 @@ -use super::analytics::ToolCallAnalytics; use super::*; use crate::agent::api::AgentTarget; use crate::tools::handlers::multi_agents_spec::create_interrupt_agent_tool_v2; @@ -21,18 +20,15 @@ impl ToolExecutor for Handler { ToolInvocation: 'a, { Box::pin(async move { - let mut analytics = - ToolCallAnalytics::new(&invocation, CollabAgentTool::InterruptAgent); - let result = handle_interrupt_agent(invocation, &mut analytics).await; - analytics.finish(&result); - result.map(boxed_tool_output) + handle_interrupt_agent(invocation) + .await + .map(boxed_tool_output) }) } } async fn handle_interrupt_agent( invocation: ToolInvocation, - analytics: &mut ToolCallAnalytics, ) -> Result { let ToolInvocation { session, @@ -44,7 +40,6 @@ async fn handle_interrupt_agent( let arguments = function_arguments(payload)?; let args: InterruptAgentArgs = parse_arguments(&arguments)?; let agent_id = resolve_agent_target(&session, &turn, &args.target).await?; - analytics.set_receiver(agent_id); let snapshot = session .services .agent_control diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs index b340a1fe..2633453e 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs @@ -1,4 +1,3 @@ -use super::analytics::ToolCallAnalytics; use super::*; use crate::tools::handlers::multi_agents_spec::create_list_agents_tool; use codex_tools::ToolSpec; @@ -22,12 +21,7 @@ impl ToolExecutor for Handler { where ToolInvocation: 'a, { - Box::pin(async move { - let analytics = ToolCallAnalytics::new(&invocation, CollabAgentTool::ListAgents); - let result = self.handle_call(invocation).await; - analytics.finish(&result); - result - }) + Box::pin(async move { self.handle_call(invocation).await }) } } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs index 83929601..826046a4 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs @@ -3,7 +3,6 @@ //! `send_message` and `followup_task` share the same submission path and differ only in whether the //! resulting `InterAgentCommunication` should wake the target immediately. -use super::analytics::ToolCallAnalytics; use super::*; use crate::TurnStartOptions; use crate::agent::api::AgentInput; @@ -44,7 +43,6 @@ pub(super) async fn handle_message_string_tool( mode: MessageDeliveryMode, target: String, message: String, - analytics: &mut ToolCallAnalytics, ) -> Result { let message = message_content(message)?; let ToolInvocation { @@ -55,7 +53,6 @@ pub(super) async fn handle_message_string_tool( .. } = invocation; let receiver_thread_id = resolve_agent_target(&session, &turn, &target).await?; - analytics.set_receiver(receiver_thread_id); let resume_config = build_agent_resume_config(&turn).map_err(FunctionCallError::RespondToModel)?; let receipt = session diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs index 7713f011..d8f6795a 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs @@ -1,4 +1,3 @@ -use super::analytics::ToolCallAnalytics; use super::message_tool::SendMessageArgs; use super::message_tool::handle_message_string_tool; use super::*; @@ -21,12 +20,7 @@ impl ToolExecutor for Handler { where ToolInvocation: 'a, { - Box::pin(async move { - let mut analytics = ToolCallAnalytics::new(&invocation, CollabAgentTool::SendMessage); - let result = self.handle_call(invocation, &mut analytics).await; - analytics.finish(&result); - result - }) + Box::pin(async move { self.handle_call(invocation).await }) } } @@ -34,7 +28,6 @@ impl Handler { async fn handle_call( &self, invocation: ToolInvocation, - analytics: &mut ToolCallAnalytics, ) -> Result, FunctionCallError> { let arguments = function_arguments(invocation.payload.clone())?; let args: SendMessageArgs = parse_arguments(&arguments)?; @@ -43,7 +36,6 @@ impl Handler { MessageDeliveryMode::QueueOnly, args.target, args.message, - analytics, ) .await .map(boxed_tool_output) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index c23caa01..4146aad3 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -4,11 +4,9 @@ use crate::agent::types::SpawnAgentForkMode; use crate::codex_thread::ThreadConfigSnapshot; use crate::thread_spawn::ThreadSpawnError; use crate::thread_spawn::ThreadSpawnRequest; -use crate::tools::handlers::multi_agents::collab_tool_call_status; use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions; use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v2; use crate::tools::handlers::multi_agents_v2::message_tool::message_content; -use crate::turn_timing::now_unix_timestamp_ms; use codex_protocol::ThreadId; use codex_protocol::protocol::MultiAgentVersion; use codex_tools::ToolSpec; @@ -46,46 +44,7 @@ impl ToolExecutor for Handler { ToolInvocation: 'a, { Box::pin(async move { - let analytics = invocation.session.services.analytics_events_client.clone(); - let sender_thread_id = invocation.session.thread_id; - let turn_id = invocation.step_context.turn.sub_id.clone(); - let call_id = invocation.call_id.clone(); - let started_at_ms = now_unix_timestamp_ms(); let result = handle_spawn_agent(invocation).await; - let completed_at_ms = now_unix_timestamp_ms(); - let (status, receiver_thread_ids, agents_states) = match &result { - Ok((_, thread_id, agent_status, _)) => ( - collab_tool_call_status(agent_status, Some(*thread_id)), - vec![*thread_id], - [(*thread_id, agent_status.clone())].into_iter().collect(), - ), - Err(_) => ( - CollabAgentToolCallStatus::Failed, - Vec::new(), - Default::default(), - ), - }; - let agent_snapshot = result.as_ref().ok().map(|(_, _, _, snapshot)| snapshot); - - analytics.track_collab_tool_call( - turn_id, - CollabAgentToolCallItem { - id: call_id, - tool: CollabAgentTool::SpawnAgent, - status, - sender_thread_id, - receiver_thread_ids, - receiver_agents: Vec::new(), - prompt: None, - model: agent_snapshot.map(|snapshot| snapshot.model.clone()), - reasoning_effort: agent_snapshot - .and_then(|snapshot| snapshot.reasoning_effort.clone()), - agents_states, - }, - started_at_ms, - completed_at_ms, - ); - result.map(|(output, _, _, _)| boxed_tool_output(output)) }) } diff --git a/codex-rs/core/src/tools/handlers/plan.rs b/codex-rs/core/src/tools/handlers/plan.rs index 34956562..004afd8d 100644 --- a/codex-rs/core/src/tools/handlers/plan.rs +++ b/codex-rs/core/src/tools/handlers/plan.rs @@ -99,11 +99,7 @@ impl PlanHandler { } } -impl CoreToolRuntime for PlanHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for PlanHandler {} fn parse_update_plan_arguments(arguments: &str) -> Result { serde_json::from_str::(arguments).map_err(|e| { diff --git a/codex-rs/core/src/tools/handlers/request_plugin_install.rs b/codex-rs/core/src/tools/handlers/request_plugin_install.rs index 335584ab..640ae114 100644 --- a/codex-rs/core/src/tools/handlers/request_plugin_install.rs +++ b/codex-rs/core/src/tools/handlers/request_plugin_install.rs @@ -1,10 +1,6 @@ use std::collections::HashSet; use std::sync::Arc; -use codex_analytics::PluginInstallRequestSource; -use codex_analytics::PluginInstallRequested; -use codex_analytics::PluginInstallRequestedPlugin; -use codex_analytics::build_track_events_context; use codex_config::types::ToolSuggestDisabledTool; use codex_core_plugins::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; @@ -217,37 +213,6 @@ impl RequestPluginInstallHandler { let tool_type = tool.tool_type(); let suggestion_id = format!("request_plugin_install_{call_id}"); - if let DiscoverableTool::Plugin(plugin) = &tool { - let source = match self.presentation { - ToolSuggestPresentation::ListTool => PluginInstallRequestSource::LegacyDiscovery, - ToolSuggestPresentation::RecommendationContext => { - PluginInstallRequestSource::EndpointRecommendation - } - }; - session - .services - .analytics_events_client - .track_plugin_install_requested( - build_track_events_context( - step_context.settings.model_info.slug.clone(), - session.thread_id.to_string(), - turn.sub_id.clone(), - turn.originator.clone(), - /*turn_metadata*/ None, - ), - PluginInstallRequested { - suggestion_id: suggestion_id.clone(), - plugins: vec![PluginInstallRequestedPlugin { - plugin_id: plugin.id.clone(), - remote_plugin_id: plugin.remote_plugin_id.clone(), - plugin_name: plugin.name.clone(), - connector_ids: plugin.app_connector_ids.clone(), - }], - source, - }, - ); - } - let request = build_request_plugin_install_elicitation_request(suggest_reason, &tool, &suggestion_id); let request_id = RequestId::String(suggestion_id.into()); diff --git a/codex-rs/core/src/tools/handlers/request_user_input.rs b/codex-rs/core/src/tools/handlers/request_user_input.rs index 0bac1b16..75a1d980 100644 --- a/codex-rs/core/src/tools/handlers/request_user_input.rs +++ b/codex-rs/core/src/tools/handlers/request_user_input.rs @@ -152,11 +152,7 @@ impl RequestUserInputHandler { } } -impl CoreToolRuntime for RequestUserInputHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for RequestUserInputHandler {} #[cfg(test)] #[path = "request_user_input_tests.rs"] diff --git a/codex-rs/core/src/tools/handlers/request_user_input_async.rs b/codex-rs/core/src/tools/handlers/request_user_input_async.rs index 17309c50..58a9383a 100644 --- a/codex-rs/core/src/tools/handlers/request_user_input_async.rs +++ b/codex-rs/core/src/tools/handlers/request_user_input_async.rs @@ -150,8 +150,4 @@ impl ToolExecutor for RequestUserInputAsyncHandler { } } -impl CoreToolRuntime for RequestUserInputAsyncHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for RequestUserInputAsyncHandler {} diff --git a/codex-rs/core/src/tools/handlers/send_message_to_user_async.rs b/codex-rs/core/src/tools/handlers/send_message_to_user_async.rs index 4d17d396..9177e0d9 100644 --- a/codex-rs/core/src/tools/handlers/send_message_to_user_async.rs +++ b/codex-rs/core/src/tools/handlers/send_message_to_user_async.rs @@ -103,8 +103,4 @@ impl ToolExecutor for SendMessageToUserAsyncHandler { } } -impl CoreToolRuntime for SendMessageToUserAsyncHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for SendMessageToUserAsyncHandler {} diff --git a/codex-rs/core/src/tools/handlers/sleep.rs b/codex-rs/core/src/tools/handlers/sleep.rs index 45db1a3b..90f8758a 100644 --- a/codex-rs/core/src/tools/handlers/sleep.rs +++ b/codex-rs/core/src/tools/handlers/sleep.rs @@ -160,8 +160,4 @@ impl ToolExecutor for SleepHandler { } } -impl CoreToolRuntime for SleepHandler { - fn is_builtin_control_tool(&self) -> bool { - true - } -} +impl CoreToolRuntime for SleepHandler {} diff --git a/codex-rs/core/src/tools/handlers/view_image.rs b/codex-rs/core/src/tools/handlers/view_image.rs index 4add23f9..129d26d5 100644 --- a/codex-rs/core/src/tools/handlers/view_image.rs +++ b/codex-rs/core/src/tools/handlers/view_image.rs @@ -214,10 +214,6 @@ impl CoreToolRuntime for ViewImageHandler { ) -> Result { function_tool_environment(invocation, |args: ToolEnvironmentArgs| args.environment_id) } - - fn is_builtin_control_tool(&self) -> bool { - true - } } pub struct ViewImageOutput { diff --git a/codex-rs/core/src/tools/mod.rs b/codex-rs/core/src/tools/mod.rs index eebc88af..8593b122 100644 --- a/codex-rs/core/src/tools/mod.rs +++ b/codex-rs/core/src/tools/mod.rs @@ -2,7 +2,6 @@ mod approvals; pub(crate) mod call_trace; pub(crate) mod code_mode; pub(crate) mod context; -mod control_tool_analytics; pub(crate) mod events; mod executed_tool_calls; pub(crate) mod handlers; diff --git a/codex-rs/core/src/tools/native_tool_review.rs b/codex-rs/core/src/tools/native_tool_review.rs index 0e251b4a..5db8db85 100644 --- a/codex-rs/core/src/tools/native_tool_review.rs +++ b/codex-rs/core/src/tools/native_tool_review.rs @@ -10,7 +10,7 @@ use crate::tools::context::ToolCallSource; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolPayload; use crate::tools::sandboxing::ApprovalRequestReasons; -use codex_analytics::GuardianApprovalRequestSource; +use codex_guardian_reviewer::GuardianApprovalRequestSource; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ReviewDecision; diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 1976726b..0b1ee458 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -19,7 +19,6 @@ use crate::tools::context::ToolEnvironments; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; -use crate::tools::control_tool_analytics::ControlToolCallGuard; use crate::tools::flat_tool_name; use crate::tools::handlers::multi_agents_spec::MULTI_AGENT_V1_NAMESPACE; use crate::tools::hook_names::HookToolName; @@ -28,7 +27,6 @@ use crate::tools::lifecycle::notify_tool_start; use crate::tools::router::tool_log_payload; use crate::tools::tool_dispatch_trace::ToolDispatchTrace; use crate::util::error_or_panic; -use codex_analytics::ControlToolCallStatus; use codex_extension_api::ToolCallOutcome; use codex_extension_api::ToolPolicy; use codex_history::CodexHarnessMetadata; @@ -67,11 +65,6 @@ pub(crate) trait CoreToolRuntime: ToolExecutor { false } - /// Whether this built-in control tool needs a structured tool-call event. - fn is_builtin_control_tool(&self) -> bool { - false - } - /// Returns a shared spec when both the spec and search metadata are immutable. fn immutable_spec(&self) -> Option<&Arc> { None @@ -834,10 +827,6 @@ impl ToolRegistry { &tool_result_tags, &extra_trace_fields, ); - if tool.is_builtin_control_tool() { - let mut analytics = ControlToolCallGuard::new(invocation); - analytics.finish(ControlToolCallStatus::Failed); - } dispatch_trace.record_failed(&err); notify_tool_finish_if_unclaimed( invocation, @@ -860,10 +849,6 @@ impl ToolRegistry { match apply_pre_tool_use(tool.as_ref(), &mut invocation).await { Ok(()) => {} Err(PreToolUseError::Blocked(message)) => { - if tool.is_builtin_control_tool() { - let mut analytics = ControlToolCallGuard::new(&invocation); - analytics.finish(ControlToolCallStatus::Rejected); - } let err = FunctionCallError::RespondToModel(message); dispatch_trace.record_failed(&err); notify_tool_finish_if_unclaimed( @@ -902,10 +887,6 @@ impl ToolRegistry { .or_cancel_tool(&cancellation_token) .await?; } - let mut control_tool_analytics = tool - .is_builtin_control_tool() - .then(|| ControlToolCallGuard::new(&invocation)); - if let Some(command) = shell_script_for_invocation(&invocation) { let parsed = parse_shell_script(&command); let mut categories = parsed.iter().map(|command| match command { @@ -944,13 +925,6 @@ impl ToolRegistry { Ok(result) => result.result.success_for_logging(), Err(_) => false, }; - if let Some(analytics) = control_tool_analytics.as_mut() { - analytics.finish(if success { - ControlToolCallStatus::Completed - } else { - ControlToolCallStatus::Failed - }); - } emit_metric_for_tool_read(&invocation, success); let post_tool_use_payload = if success { result diff --git a/codex-rs/core/src/tools/registry_tests.rs b/codex-rs/core/src/tools/registry_tests.rs index 10f44529..ce6fb811 100644 --- a/codex-rs/core/src/tools/registry_tests.rs +++ b/codex-rs/core/src/tools/registry_tests.rs @@ -626,7 +626,6 @@ fn post_tool_use_feedback_output_preserves_fallback_token_limit_override( meta: None, }, tool_input: serde_json::json!({}), - result_metadata_capture_allowed: false, wall_time: Duration::ZERO, original_image_detail_supported: false, truncation_policy, @@ -728,7 +727,6 @@ fn post_tool_use_feedback_output_preserves_mcp_result_metadata(tool_error: bool) meta: Some(metadata.clone()), }, tool_input: serde_json::json!({ "query": "rewritten query" }), - result_metadata_capture_allowed: true, wall_time: std::time::Duration::ZERO, original_image_detail_supported: false, truncation_policy: codex_utils_output_truncation::TruncationPolicy::Bytes(64), @@ -742,7 +740,8 @@ fn post_tool_use_feedback_output_preserves_mcp_result_metadata(tool_error: bool) arguments: "{}".to_string(), }; let original_result = result.original.code_mode_result(&payload); - assert_eq!(result.tool_result_metadata(), Some(&metadata)); + // MCP result metadata is never captured for usage reporting. + assert_eq!(result.tool_result_metadata(), None); assert_eq!(result.code_mode_result(&payload), original_result); } diff --git a/codex-rs/core/src/tools/runtimes/mod.rs b/codex-rs/core/src/tools/runtimes/mod.rs index b8a3e613..efe8b684 100644 --- a/codex-rs/core/src/tools/runtimes/mod.rs +++ b/codex-rs/core/src/tools/runtimes/mod.rs @@ -13,7 +13,6 @@ use crate::sandboxing::SandboxPermissions; use crate::shell::Shell; use crate::shell::ShellType; use codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR; -use codex_core_plugins::PLUGIN_METRICS_OUTPUT_ENV_VAR; use codex_file_system::WindowsSandboxSelection; #[cfg(unix)] use codex_install_context::InstallContext; @@ -345,7 +344,6 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot( CODEX_VERSION_ENV_VAR, CODEX_PERMISSION_PROFILE_ENV_VAR, CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, - PLUGIN_METRICS_OUTPUT_ENV_VAR, ] { if let Some(value) = env.get(key) { override_env.insert(key.to_string(), value.clone()); @@ -357,7 +355,6 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot( &[ CODEX_PERMISSION_PROFILE_ENV_VAR, CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, - PLUGIN_METRICS_OUTPUT_ENV_VAR, CODEX_TOOL_CALL_ID_ENV_VAR, ], ); diff --git a/codex-rs/core/src/tools/runtimes/mod_tests.rs b/codex-rs/core/src/tools/runtimes/mod_tests.rs index d5933281..0e3fb732 100644 --- a/codex-rs/core/src/tools/runtimes/mod_tests.rs +++ b/codex-rs/core/src/tools/runtimes/mod_tests.rs @@ -669,50 +669,6 @@ fn maybe_wrap_shell_lc_with_snapshot_restores_apply_patch_rollout_state() { assert_eq!(output.stdout, b""); } -#[test] -fn maybe_wrap_shell_lc_with_snapshot_restores_reserved_metrics_output_env() { - let dir = tempdir().expect("create temp dir"); - let snapshot_path = dir.path().join("snapshot.sh"); - std::fs::write( - &snapshot_path, - "# Snapshot file\nexport CODEX_PLUGIN_METRICS_OUTPUT='/stale/path'\n", - ) - .expect("write snapshot"); - let (session_shell, shell_snapshot) = - shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot_path.abs()); - let command = vec![ - "/bin/bash".to_string(), - "-lc".to_string(), - "printf '%s' \"${CODEX_PLUGIN_METRICS_OUTPUT-unset}\"".to_string(), - ]; - - for (live_value, expected) in [(None, "unset"), (Some("/private/path"), "/private/path")] { - let env = live_value - .map(|value| { - HashMap::from([(PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(), value.to_string())]) - }) - .unwrap_or_default(); - let rewritten = maybe_wrap_shell_lc_with_snapshot( - &command, - &session_shell, - Some(&shell_snapshot), - &HashMap::new(), - &env, - &RuntimePathPrepends::default(), - ); - let mut process = Command::new(&rewritten[0]); - process.args(&rewritten[1..]); - match live_value { - Some(value) => process.env(PLUGIN_METRICS_OUTPUT_ENV_VAR, value), - None => process.env_remove(PLUGIN_METRICS_OUTPUT_ENV_VAR), - }; - let output = process.output().expect("run rewritten command"); - - assert!(output.status.success(), "command failed: {output:?}"); - assert_eq!(String::from_utf8_lossy(&output.stdout), expected); - } -} - #[test] fn maybe_wrap_shell_lc_with_snapshot_restores_proxy_env_from_process_env() { let dir = tempdir().expect("create temp dir"); diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 915bf0a3..5abd98a6 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -9,7 +9,6 @@ use crate::exec::ExecExpiration; use crate::guardian::GUARDIAN_REVIEW_TIMEOUT; use crate::guardian::GuardianNetworkAccessTrigger; use crate::guardian::routes_approval_policy_to_guardian; -use crate::plugins::metrics::sidecar_for_command; use crate::sandboxing::ExecOptions; use crate::sandboxing::ExecServerEnvConfig; use crate::sandboxing::SandboxPermissions; @@ -40,7 +39,6 @@ use crate::unified_exec::TerminalPermissions; use crate::unified_exec::TerminalSandboxSource; use crate::unified_exec::UnifiedExecProcess; use crate::unified_exec::UnifiedExecProcessManager; -use codex_core_plugins::PluginMetricsSidecar; use codex_features::Feature; use codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY; use codex_network_proxy::ManagedNetworkSandboxContext; @@ -104,7 +102,6 @@ pub struct UnifiedExecRuntime<'a> { pub(crate) struct UnifiedExecAttempt { pub(crate) process: UnifiedExecProcess, - pub(crate) metrics_sidecar: Option, pub(crate) permissions: TerminalPermissions, } @@ -442,16 +439,6 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec } } } - let metrics_sidecar = sidecar_for_command( - ctx, - &prepared.resolved.command, - &prepared.cwd, - prepared.turn_environment.environment().as_ref(), - ) - .await; - if let Some(sidecar) = metrics_sidecar.as_ref() { - sidecar.install_output_env(&mut env); - } #[cfg(unix)] let runtime_path_prepends = { let mut runtime_path_prepends = RuntimePathPrepends::default(); @@ -561,9 +548,6 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec } else { command }; - let sidecar_permissions = metrics_sidecar - .as_ref() - .map(PluginMetricsSidecar::additional_permissions); let snapshot_permissions = shell_snapshot_location .as_ref() .filter(|_| { @@ -580,7 +564,7 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec ) }); let internal_permissions = - merge_permission_profiles(sidecar_permissions.as_ref(), snapshot_permissions.as_ref()); + merge_permission_profiles(/*base*/ None, snapshot_permissions.as_ref()); let additional_permissions = merge_permission_profiles( prepared.permissions.additional_permissions.as_ref(), internal_permissions.as_ref(), @@ -649,7 +633,6 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec process._shell_snapshot = shell_snapshot; Ok(UnifiedExecAttempt { process, - metrics_sidecar, permissions, }) } diff --git a/codex-rs/core/src/turn_metadata.rs b/codex-rs/core/src/turn_metadata.rs index 70e76f87..8c36248c 100644 --- a/codex-rs/core/src/turn_metadata.rs +++ b/codex-rs/core/src/turn_metadata.rs @@ -15,7 +15,6 @@ use tokio_util::task::AbortOnDropHandle; use crate::responses_metadata::AGENT_NAME_KEY; use crate::responses_metadata::CodexResponsesMetadata; use crate::responses_metadata::CodexResponsesRequestKind; -use crate::responses_metadata::MAX_EXTRA_METADATA_VALUE_BYTES; use crate::responses_metadata::PARENT_TURN_ID_KEY; use crate::responses_metadata::ROOT_TURN_ID_KEY; use crate::responses_metadata::TurnMetadataWorkspace; @@ -48,6 +47,7 @@ const MODEL_KEY: &str = "model"; const CODEX_VERSION_KEY: &str = "codex_version"; const REASONING_EFFORT_KEY: &str = "reasoning_effort"; const USER_INPUT_REQUESTED_DURING_TURN_KEY: &str = "user_input_requested_during_turn"; +#[cfg(test)] const WORKSPACE_KIND_KEY: &str = "workspace_kind"; fn is_targeted_continuation(value: &str) -> bool { @@ -186,36 +186,6 @@ pub(crate) struct TurnMetadataState { git_enrichment_complete: watch::Sender, } -impl codex_analytics::TurnAnalyticsMetadata for TurnMetadataState { - fn root_turn_id(&self) -> Option { - TurnMetadataState::root_turn_id(self) - } - - fn turn_trigger(&self) -> Option { - self.turn_trigger - .get() - .filter(|trigger| trigger.len() <= MAX_EXTRA_METADATA_VALUE_BYTES) - .cloned() - } - - fn codex_turn_source(&self) -> Option { - // Match Responses metadata precedence without copying oversized client values to analytics. - let configured_metadata = self - .responses_api_metadata - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let client_metadata = self - .responsesapi_client_metadata - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner); - configured_metadata - .get("source") - .or_else(|| client_metadata.get("source")) - .filter(|source| source.len() <= MAX_EXTRA_METADATA_VALUE_BYTES) - .cloned() - } -} - impl TurnMetadataState { #[allow(clippy::too_many_arguments)] pub(crate) fn new( @@ -439,6 +409,7 @@ impl TurnMetadataState { .unwrap_or_else(std::sync::PoisonError::into_inner) = metadata; } + #[cfg(test)] pub(crate) fn workspace_kind(&self) -> Option { self.responsesapi_client_metadata .read() diff --git a/codex-rs/core/src/turn_metadata_tests.rs b/codex-rs/core/src/turn_metadata_tests.rs index 2d8aad6e..54f53311 100644 --- a/codex-rs/core/src/turn_metadata_tests.rs +++ b/codex-rs/core/src/turn_metadata_tests.rs @@ -1,6 +1,9 @@ use super::*; -use crate::responses_metadata::ANALYTICS_ENABLED_KEY; +use crate::compaction_metadata::CompactionImplementation; +use crate::compaction_metadata::CompactionPhase; +use crate::compaction_metadata::CompactionReason; +use crate::compaction_metadata::CompactionTrigger; use crate::responses_metadata::AUTO_REVIEW_ENABLED_KEY; use crate::responses_metadata::CONTEXT_WINDOW_ID_KEY; use crate::responses_metadata::CodexResponsesMetadata; @@ -9,6 +12,7 @@ use crate::responses_metadata::CompactionTurnMetadata; use crate::responses_metadata::FORKED_FROM_ORDINAL_EXCLUSIVE_KEY; use crate::responses_metadata::INSTALLATION_ID_KEY; use crate::responses_metadata::LEGACY_CODE_MODE_TOOL_NAMES_KEY; +use crate::responses_metadata::LEGACY_USAGE_DATA_ENABLED_KEY; use crate::responses_metadata::MCP_ATTRIBUTION_CLIENT_METADATA_KEY; use crate::responses_metadata::NODE_REPL_AUTO_REVIEW_REQUIRED_KEY; use crate::responses_metadata::NODE_REPL_DISABLED_KEY; @@ -23,11 +27,6 @@ use crate::responses_metadata::validate_extra_metadata; use crate::session::step_context::StepContext; use crate::session::tests::make_session_and_context; use crate::session::tests::update_turn_settings_for_test; -use codex_analytics::CompactionImplementation; -use codex_analytics::CompactionPhase; -use codex_analytics::CompactionReason; -use codex_analytics::CompactionTrigger; -use codex_analytics::TurnAnalyticsMetadata; use codex_models_manager::model_info::model_info_from_slug; use codex_protocol::AgentPath; use codex_protocol::config_types::WindowsSandboxLevel; @@ -848,7 +847,10 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields( ); state.set_responses_api_metadata(BTreeMap::from([ ("codex_security_surface".to_string(), "sdk".to_string()), - (ANALYTICS_ENABLED_KEY.to_string(), "false".to_string()), + ( + LEGACY_USAGE_DATA_ENABLED_KEY.to_string(), + "false".to_string(), + ), ("source".to_string(), " Configured_Source ".to_string()), ( WINDOW_NUMBER_KEY.to_string(), @@ -868,7 +870,10 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields( "client-supplied".to_string(), ), ("fiber_run_id".to_string(), "fiber-123".to_string()), - (ANALYTICS_ENABLED_KEY.to_string(), "true".to_string()), + ( + LEGACY_USAGE_DATA_ENABLED_KEY.to_string(), + "true".to_string(), + ), ("origin".to_string(), "東京".to_string()), ("workspace_kind".to_string(), "projectless".to_string()), ("source".to_string(), "client-source".to_string()), @@ -943,7 +948,7 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields( let json: Value = serde_json::from_str(&header).expect("json"); assert_eq!(json["fiber_run_id"].as_str(), Some("fiber-123")); - assert!(json.get(ANALYTICS_ENABLED_KEY).is_none()); + assert!(json.get(LEGACY_USAGE_DATA_ENABLED_KEY).is_none()); assert_eq!(json["origin"].as_str(), Some("東京")); assert_eq!(json["workspace_kind"].as_str(), Some("projectless")); assert_eq!(json["codex_security_surface"].as_str(), Some("sdk")); @@ -1037,7 +1042,7 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields( assert!(meta.get(ROOT_TURN_ID_KEY).is_none()); assert!(meta.get(WINDOW_ID_KEY).is_none()); assert!(meta.get("codex_security_surface").is_none()); - assert!(meta.get(ANALYTICS_ENABLED_KEY).is_none()); + assert!(meta.get(LEGACY_USAGE_DATA_ENABLED_KEY).is_none()); let extension_meta = state .current_meta_value_for_extension_request(test_mcp_turn_metadata_context()) .expect("extension metadata should be present"); @@ -1047,78 +1052,7 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields( assert_eq!(extension_meta["model"], "gpt-5.4"); assert!(extension_meta.get(TOOL_NAMESPACES_INFO_KEY).is_none()); assert_eq!(state.workspace_kind().as_deref(), Some("projectless")); - assert_eq!( - (state.turn_trigger(), state.codex_turn_source()), - ( - Some("goal".to_string()), - Some(" Configured_Source ".to_string()) - ) - ); assert_eq!(model_request_json["source"], " Configured_Source "); - - for (configured, client, expected) in [ - (None, None, None), - ( - None, - Some(" New_Source ".to_string()), - Some(" New_Source ".to_string()), - ), - (None, Some(String::new()), Some(String::new())), - (None, Some("é".repeat(/*n*/ 64)), Some("é".repeat(/*n*/ 64))), - (None, Some("é".repeat(/*n*/ 65)), None), - ( - Some("x".repeat(/*n*/ 129)), - Some("client-source".to_string()), - None, - ), - ] { - state.set_responses_api_metadata( - configured - .map(|source| ("source".to_string(), source)) - .into_iter() - .collect(), - ); - state.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate { - replacement: Some( - client - .map(|source| ("source".to_string(), source)) - .into_iter() - .collect(), - ), - ..Default::default() - }); - assert_eq!(state.codex_turn_source(), expected); - } -} - -#[test] -fn turn_metadata_state_bounds_trigger_only_for_analytics() { - let temp_dir = TempDir::new().expect("temp dir"); - for (characters, included) in [(64, true), (65, false)] { - let state = TurnMetadataState::new( - "session-a".to_string(), - "thread-a".to_string(), - /*forked_from_thread_id*/ None, - /*parent_thread_id*/ None, - &SessionSource::Exec, - /*thread_source*/ None, - "turn-a".to_string(), - temp_dir.path().abs(), - &PermissionProfile::read_only(), - WindowsSandboxLevel::Disabled, - /*enforce_managed_network*/ false, - /*auto_review_enabled*/ false, - &model_info_from_slug("gpt-5.4"), - ); - let trigger = "é".repeat(characters); - state.set_turn_trigger(trigger.clone()); - let metadata: Value = - serde_json::from_str(&test_turn_metadata_header(&state)).expect("json"); - assert_eq!( - (state.turn_trigger(), metadata[TURN_TRIGGER_KEY].as_str()), - (included.then(|| trigger.clone()), Some(trigger.as_str())) - ); - } } #[test_case::test_case(r#"{"review_target":"RB._~:-opaque"}"#, None; "target")] @@ -1238,7 +1172,7 @@ fn responses_api_metadata_accepts_previously_valid_reserved_keys() { for legacy_key in [ WINDOW_NUMBER_KEY, FORKED_FROM_ORDINAL_EXCLUSIVE_KEY, - ANALYTICS_ENABLED_KEY, + LEGACY_USAGE_DATA_ENABLED_KEY, ] { assert_eq!( validate_extra_metadata( diff --git a/codex-rs/core/src/turn_timing.rs b/codex-rs/core/src/turn_timing.rs index f666d7fc..fe33a659 100644 --- a/codex-rs/core/src/turn_timing.rs +++ b/codex-rs/core/src/turn_timing.rs @@ -6,7 +6,6 @@ use std::time::Instant; use std::time::SystemTime; use std::time::UNIX_EPOCH; -use codex_analytics::TurnProfile; use codex_direct_tool_timing::DirectToolTimings; use codex_otel::TURN_TTFM_DURATION_METRIC; use codex_protocol::ThreadId; @@ -14,6 +13,11 @@ use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use tokio::sync::Mutex; +mod profile; +pub(crate) use profile::TurnCriticalPath; +pub(crate) use profile::TurnCriticalPathDurations; +pub(crate) use profile::TurnProfile; + use crate::ResponseEvent; use crate::session::turn_context::TurnContext; use crate::stream_events_utils::raw_assistant_output_text_from_item; @@ -21,7 +25,7 @@ use codex_direct_tool_timing::ToolBatchTiming; use codex_utils_critical_path::CriticalPath; use codex_utils_critical_path::WorkKind; -// Reuse the finalized analytics counters instead of counting sampled child spans. +// Reuse the finalized profile counters instead of counting sampled child spans. // Recovery can complete the same turn ID again, so consumers must retain the // completion event's trace and timestamp rather than deduplicating by turn alone. pub(crate) fn record_terminal_turn_profile( @@ -29,10 +33,7 @@ pub(crate) fn record_terminal_turn_profile( turn: &TurnContext, profile: &TurnProfile, ) { - if !matches!( - profile.critical_path, - codex_analytics::TurnCriticalPath::Disabled - ) { + if !matches!(profile.critical_path, TurnCriticalPath::Disabled) { turn.turn_timing_state .critical_path_metrics .get_or_init(|| { diff --git a/codex-rs/core/src/turn_timing/profile.rs b/codex-rs/core/src/turn_timing/profile.rs new file mode 100644 index 00000000..87a92241 --- /dev/null +++ b/codex-rs/core/src/turn_timing/profile.rs @@ -0,0 +1,59 @@ +//! Turn profile and critical-path summaries, used for local tracing and local metrics only. +//! Missing capture never becomes a zero-duration measurement. + +/// Capture coverage for one finalized turn, independent of its completion status. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum TurnCriticalPath { + #[default] + Disabled, + Incomplete, + Complete(TurnCriticalPathDurations), +} + +impl TurnCriticalPath { + pub(crate) fn status(&self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Incomplete => "incomplete", + Self::Complete(_) => "complete", + } + } + + pub(crate) fn durations(&self) -> Option<&TurnCriticalPathDurations> { + match self { + Self::Complete(durations) => Some(durations), + Self::Disabled | Self::Incomplete => None, + } + } +} + +/// Category totals over the server turn interval, truncated to milliseconds. +/// Inference is the compatibility total of sampling and compaction, not another leaf. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct TurnCriticalPathDurations { + pub(crate) duration_ms: u64, + pub(crate) inference_ms: u64, + pub(crate) sampling_ms: u64, + pub(crate) compaction_ms: u64, + pub(crate) auto_review_ms: u64, + /// Portion of auto_review_ms outside observed Guardian turn execution; not additive. + pub(crate) auto_review_overhead_ms: Option, + pub(crate) user_wait_ms: u64, + pub(crate) tools_ms: u64, + pub(crate) overhead_ms: u64, + pub(crate) unknown_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct TurnProfile { + pub(crate) critical_path: TurnCriticalPath, + pub(crate) before_first_sampling_ms: u64, + pub(crate) sampling_ms: u64, + pub(crate) compaction_ms: u64, + pub(crate) between_sampling_overhead_ms: u64, + pub(crate) tool_blocking_ms: u64, + pub(crate) after_last_sampling_ms: u64, + pub(crate) sampling_request_count: u32, + pub(crate) sampling_retry_count: u32, + pub(crate) tools_change_count: u32, +} diff --git a/codex-rs/core/src/turn_timing/report.rs b/codex-rs/core/src/turn_timing/report.rs index 1928c44a..1927bd6a 100644 --- a/codex-rs/core/src/turn_timing/report.rs +++ b/codex-rs/core/src/turn_timing/report.rs @@ -1,9 +1,9 @@ //! Report the frozen critical path over the same interval as the turn profile. +use super::TurnCriticalPath; +use super::TurnCriticalPathDurations; use super::TurnProfileState; use super::duration_to_u64_ms; -use codex_analytics::TurnCriticalPath; -use codex_analytics::TurnCriticalPathDurations; use codex_otel::TURN_CRITICAL_PATH_CAPTURE_METRIC; use codex_otel::TURN_CRITICAL_PATH_COMPONENT_METRIC; use codex_otel::TURN_CRITICAL_PATH_DURATION_METRIC; @@ -31,10 +31,7 @@ pub(super) fn completed_critical_path(state: &TurnProfileState, end: Instant) -> }) } -pub(super) fn record_turn_profile_metrics( - turn: &super::TurnContext, - profile: &codex_analytics::TurnProfile, -) { +pub(super) fn record_turn_profile_metrics(turn: &super::TurnContext, profile: &super::TurnProfile) { let telemetry = &turn.session_telemetry; let sku = codex_otel::bounded_product_sku(turn.config.apps_mcp_product_sku.as_deref()) .unwrap_or("unknown"); diff --git a/codex-rs/core/src/turn_timing_tests.rs b/codex-rs/core/src/turn_timing_tests.rs index 2d81c1c5..a495972b 100644 --- a/codex-rs/core/src/turn_timing_tests.rs +++ b/codex-rs/core/src/turn_timing_tests.rs @@ -1,5 +1,5 @@ use super::ToolBatchTiming; -use codex_analytics::TurnProfile; +use crate::turn_timing::TurnProfile; use codex_protocol::items::AgentMessageItem; use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; @@ -247,7 +247,7 @@ fn turn_profile_breaks_down_sampling_blocking_and_retry_overhead() { assert_eq!( state.complete(started_at + Duration::from_millis(1_300)), TurnProfile { - critical_path: codex_analytics::TurnCriticalPath::Disabled, + critical_path: crate::turn_timing::TurnCriticalPath::Disabled, before_first_sampling_ms: 100, sampling_ms: 700, compaction_ms: 0, @@ -286,8 +286,8 @@ fn turn_profile_counts_compaction_as_an_exclusive_phase() { assert_eq!( state.complete(started_at + Duration::from_millis(1_100)), TurnProfile { - critical_path: codex_analytics::TurnCriticalPath::Complete( - codex_analytics::TurnCriticalPathDurations { + critical_path: crate::turn_timing::TurnCriticalPath::Complete( + crate::turn_timing::TurnCriticalPathDurations { duration_ms: 1100, inference_ms: 800, sampling_ms: 300, @@ -335,18 +335,20 @@ async fn turn_profile_and_duration_share_a_completion_instant() { let (_, duration_ms, profile) = result; assert_eq!( profile.critical_path, - codex_analytics::TurnCriticalPath::Complete(codex_analytics::TurnCriticalPathDurations { - duration_ms: duration_ms.unwrap() as u64, - inference_ms: 0, - sampling_ms: 0, - compaction_ms: 0, - auto_review_ms: 0, - auto_review_overhead_ms: Some(0), - user_wait_ms: 0, - tools_ms: 0, - overhead_ms: duration_ms.unwrap() as u64, - unknown_ms: 0, - }) + crate::turn_timing::TurnCriticalPath::Complete( + crate::turn_timing::TurnCriticalPathDurations { + duration_ms: duration_ms.unwrap() as u64, + inference_ms: 0, + sampling_ms: 0, + compaction_ms: 0, + auto_review_ms: 0, + auto_review_overhead_ms: Some(0), + user_wait_ms: 0, + tools_ms: 0, + overhead_ms: duration_ms.unwrap() as u64, + unknown_ms: 0, + } + ) ); let classified_ms = profile.before_first_sampling_ms + profile.sampling_ms @@ -391,18 +393,20 @@ fn capture_preserves_phases_and_freezes_missing_dependencies() { ); assert_eq!( profile.critical_path, - codex_analytics::TurnCriticalPath::Complete(codex_analytics::TurnCriticalPathDurations { - duration_ms: 60, - inference_ms: 10, - sampling_ms: 10, - compaction_ms: 0, - auto_review_ms: 0, - auto_review_overhead_ms: None, - user_wait_ms: 0, - tools_ms: 0, - overhead_ms: 20, - unknown_ms: 30, - }) + crate::turn_timing::TurnCriticalPath::Complete( + crate::turn_timing::TurnCriticalPathDurations { + duration_ms: 60, + inference_ms: 10, + sampling_ms: 10, + compaction_ms: 0, + auto_review_ms: 0, + auto_review_overhead_ms: None, + user_wait_ms: 0, + tools_ms: 0, + overhead_ms: 20, + unknown_ms: 30, + } + ) ); let frozen_path = state.path.clone(); state.end_phase(time_after_turn_start(70), TurnProfilePhase::ToolBlocking); @@ -420,7 +424,7 @@ async fn invalidation_and_late_guard_drop_cannot_restore_a_frozen_path() { let (_, _, profile) = timing.complete_profile_and_duration_ms().await; assert_eq!( profile.critical_path, - codex_analytics::TurnCriticalPath::Incomplete + crate::turn_timing::TurnCriticalPath::Incomplete ); timing.enable_critical_path(); drop(guard); @@ -489,18 +493,20 @@ fn critical_path_report_retains_fractional_millisecond_rounding_and_compaction() let profile = state.complete(end); assert_eq!( profile.critical_path, - codex_analytics::TurnCriticalPath::Complete(codex_analytics::TurnCriticalPathDurations { - duration_ms: 1, - inference_ms: 1, - sampling_ms: 0, - compaction_ms: 1, - auto_review_ms: 0, - auto_review_overhead_ms: Some(0), - user_wait_ms: 0, - tools_ms: 0, - overhead_ms: 0, - unknown_ms: 0, - }) + crate::turn_timing::TurnCriticalPath::Complete( + crate::turn_timing::TurnCriticalPathDurations { + duration_ms: 1, + inference_ms: 1, + sampling_ms: 0, + compaction_ms: 1, + auto_review_ms: 0, + auto_review_overhead_ms: Some(0), + user_wait_ms: 0, + tools_ms: 0, + overhead_ms: 0, + unknown_ms: 0, + } + ) ); } diff --git a/codex-rs/core/src/unified_exec/async_watcher.rs b/codex-rs/core/src/unified_exec/async_watcher.rs index 49ae8b2c..ffac5cf6 100644 --- a/codex-rs/core/src/unified_exec/async_watcher.rs +++ b/codex-rs/core/src/unified_exec/async_watcher.rs @@ -8,14 +8,11 @@ use tokio::time::Duration; use tokio::time::Instant; use tokio::time::Sleep; -use super::SharedPluginMetricsSidecar; use super::UnifiedExecContext; use super::process::OutputBuffers; use super::process::OutputHandles; use super::process::UnifiedExecProcess; -use super::take_plugin_metrics_sidecar; use crate::exec::MAX_EXEC_OUTPUT_DELTAS_PER_CALL; -use crate::plugins::metrics::finish_and_track_measurements; use crate::session::session::Session; use crate::session::turn_context::TurnContext; use crate::tools::events::ToolEmitter; @@ -165,12 +162,10 @@ pub(crate) fn spawn_exit_watcher( output_buffer: Arc>, started_at: Instant, network_denial_monitor: Option>, - plugin_metrics_sidecar: Option, ) { let session_ref = Arc::clone(&context.session); let turn_ref = Arc::clone(&context.step_context.turn); let model_info = Arc::clone(&context.step_context.settings.model_info); - let model_context = context.step_context.model_context(); let call_id = context.call_id.clone(); let exit_token = process.cancellation_token(); let output_drained = process.output_drained_notify(); @@ -188,11 +183,7 @@ pub(crate) fn spawn_exit_watcher( let _interaction_guard = interaction_lock.lock_owned().await; let duration = Instant::now().saturating_duration_since(started_at); - let plugin_metrics_sidecar = plugin_metrics_sidecar - .as_ref() - .and_then(take_plugin_metrics_sidecar); if let Some(message) = process.failure_message() { - drop(plugin_metrics_sidecar); emit_failed_exec_end_for_unified_exec( process.sandbox_type(), session_ref, @@ -212,15 +203,6 @@ pub(crate) fn spawn_exit_watcher( } else { let exit_code = process.exit_code().unwrap_or(-1); let timed_out = process.timed_out(); - finish_and_track_measurements( - plugin_metrics_sidecar, - exit_code, - &session_ref, - &turn_ref, - &model_context, - &call_id, - ) - .await; emit_exec_end_for_unified_exec( process.sandbox_type(), session_ref, diff --git a/codex-rs/core/src/unified_exec/async_watcher_tests.rs b/codex-rs/core/src/unified_exec/async_watcher_tests.rs index 5e9973c7..aefc3021 100644 --- a/codex-rs/core/src/unified_exec/async_watcher_tests.rs +++ b/codex-rs/core/src/unified_exec/async_watcher_tests.rs @@ -109,7 +109,6 @@ async fn completed_output_preserves_bytes_before_subscription( output_buffer, Instant::now(), /*network_denial_monitor*/ None, - /*plugin_metrics_sidecar*/ None, ); stdout_tx.send(late_output.to_vec())?; drop(stdout_tx); @@ -325,7 +324,6 @@ async fn exit_watcher_waits_for_late_network_denial_before_classifying_end() -> output_buffer, Instant::now(), Some(network_denial_monitor), - /*plugin_metrics_sidecar*/ None, ); let exited_at = Instant::now(); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 466af4bd..43dd9509 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -41,7 +41,6 @@ use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; use crate::tools::handlers::unified_exec::preparation::PreparedExecCommand; use crate::tools::network_approval::DeferredNetworkApproval; -use codex_core_plugins::PluginMetricsSidecar; mod async_watcher; mod command_sessions; @@ -180,7 +179,6 @@ impl Default for UnifiedExecProcessManager { struct ProcessEntry { process: Arc, - plugin_metrics_sidecar: Option, call_id: String, process_id: i32, cwd: PathUri, @@ -194,17 +192,6 @@ struct ProcessEntry { last_used: tokio::time::Instant, } -type SharedPluginMetricsSidecar = Arc>>; - -fn take_plugin_metrics_sidecar( - sidecar: &SharedPluginMetricsSidecar, -) -> Option { - sidecar - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .take() -} - pub(crate) fn clamp_yield_time(yield_time_ms: u64) -> u64 { let yield_time_ms = if cfg!(windows) { yield_time_ms.max(WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS) diff --git a/codex-rs/core/src/unified_exec/mod_tests.rs b/codex-rs/core/src/unified_exec/mod_tests.rs index 78099ddb..f890c6ee 100644 --- a/codex-rs/core/src/unified_exec/mod_tests.rs +++ b/codex-rs/core/src/unified_exec/mod_tests.rs @@ -138,7 +138,6 @@ async fn exec_command_with_tty( if process_started_alive { let entry = ProcessEntry { process: Arc::clone(&process), - plugin_metrics_sidecar: None, call_id: context.call_id.clone(), process_id, cwd: cwd.clone().into(), @@ -610,7 +609,6 @@ async fn terminating_initial_exec_command_rechecks_initial_response_state() -> a process_id, ProcessEntry { process, - plugin_metrics_sidecar: None, call_id: "call".to_string(), process_id, cwd: cwd.into(), @@ -700,7 +698,6 @@ async fn terminating_during_stdin_poll_returns_exited_response( process_id, ProcessEntry { process: Arc::clone(&process), - plugin_metrics_sidecar: None, call_id: "call".to_string(), process_id, cwd: cwd.into(), diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index caa45622..3f897483 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -26,7 +26,6 @@ use crate::exec_env::inject_permission_profile_env; use crate::exec_env::inject_session_env; use crate::exec_env::set_tool_call_id_env_var; use crate::guardian::GuardianReviewContext; -use crate::plugins::metrics::finish_and_track_measurements; use crate::sandboxing::ExecOptions; use crate::sandboxing::ExecRequest; use crate::sandboxing::ExecServerEnvConfig; @@ -68,12 +67,8 @@ use crate::unified_exec::process::OutputBuffers; use crate::unified_exec::process::OutputHandles; use crate::unified_exec::process::UnifiedExecProcess; use crate::unified_exec::shell_snapshot::shell_snapshot_request; -use crate::unified_exec::take_plugin_metrics_sidecar; use crate::unified_exec::trace_id; -use codex_core_plugins::PLUGIN_METRICS_OUTPUT_ENV_VAR; use codex_core_plugins::PluginCommandAttribution; -use codex_core_plugins::PluginMetricsSidecar; -use codex_core_plugins::strip_output_env; use codex_network_proxy::NetworkPolicyDecider; use codex_network_proxy::NetworkProxy; use codex_protocol::config_types::ShellEnvironmentPolicy; @@ -145,7 +140,6 @@ pub(crate) fn exec_env_policy_from_shell_policy( CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(), CODEX_VERSION_ENV_VAR.to_string(), codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(), - PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(), ]); let mut r#set = policy.r#set.clone(); r#set.retain(|key, _| { @@ -153,7 +147,6 @@ pub(crate) fn exec_env_policy_from_shell_policy( CODEX_PERMISSION_PROFILE_ENV_VAR, CODEX_VERSION_ENV_VAR, codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, - PLUGIN_METRICS_OUTPUT_ENV_VAR, ] .iter() .any(|runtime_key| key.eq_ignore_ascii_case(runtime_key)) @@ -270,25 +263,9 @@ struct PreparedProcessHandles { struct InitialExecCommandGuard { active: Option>, - metrics_sidecar: Option, collection_finished: CancellationToken, } -impl InitialExecCommandGuard { - async fn finish_plugin_metrics(&mut self, context: &UnifiedExecContext, exit_code: i32) { - let model_context = context.step_context.model_context(); - finish_and_track_measurements( - self.metrics_sidecar.take(), - exit_code, - &context.session, - &context.step_context.turn, - &model_context, - &context.call_id, - ) - .await; - } -} - impl Drop for InitialExecCommandGuard { fn drop(&mut self) { if let Some(active) = self.active.as_ref() { @@ -553,7 +530,6 @@ impl UnifiedExecProcessManager { }; let UnifiedExecAttempt { process, - metrics_sidecar, permissions, } = attempt; let process = Arc::new(process); @@ -620,7 +596,6 @@ impl UnifiedExecProcessManager { .load(Ordering::Acquire)); let mut initial_exec_command_guard = InitialExecCommandGuard { active: None, - metrics_sidecar, collection_finished: process.output_handles().collection_finished.clone(), }; if process_stored { @@ -640,7 +615,6 @@ impl UnifiedExecProcessManager { prepared.tty, deferred_network_approval.clone(), network_denial_monitor, - initial_exec_command_guard.metrics_sidecar.take(), Arc::clone(&output_buffer), Arc::clone(&initial_exec_command_active), ) @@ -774,19 +748,6 @@ impl UnifiedExecProcessManager { ) })?; } - let metrics_sidecar = entry - .plugin_metrics_sidecar - .as_ref() - .and_then(take_plugin_metrics_sidecar); - finish_and_track_measurements( - metrics_sidecar, - exit_code.unwrap_or(-1), - &context.session, - &context.step_context.turn, - &model_context, - &context.call_id, - ) - .await; (None, exit_code) } ProcessStatus::Unknown => { @@ -820,9 +781,6 @@ impl UnifiedExecProcessManager { } let exit_code = process.exit_code(); let exit = exit_code.unwrap_or(-1); - initial_exec_command_guard - .finish_plugin_metrics(context, exit) - .await; emit_exec_end_for_unified_exec( process.sandbox_type(), Arc::clone(&context.session), @@ -1259,15 +1217,11 @@ impl UnifiedExecProcessManager { tty: bool, network_approval: Option, network_denial_monitor: Option>, - metrics_sidecar: Option, output_buffer: Arc>, initial_exec_command_active: Arc, ) { - let plugin_metrics_sidecar = - metrics_sidecar.map(|sidecar| Arc::new(std::sync::Mutex::new(Some(sidecar)))); let entry = ProcessEntry { process: Arc::clone(&process), - plugin_metrics_sidecar: plugin_metrics_sidecar.clone(), call_id: context.call_id.clone(), process_id, cwd: cwd.clone(), @@ -1296,7 +1250,6 @@ impl UnifiedExecProcessManager { output_buffer, started_at, network_denial_monitor, - plugin_metrics_sidecar, ); // Install the watcher before cancellable cleanup, and outside the process-store lock. if let Some(pruned_entry) = pruned_entry { @@ -1505,10 +1458,8 @@ impl UnifiedExecProcessManager { inject_apply_patch_env(&mut env); let active_permission_profile = prepared.turn_environment.active_permission_profile(); inject_permission_profile_env(&mut env, active_permission_profile.as_ref()); - let mut env = apply_unified_exec_env(env); - strip_output_env(&mut env); - let mut explicit_env_overrides = shell_environment_policy.r#set.clone(); - strip_output_env(&mut explicit_env_overrides); + let env = apply_unified_exec_env(env); + let explicit_env_overrides = shell_environment_policy.r#set.clone(); let exec_server_env_config = ExecServerEnvConfig { policy: exec_env_policy_from_shell_policy(shell_environment_policy), local_policy_env, 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 602894ff..2d7551c0 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -146,10 +146,6 @@ fn exec_env_policy_excludes_non_inheritable_and_runtime_variables() { "codex_apply_patch_preserve_line_endings".to_string(), "1".to_string(), ), - ( - "codex_plugin_metrics_output".to_string(), - "/stale/sidecar".to_string(), - ), ("KEEP".to_string(), "value".to_string()), ]), ..Default::default() @@ -164,7 +160,6 @@ fn exec_env_policy_excludes_non_inheritable_and_runtime_variables() { CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(), CODEX_VERSION_ENV_VAR.to_string(), codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(), - PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(), ], r#set: HashMap::from([("KEEP".to_string(), "value".to_string())]), include_only: Vec::new(), @@ -739,7 +734,6 @@ async fn pruning_does_not_evict_live_process_while_exited_process_is_finalizing( } else { Arc::clone(&live_process) }, - plugin_metrics_sidecar: None, call_id: format!("call-{process_id}"), process_id, cwd: cwd.clone(), diff --git a/codex-rs/core/src/util_tests.rs b/codex-rs/core/src/util_tests.rs index fdc75351..0540fac4 100644 --- a/codex-rs/core/src/util_tests.rs +++ b/codex-rs/core/src/util_tests.rs @@ -67,7 +67,7 @@ where } #[test] -fn emit_feedback_request_tags_records_sentry_feedback_fields() { +fn emit_feedback_request_tags_records_feedback_tag_fields() { let tags = Arc::new(Mutex::new(BTreeMap::new())); let event_count = Arc::new(Mutex::new(0)); let _guard = tracing_subscriber::registry() diff --git a/codex-rs/core/tests/common/Cargo.toml b/codex-rs/core/tests/common/Cargo.toml index 0837095d..15c63bc2 100644 --- a/codex-rs/core/tests/common/Cargo.toml +++ b/codex-rs/core/tests/common/Cargo.toml @@ -17,7 +17,6 @@ anyhow = { workspace = true } assert_cmd = { workspace = true } base64 = { workspace = true } codex-agent-graph-store = { workspace = true } -codex-analytics = { workspace = true } codex-arg0 = { workspace = true } codex-attachment-store = { workspace = true } codex-config = { workspace = true } diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index c3606244..6754c116 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -105,19 +105,6 @@ fn assert_turn_id(body: &Value, key: &str, expected: Option<&str>) -> Result<()> #[derive(Debug, Clone)] pub struct ResponsesRequest(wiremock::Request); -pub async fn received_analytics_events(server: &MockServer, event_type: &str) -> Vec { - server - .received_requests() - .await - .unwrap_or_default() - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .filter_map(|request| serde_json::from_slice::(&request.body).ok()) - .flat_map(|payload| payload["events"].as_array().cloned().unwrap_or_default()) - .filter(|event| event["event_type"] == event_type) - .collect() -} - pub async fn received_responses_requests(server: &MockServer) -> Vec { server .received_requests() diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index a20d6b55..fa2d135f 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -16,7 +16,6 @@ use anyhow::Context; use anyhow::Result; use anyhow::anyhow; use codex_agent_graph_store::AgentGraphStore; -use codex_analytics::AnalyticsEventsClient; use codex_attachment_store::AttachmentStore; use codex_config::CloudConfigBundleLoader; use codex_core::CodexThread; @@ -411,7 +410,6 @@ pub struct TestCodexBuilder { config_mutators: Vec>, thread_manager_configurer: Option ThreadManager + Send>>, auth: TestAuth, - analytics_events_client: Option, pre_build_hooks: Vec>, workspace_setups: Vec>, home: Option>, @@ -473,14 +471,6 @@ impl TestCodexBuilder { self } - pub fn with_analytics_events_client( - mut self, - analytics_events_client: AnalyticsEventsClient, - ) -> Self { - self.analytics_events_client = Some(analytics_events_client); - self - } - pub fn with_model_catalog_settings(mut self, settings: ModelCatalogSettings) -> Self { self.model_catalog_settings = Some(settings); self @@ -910,7 +900,6 @@ impl TestCodexBuilder { Arc::clone(&environment_manager), Arc::new(extensions.build()), user_instructions_provider, - self.analytics_events_client.clone(), Arc::clone(&self.image_store), Arc::clone(&thread_store), self.agent_graph_store.clone().or_else(|| { @@ -1579,7 +1568,6 @@ pub fn test_codex() -> TestCodexBuilder { .expect("test config should allow ShellSnapshot override"); })], auth: TestAuth::Cached(CodexAuth::from_api_key("dummy")), - analytics_events_client: None, pre_build_hooks: vec![], workspace_setups: vec![], home: None, diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 82a93700..81bf4c8e 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -500,11 +500,7 @@ async fn responses_stream_includes_turn_metadata_header_for_git_workspace_e2e() responses::ev_completed("resp-1"), ]); - let test = test_codex() - .with_config(|config| config.analytics_enabled = Some(true)) - .build(&server) - .await - .expect("build test codex"); + let test = test_codex().build(&server).await.expect("build test codex"); let cwd = test.cwd_path(); let first_request = responses::mount_sse_once(&server, response_body.clone()).await; @@ -554,10 +550,11 @@ async fn responses_stream_includes_turn_metadata_header_for_git_workspace_e2e() .expect("body x-codex-turn-metadata should be valid JSON"); assert_eq!( ( - initial_parsed["analytics_enabled"].as_bool(), - body_metadata["analytics_enabled"].as_bool(), + initial_parsed.get("analytics_enabled"), + body_metadata.get("analytics_enabled"), ), - (Some(true), Some(true)), + (None, None), + "usage-data collection state must never be reported", ); assert_eq!( body_metadata diff --git a/codex-rs/core/tests/suite/agent_execution.rs b/codex-rs/core/tests/suite/agent_execution.rs index 4c88ebf6..cfb061c8 100644 --- a/codex-rs/core/tests/suite/agent_execution.rs +++ b/codex-rs/core/tests/suite/agent_execution.rs @@ -240,12 +240,6 @@ async fn child_turn_start_preserves_root_attribution() -> Result<()> { let test = test_codex() .with_model("gpt-5.6-sol") .with_config(|config| { - config.otel.log_agent_responses = true; - config.otel.exporter = codex_config::types::OtelExporterKind::OtlpGrpc { - endpoint: "http://127.0.0.1:1".into(), - headers: Default::default(), - tls: None, - }; config.features.enable(Feature::Collab).unwrap(); config.features.enable(Feature::MultiAgentV2).unwrap(); }) @@ -288,40 +282,6 @@ async fn child_turn_start_preserves_root_attribution() -> Result<()> { .iter() .all(|(_, event)| { event.root_turn_id.as_ref() == Some(root_turn_id) }) ); - logs_assert(|lines: &[&str]| { - let logs: Vec<_> = lines - .iter() - .filter(|line| line.contains("codex.agent_response")) - .collect(); - assert_eq!(logs.len(), 2); - for (id, turn) in &starts { - let line = logs - .iter() - .find(|line| line.contains(&format!(" conversation.id={id}"))) - .expect("response log"); - let (agent, item, text) = if *id == test.session_configured.thread_id { - ("main", "msg-first-call", "collaboration completed") - } else { - assert!(line.contains(&format!( - " parent.conversation.id=\"{}\"", - test.session_configured.thread_id - ))); - assert!(line.contains(&format!(" parent.turn.id={root_turn_id:?}"))); - assert!(line.contains(" initiating.agent.path=\"/root\"")); - ("subagent", "msg-worker-first-call", "worker completed") - }; - for field in [ - format!(" agent.type={agent:?}"), - format!(" turn.id={:?}", turn.turn_id), - format!(" root.turn.id={root_turn_id:?}"), - format!(" item.id={item:?}"), - format!(" response={text:?}"), - ] { - assert!(line.contains(&field), "missing {field}: {line}"); - } - } - Ok(()) - }); Ok(()) } diff --git a/codex-rs/core/tests/suite/agent_websocket.rs b/codex-rs/core/tests/suite/agent_websocket.rs index 57ec3455..affbd4a5 100644 --- a/codex-rs/core/tests/suite/agent_websocket.rs +++ b/codex-rs/core/tests/suite/agent_websocket.rs @@ -611,7 +611,6 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create( .with_model("gpt-5.2") .with_config(move |config| { config.update_plan_enabled = update_plan_enabled; - config.analytics_enabled = Some(false); if incremental_tools { config .features @@ -663,7 +662,7 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create( .expect("warmup turn metadata"), )?; assert_eq!(warmup_metadata["request_kind"].as_str(), Some("prewarm")); - assert_eq!(warmup_metadata["analytics_enabled"].as_bool(), Some(false)); + assert!(warmup_metadata.get("analytics_enabled").is_none()); assert_eq!( warmup_metadata["window_id"].as_str(), warmup["client_metadata"]["x-codex-window-id"].as_str() @@ -682,7 +681,7 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create( .expect("turn metadata"), )?; assert_eq!(turn_metadata["request_kind"].as_str(), Some("turn")); - assert_eq!(turn_metadata["analytics_enabled"].as_bool(), Some(false)); + assert!(turn_metadata.get("analytics_enabled").is_none()); assert_eq!(warmup_metadata["window_number"].as_u64(), Some(0)); assert_eq!( warmup_metadata["window_number"], diff --git a/codex-rs/core/tests/suite/app_tool_exposure.rs b/codex-rs/core/tests/suite/app_tool_exposure.rs index ec86d8ad..e90fb691 100644 --- a/codex-rs/core/tests/suite/app_tool_exposure.rs +++ b/codex-rs/core/tests/suite/app_tool_exposure.rs @@ -1,7 +1,6 @@ //! Verifies connector-scoped exposure, server restrictions, and MCP dispatch. use codex_core::config::Config; -use core_test_support::apps_test_server::mock_apps_mcp_server_config; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::McpServerContribution; @@ -11,6 +10,7 @@ use codex_features::Feature; use codex_protocol::config_types::ToolExposureSurface; use codex_protocol::openai_models::ToolMode; use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::apps_test_server::mock_apps_mcp_server_config; use core_test_support::apps_test_server::search_capable_apps_builder; use core_test_support::responses; use pretty_assertions::assert_eq; @@ -189,7 +189,6 @@ pub(super) async fn connector_exposure_requests( if case.direct_only { config.code_mode.direct_only_tool_namespaces = vec![namespace.to_string()]; } - config.analytics_enabled = Some(false); config .features .enable(Feature::CodeModeHost) diff --git a/codex-rs/core/tests/suite/app_tool_exposure_strict_tests.rs b/codex-rs/core/tests/suite/app_tool_exposure_strict_tests.rs index 894695ff..72739b48 100644 --- a/codex-rs/core/tests/suite/app_tool_exposure_strict_tests.rs +++ b/codex-rs/core/tests/suite/app_tool_exposure_strict_tests.rs @@ -67,7 +67,6 @@ enabled = false .features .enable(Feature::CodeModeOnlyStrictThirdPartyTools) .expect("strict third-party tools"); - config.analytics_enabled = Some(false); }); let test = builder.build_with_auto_env(&server).await?; test.submit_turn("Look up my calendar.").await?; diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 74205193..b1ca5249 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -2090,7 +2090,6 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), empty_extension_registry(), Arc::new(codex_core::test_support::EmptyUserInstructionsProvider), - /*analytics_events_client*/ None, codex_core::passthrough_image_store(), ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(), /*agent_graph_store*/ None, diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 6b073c74..02b49e73 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -11,7 +11,6 @@ use anyhow::Context; use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use codex_analytics::AnalyticsEventsClient; use codex_config::types::McpServerConfig; use codex_config::types::McpServerTransportConfig; use codex_core::StartThreadOptions; @@ -38,7 +37,6 @@ use codex_http_client::DestinationPolicy; use codex_http_client::NetworkPolicyController; use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; -use core_test_support::apps_test_server::mock_apps_mcp_server_config; use codex_models_manager::bundled_models_response; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::CollaborationMode; @@ -82,6 +80,7 @@ use codex_web_search_extension::install as install_web_search_extension; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::apps_test_server::AppsTestToolLoading; use core_test_support::apps_test_server::DIRECT_CALENDAR_APP_ONLY_TOOL; +use core_test_support::apps_test_server::mock_apps_mcp_server_config; use core_test_support::apps_test_server::recorded_apps_tool_calls; use core_test_support::apps_test_server::search_capable_apps_builder; use core_test_support::assert_regex_match; @@ -2191,399 +2190,18 @@ fn assert_result_metadata_call( assert!(metadata.get("tool_result_metadata").is_none()); } -enum ResultMetadataAnalytics { - Config(Option), - HostDisabled(Option), -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn direct_result_metadata_retained_budget_preserves_resource_access() -> Result<()> { - skip_if_no_network!(Ok(())); - let server = responses::start_mock_server().await; - let arguments = serde_json::json!({ "search": "retained-budget" }); - let resource_access = serde_json::json!({ - "schema_version": 1, - "resource_coverage": "complete", - "resources": [], - }); - let resource_only = serde_json::json!({ "openai/resource_access": resource_access }); - let result_metadata = serde_json::json!({ - "payload": "x".repeat(31 * 1024), - "openai/resource_access": resource_access, - }); - let metadata_bytes = serde_json::to_vec(&result_metadata)?.len(); - assert!(metadata_bytes * 32 < 1024 * 1024); - assert!(metadata_bytes * 33 > 1024 * 1024); - let apps_server = mount_result_metadata_app( - &server, - Some(result_metadata.clone()), - /*is_error*/ false, - ) - .await?; - let mut builder = - result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config( - |config| { - config.features.disable(Feature::CodeModeOnly).unwrap(); - config.features.disable(Feature::CodeMode).unwrap(); - }, - ); - let test = builder.build_with_auto_env(&server).await?; - let call_ids = (0..33) - .map(|index| format!("call-{index}")) - .collect::>(); - let mut events = call_ids[..32] - .iter() - .map(|call_id| { - responses::ev_function_call_with_namespace( - call_id, - "mcp__codex_apps__messagesearch", - RESULT_METADATA_TOOL, - &arguments.to_string(), - ) - }) - .collect::>(); - events.push(ev_completed("resp-1")); - let initial = responses::mount_sse_once(&server, sse(events)).await; - // Cross the retained-history limit after the first batch has finished, regardless of order. - let overflow = responses::mount_sse_once( - &server, - sse(vec![ - responses::ev_function_call_with_namespace( - &call_ids[32], - "mcp__codex_apps__messagesearch", - RESULT_METADATA_TOOL, - &arguments.to_string(), - ), - ev_completed("resp-2"), - ]), - ) - .await; - let completion = responses::mount_sse_once(&server, sse(vec![ev_completed("resp-3")])).await; - test.submit_turn("Search the connected app 33 times") - .await?; - let initial = initial.single_request(); - assert!(initial.has_message_with_input_texts("user", |texts| { - texts == ["Search the connected app 33 times"] - })); - assert!( - !tool_names(&initial.body_json()) - .iter() - .any(|name| name == "exec") - ); - for (request, expected_calls) in [ - (overflow.single_request(), &call_ids[..32]), - (completion.single_request(), &call_ids[..]), - ] { - for call_id in expected_calls { - let output = request.function_call_output(call_id); - assert_eq!( - &output["output"].as_array().expect("direct output content")[1..], - &[serde_json::json!({ - "type": "input_text", - "text": RESULT_METADATA_PRIVATE_RESULT, - })], - ); - } - } - let calls = recorded_apps_tool_calls(&server).await; - assert_eq!(calls.len(), call_ids.len()); - for call in calls { - assert_eq!(call["params"]["name"], RESULT_METADATA_TOOL); - assert_eq!(call["params"]["arguments"], arguments); - } - // Inspect retained history directly to isolate the Direct admission budget. - let history = test.codex.conversation_history_snapshot().await; - assert!( - history - .items() - .map(codex_protocol::models::executed_tool_call_metadata_bytes) - .sum::() - <= 1024 * 1024 - ); - let outputs = history - .items() - .filter(|item| matches!(item, ResponseItem::FunctionCallOutput { .. })) - .collect::>(); - assert_eq!(outputs.len(), call_ids.len()); - for (index, call_id) in call_ids.iter().enumerate() { - let item = outputs - .iter() - .find(|item| matches!(item, ResponseItem::FunctionCallOutput { call_id: Some(id), .. } if id == call_id)) - .expect("retained Direct output"); - if let ResponseItem::FunctionCallOutput { output, .. } = item { - assert_eq!(output.success, Some(true)); - } - let output = serde_json::to_value(item)?; - let metadata = &output["internal_chat_message_metadata_passthrough"]; - assert_eq!(metadata["tool_calls_complete"], true); - let calls = metadata["executed_tool_calls"].as_array().unwrap(); - assert_eq!(calls.len(), 1); - assert!( - calls[0]["name"] - .as_str() - .unwrap() - .ends_with(RESULT_METADATA_TOOL) - ); - assert_eq!(calls[0]["arguments"], arguments); - assert_eq!( - calls[0]["tool_result_metadata"], - if index < 32 { - &result_metadata - } else { - &resource_only - } - .clone(), - ); - } - test.codex.shutdown_and_wait().await?; - Ok(()) -} - -#[test_case(ToolMode::Direct; "direct")] -#[test_case(ToolMode::CodeModeOnly; "code_mode")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn result_metadata_preserves_results_within_request_budget( - tool_mode: ToolMode, -) -> Result<()> { - skip_if_no_network!(Ok(())); - let server = responses::start_mock_server().await; - let arguments = [ - serde_json::json!({ "search": "large" }), - serde_json::json!({ "search": "medium-1" }), - serde_json::json!({ "search": "medium-2" }), - serde_json::json!({ "search": "medium-3" }), - serde_json::json!({ "search": "medium-4" }), - serde_json::json!({ "search": "medium-5" }), - serde_json::json!({ "search": "oversized" }), - serde_json::json!({ "search": "small" }), - ]; - let resource_access = serde_json::json!({ - "schema_version": 1, - "resource_coverage": "complete", - "resources": [], - }); - let result_metadata = [ - serde_json::json!({ - "payload": "l".repeat(31 * 1024), - "openai/resource_access": resource_access, - }), - serde_json::json!({ "payload": "m".repeat(450 * 1024) }), - serde_json::json!({ "payload": "m".repeat(450 * 1024) }), - serde_json::json!({ "payload": "m".repeat(450 * 1024) }), - serde_json::json!({ "payload": "m".repeat(450 * 1024) }), - serde_json::json!({ "payload": "m".repeat(450 * 1024) }), - serde_json::json!({ - "payload": "o".repeat(40 * 1024), - "openai/resource_access": { - "schema_version": 1, - "resource_coverage": "complete", - "resources": ["r".repeat(40 * 1024)], - }, - }), - serde_json::json!({ "status": "ok" }), - ]; - let metadata_sizes = result_metadata - .iter() - .map(|metadata| serde_json::to_vec(metadata).unwrap().len()) - .collect::>(); - assert!(metadata_sizes.iter().sum::() > 2 * 1024 * 1024); - assert!(metadata_sizes.iter().sum::() < 15 * 1024 * 1024); - assert!(serde_json::to_vec(&result_metadata[6]["openai/resource_access"])?.len() > 32 * 1024); - for (arguments, metadata) in arguments.iter().zip(&result_metadata) { - let result = serde_json::json!({ - "content": [{ "type": "text", "text": RESULT_METADATA_PRIVATE_RESULT }], - "isError": false, - "_meta": metadata, - }); - Mock::given(method("POST")) - .and(path("/api/codex/ps/mcp")) - .and(body_partial_json(serde_json::json!({ - "method": "tools/call", - "params": { "arguments": arguments }, - }))) - .respond_with(move |request: &Request| { - let request: Value = serde_json::from_slice(&request.body).unwrap(); - ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "jsonrpc": "2.0", - "id": request["id"], - "result": result, - })) - }) - .with_priority(/*p*/ 1) - .mount(&server) - .await; - } - // Exact argument matches take precedence over the shared fallback mounted afterward. - let apps_server = mount_result_metadata_app( - &server, /*result_metadata*/ None, /*is_error*/ false, - ) - .await?; - let direct = tool_mode == ToolMode::Direct; - let mut builder = - result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config( - move |config| { - if direct { - config.features.disable(Feature::CodeModeOnly).unwrap(); - config.features.disable(Feature::CodeMode).unwrap(); - } - }, - ); - let test = builder.build_with_auto_env(&server).await?; - let call_ids = [ - "call-1", "call-2", "call-3", "call-4", "call-5", "call-6", "call-7", "call-8", - ]; - let mut events = if direct { - arguments - .iter() - .zip(call_ids) - .map(|(arguments, call_id)| { - responses::ev_function_call_with_namespace( - call_id, - "mcp__codex_apps__messagesearch", - RESULT_METADATA_TOOL, - &arguments.to_string(), - ) - }) - .collect::>() - } else { - let arguments = serde_json::to_string(&arguments)?; - let code = format!( - "const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \ - const results = []; \ - for (const args of {arguments}) {{ \ - const result = await tools[tool.name](args); \ - results.push({{ content: result.content, isError: Boolean(result.isError), \ - hasMeta: Object.hasOwn(result, \"_meta\") }}); \ - }} \ - text(JSON.stringify(results));" - ); - vec![ev_custom_tool_call("call-1", "exec", &code)] - }; - events.push(ev_completed("resp-1")); - let initial = responses::mount_sse_once(&server, sse(events)).await; - let follow_up = responses::mount_sse_once(&server, sse(vec![ev_completed("resp-2")])).await; - test.submit_turn("Search the connected app eight times") - .await?; - let initial = initial.single_request(); - assert!(initial.has_message_with_input_texts("user", |texts| { - texts == ["Search the connected app eight times"] - })); - assert_eq!( - tool_names(&initial.body_json()) - .iter() - .any(|name| name == "exec"), - !direct, - ); - let request = follow_up.single_request(); - let mut actual_arguments = recorded_apps_tool_calls(&server) - .await - .into_iter() - .map(|call| { - assert_eq!(call["params"]["name"], RESULT_METADATA_TOOL); - call["params"]["arguments"].clone() - }) - .collect::>(); - actual_arguments.sort_by_key(Value::to_string); - assert_eq!(actual_arguments, arguments); - if direct { - for call_id in call_ids { - let output = request.function_call_output(call_id); - assert_eq!( - &output["output"].as_array().expect("direct output content")[1..], - &[serde_json::json!({ - "type": "input_text", - "text": RESULT_METADATA_PRIVATE_RESULT, - })], - ); - assert!(!output["output"].to_string().contains("payload")); - } - } else { - let (body, success) = custom_tool_output_body_and_success(&request, "call-1"); - assert_ne!(success, Some(false), "Code Mode failed: {body}"); - assert_eq!( - serde_json::from_str::(&body)?, - serde_json::json!(vec![ - serde_json::json!({ - "content": [{ "type": "text", "text": RESULT_METADATA_PRIVATE_RESULT }], - "isError": false, - "hasMeta": false, - }); - arguments.len() - ]), - ); - } - let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await; - if direct { - for item in &captured { - if let ResponseItem::FunctionCallOutput { output, .. } = item { - assert_eq!(output.success, Some(true)); - } - } - } - assert!( - captured - .iter() - .map(codex_protocol::models::executed_tool_call_metadata_bytes) - .sum::() - > 2 * 1024 * 1024 - ); - let captured = serde_json::to_value(captured)?; - for (input, expected_metadata) in [ - // Ungranted custom inference endpoints strip raw metadata, including omission markers. - (request.input(), None), - ( - captured.as_array().unwrap().clone(), - Some(result_metadata.clone()), - ), - ] { - let mut calls = Vec::new(); - for output in &input { - let metadata = &output["internal_chat_message_metadata_passthrough"]; - if let Some(recorded) = metadata["executed_tool_calls"].as_array() { - assert_eq!(metadata["tool_calls_complete"], true); - calls.extend(recorded.iter().cloned()); - } - } - assert_eq!(calls.len(), arguments.len()); - let expected_calls = arguments - .iter() - .enumerate() - .map(|(index, arguments)| { - let name = calls[index]["name"].as_str().unwrap(); - assert!(name.ends_with(RESULT_METADATA_TOOL)); - let mut call = serde_json::json!({ "name": name, "arguments": arguments }); - if let Some(metadata) = &expected_metadata { - call["tool_result_metadata"] = metadata[index].clone(); - } - call - }) - .collect::>(); - assert_eq!(calls, expected_calls); - } - test.codex.shutdown_and_wait().await?; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "copies_full_metadata_without_rules")] -#[test_case(true, true, true, true, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "accepted_error_keeps_metadata")] -#[test_case(true, true, false, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "missing_metadata_stays_absent")] -#[test_case(false, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "feature_off_does_not_record")] -#[test_case(true, false, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "extension_owned_apps_do_not_record")] -#[test_case(true, true, true, false, "employee@openai.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "employee_keeps_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_keeps_metadata")] -#[test_case(true, true, true, true, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_accepted_error_keeps_metadata")] -#[test_case(true, true, false, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_missing_metadata_stays_absent")] -#[test_case(false, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_feature_off_does_not_record")] -#[test_case(true, false, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_extension_owned_apps_do_not_record")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(Some(true)); "analytics_enabled_keeps_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(Some(false)); "analytics_disabled_omits_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(Some(true)); "direct_analytics_enabled_keeps_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(Some(false)); "direct_analytics_disabled_omits_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::HostDisabled(None); "host_analytics_disabled_with_config_unset_omits_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::HostDisabled(Some(true)); "host_analytics_disabled_with_config_enabled_omits_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::HostDisabled(None); "direct_host_analytics_disabled_with_config_unset_omits_metadata")] -#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::HostDisabled(Some(true)); "direct_host_analytics_disabled_with_config_enabled_omits_metadata")] +#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly; "copies_full_metadata_without_rules")] +#[test_case(true, true, true, true, "user@example.com", ToolMode::CodeModeOnly; "accepted_error_keeps_metadata")] +#[test_case(true, true, false, false, "user@example.com", ToolMode::CodeModeOnly; "missing_metadata_stays_absent")] +#[test_case(false, true, true, false, "user@example.com", ToolMode::CodeModeOnly; "feature_off_does_not_record")] +#[test_case(true, false, true, false, "user@example.com", ToolMode::CodeModeOnly; "extension_owned_apps_do_not_record")] +#[test_case(true, true, true, false, "employee@openai.com", ToolMode::CodeModeOnly; "employee_keeps_metadata")] +#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct; "direct_keeps_metadata")] +#[test_case(true, true, true, true, "user@example.com", ToolMode::Direct; "direct_accepted_error_keeps_metadata")] +#[test_case(true, true, false, false, "user@example.com", ToolMode::Direct; "direct_missing_metadata_stays_absent")] +#[test_case(false, true, true, false, "user@example.com", ToolMode::Direct; "direct_feature_off_does_not_record")] +#[test_case(true, false, true, false, "user@example.com", ToolMode::Direct; "direct_extension_owned_apps_do_not_record")] async fn result_metadata_follows_call_binding( metadata_enabled: bool, host_owned: bool, @@ -2591,14 +2209,8 @@ async fn result_metadata_follows_call_binding( is_error: bool, account_email: &str, tool_mode: ToolMode, - analytics: ResultMetadataAnalytics, ) -> Result<()> { skip_if_no_network!(Ok(())); - let (analytics_enabled, host_disables_analytics) = match analytics { - ResultMetadataAnalytics::Config(enabled) => (enabled, false), - ResultMetadataAnalytics::HostDisabled(enabled) => (enabled, true), - }; - let effective_analytics_enabled = analytics_enabled != Some(false) && !host_disables_analytics; let direct = matches!(tool_mode, ToolMode::Direct); let server = responses::start_mock_server().await; let result_metadata = has_metadata.then(|| { @@ -2619,7 +2231,6 @@ async fn result_metadata_follows_call_binding( let mut builder = result_metadata_apps_builder(apps_server.chatgpt_base_url.clone(), account_email) .with_config(move |config| { - config.analytics_enabled = analytics_enabled; if direct { config.features.disable(Feature::CodeModeOnly).unwrap(); config.features.disable(Feature::CodeMode).unwrap(); @@ -2631,9 +2242,6 @@ async fn result_metadata_follows_call_binding( .unwrap(); } }); - if host_disables_analytics { - builder = builder.with_analytics_events_client(AnalyticsEventsClient::disabled()); - } if !host_owned { let mut extensions = ExtensionRegistryBuilder::::new(); extensions.mcp_server_contributor(Arc::new(ResultMetadataTestControl { @@ -2672,7 +2280,6 @@ async fn result_metadata_follows_call_binding( ); run_code_mode_turn_with_builder(&server, "Search a connected app", &code, builder).await? }; - assert_eq!(test.codex.analytics_enabled(), effective_analytics_enabled); let request = follow_up.single_request(); assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1); let output = if direct { @@ -2728,10 +2335,8 @@ async fn result_metadata_follows_call_binding( .iter() .find(|item| item["type"] == output["type"] && item["call_id"] == "call-1") .expect("captured tool output"); - let expected_metadata = (host_owned && effective_analytics_enabled) - .then_some(result_metadata) - .flatten(); - assert_result_metadata_call(captured_output, &arguments, expected_metadata); + // Raw MCP result metadata is never captured: usage-data reporting was removed. + assert_result_metadata_call(captured_output, &arguments, /*expected_metadata*/ None); assert_eq!( output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"], true @@ -2746,261 +2351,6 @@ async fn result_metadata_follows_call_binding( Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn code_mode_result_metadata_follows_runtime_recording_enablement() -> Result<()> { - skip_if_no_network!(Ok(())); - let server = responses::start_mock_server().await; - let result_metadata = serde_json::json!({ "provider": { "id": "refresh" } }); - let apps_server = mount_result_metadata_app( - &server, - Some(result_metadata.clone()), - /*is_error*/ false, - ) - .await?; - let mut builder = - result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config( - |config| { - config - .features - .disable(Feature::ExecutedToolCallMetadata) - .unwrap(); - }, - ); - let test = builder.build_with_auto_env(&server).await?; - let arguments = serde_json::json!({ "search": "launch plan" }); - let code = format!( - "const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \ - const result = await tools[tool.name]({arguments}); \ - text(JSON.stringify({{ isError: Boolean(result.isError), hasMeta: Object.hasOwn(result, \"_meta\") }}));" - ); - for (call_id, enabled) in [("call-off", false), ("call-on", true)] { - if enabled { - let current_config = test.codex.config().await; - let mut config = test.config.clone(); - config - .features - .enable(Feature::ExecutedToolCallMetadata) - .unwrap(); - let _ = test - .codex - .refresh_runtime_config(current_config, config) - .await; - // Runtime recording changes without updating the session's execution features. - assert!( - !test - .codex - .config() - .await - .features - .enabled(Feature::ExecutedToolCallMetadata) - ); - } - let initial = responses::mount_sse_once( - &server, - sse(vec![ - ev_custom_tool_call(call_id, "exec", &code), - ev_completed(call_id), - ]), - ) - .await; - let follow_up = responses::mount_sse_once( - &server, - sse(vec![ - ev_assistant_message(&format!("{call_id}-message"), "done"), - ev_completed(&format!("{call_id}-done")), - ]), - ) - .await; - test.submit_turn("Search a connected app").await?; - initial.single_request(); - let request = follow_up.single_request(); - let (body, success) = custom_tool_output_body_and_success(&request, call_id); - assert_ne!(success, Some(false), "Code Mode failed: {body}"); - assert_eq!( - serde_json::from_str::(&body)?, - serde_json::json!({ "isError": false, "hasMeta": false }), - ); - assert_eq!( - result_metadata_fixture_calls(&request.input()).count(), - usize::from(enabled) - ); - let output = request.custom_tool_call_output(call_id); - assert!( - output["internal_chat_message_metadata_passthrough"] - .get("tool_calls_complete") - .is_none() - ); - if enabled { - assert_result_metadata_call(&output, &arguments, /*expected_metadata*/ None); - } - } - assert_eq!(recorded_apps_tool_calls(&server).await.len(), 2); - let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await; - let captured = serde_json::to_value(captured)?; - let captured_output = captured - .as_array() - .unwrap() - .iter() - .find(|item| item["type"] == "custom_tool_call_output" && item["call_id"] == "call-on") - .expect("captured exec output after runtime enablement"); - let expected_metadata = Some(result_metadata); - assert_result_metadata_call(captured_output, &arguments, expected_metadata); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn code_mode_result_metadata_keeps_prepared_call_binding_across_runtime_refresh() -> Result<()> -{ - skip_if_no_network!(Ok(())); - let server = responses::start_mock_server().await; - let original_metadata = - serde_json::json!({ "provider": { "origin": "original", "items": [] } }); - let apps_server = mount_result_metadata_app( - &server, - Some(original_metadata.clone()), - /*is_error*/ false, - ) - .await?; - let refreshed_server = responses::start_mock_server().await; - let refreshed_apps = mount_result_metadata_app( - &refreshed_server, - Some(serde_json::json!({ "provider": { "origin": "refreshed" } })), - /*is_error*/ false, - ) - .await?; - let (reached_tx, reached_rx) = oneshot::channel(); - let (release_tx, release_rx) = oneshot::channel(); - let control = Arc::new(ResultMetadataTestControl { - server: Mutex::new(McpServerContribution::HostedApps { - config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)), - protocol_mode: None, - }), - gate: Mutex::new(Some((reached_tx, release_rx))), - }); - let mut extensions = ExtensionRegistryBuilder::::new(); - extensions.mcp_server_contributor(control.clone()); - extensions.tool_lifecycle_contributor(control.clone()); - let builder = result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com") - .with_extensions(Arc::new(extensions.build())); - let arguments = serde_json::json!({ - "query": "launch plan", - "response_format": "detailed", - "content_types": "messages", - }); - let code = format!( - "const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \ - const pending = tools[tool.name]({arguments}); yield_control(); await pending; \ - await tools[tool.name]({arguments}); text(\"done\");" - ); - let (test, follow_up) = - run_code_mode_turn_with_builder(&server, "Search a connected app", &code, builder).await?; - let first_items = custom_tool_output_items(&follow_up.single_request(), "call-1"); - assert!( - text_item(&first_items, /*index*/ 0).starts_with("Script running with cell ID "), - "expected the held call to yield: {first_items:?}", - ); - let cell_id = extract_running_cell_id(text_item(&first_items, /*index*/ 0)); - tokio::time::timeout(Duration::from_secs(10), reached_rx).await??; - - // Yield may precede call admission. Drain inventory after the lifecycle gate is reached; - // the short wait is only a poll budget while the gate keeps acceptance blocked. - let held_wait = responses::mount_function_call_agent_response( - &server, - "call-2", - &serde_json::to_string(&serde_json::json!({ - "cell_id": cell_id, - "yield_time_ms": 1, - }))?, - "wait", - ) - .await; - test.submit_turn("Read the pending call inventory").await?; - let held_request = held_wait.completion.single_request(); - let held_items = function_tool_output_items(&held_request, "call-2"); - assert_eq!( - extract_running_cell_id(text_item(&held_items, /*index*/ 0)), - cell_id - ); - let held_input = held_request.input(); - let emitted_calls = result_metadata_fixture_calls(&held_input).collect::>(); - assert_eq!( - emitted_calls.len(), - 1, - "held wait must not duplicate inventory" - ); - let original_output = emitted_calls[0]; - assert_result_metadata_call(original_output, &arguments, /*expected_metadata*/ None); - assert_ne!( - original_output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"], - true - ); - // The next call uses an extension-owned binding, but the held call keeps its host proof. - *control.server.lock().unwrap() = McpServerContribution::Set { - name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - config: Box::new(mock_apps_mcp_server_config(&refreshed_apps.chatgpt_base_url)), - }; - let current_config = test.codex.config().await; - let _ = test - .codex - .refresh_runtime_config(current_config, test.config.clone()) - .await; - release_tx.send(()).unwrap(); - let wait = responses::mount_function_call_agent_response( - &server, - "call-3", - &serde_json::to_string(&serde_json::json!({ - "cell_id": cell_id, - "yield_time_ms": 10_000, - }))?, - "wait", - ) - .await; - test.submit_turn("Wait for the accepted app result").await?; - let request = wait.completion.single_request(); - assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1); - assert_eq!(recorded_apps_tool_calls(&refreshed_server).await.len(), 1); - assert!( - !request - .body_json() - .to_string() - .contains(RESULT_METADATA_PRIVATE_RESULT) - ); - let input = request.input(); - assert_eq!( - result_metadata_fixture_calls(&input).count(), - 2, - "late results must not duplicate the call" - ); - let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await; - let captured = serde_json::to_value(captured)?; - // A's accepted result must update the output that first reported it, not the final wait. - let expected_metadata = Some(original_metadata); - for (call_id, call_type, expected_metadata) in [ - ( - original_output["call_id"].as_str().unwrap(), - original_output["type"].as_str().unwrap(), - expected_metadata, - ), - ("call-3", "function_call_output", None), - ] { - let output = request.call_output(call_id, call_type); - assert_result_metadata_call(&output, &arguments, /*expected_metadata*/ None); - let captured_output = captured - .as_array() - .unwrap() - .iter() - .find(|item| item["type"] == call_type && item["call_id"] == call_id) - .expect("captured tool output"); - assert_result_metadata_call(captured_output, &arguments, expected_metadata); - } - let terminal_output = request.function_call_output("call-3"); - assert_eq!( - terminal_output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"], - true - ); - Ok(()) -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn code_mode_late_result_metadata_with_large_arguments_survives_waits() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/direct_tool_metadata.rs b/codex-rs/core/tests/suite/direct_tool_metadata.rs index 8656e538..98825d44 100644 --- a/codex-rs/core/tests/suite/direct_tool_metadata.rs +++ b/codex-rs/core/tests/suite/direct_tool_metadata.rs @@ -1,27 +1,10 @@ //! Direct-call metadata coverage, including malformed calls and metadata budgets. use anyhow::Result; -use codex_core::ForkSnapshot; -use codex_core::StartThreadOptions; use codex_core::TurnInputRequest; use codex_core::TurnStartOptions; use codex_features::Feature; -use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_model_provider::RemoteCompactionSupport; -use core_test_support::apps_test_server::AppsTestServer; -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_calls; -use core_test_support::apps_test_server::search_capable_apps_builder; -use core_test_support::responses::ev_function_call_with_namespace; -use core_test_support::wait_for_mcp_server; -use wiremock::Mock; -use wiremock::Request; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_partial_json; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::path_regex; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; @@ -653,346 +636,3 @@ async fn direct_function_and_tool_search_mark_complete_attempts( } Ok(()) } - -#[test_case(false, false; "ungranted_provider")] -#[test_case(true, false; "granted_provider_cold_fork")] -#[test_case(true, true; "granted_provider_warm_fork")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn direct_metadata_limit_respects_provider_support( - include_internal_metadata: bool, - fork_from_running_thread: bool, -) -> Result<()> { - skip_if_no_network!(Ok(())); - let server = start_mock_server().await; - let apps = AppsTestServer::mount(&server).await?; - fn metadata_for_query(query: &str) -> Value { - json!({"openai/resource_access": {"payload": "x".repeat(600 * 1024), "query": query}}) - } - let raw_bytes = serde_json::to_vec(&metadata_for_query("first"))?.len(); - assert!(raw_bytes < 1024 * 1024); - assert!(raw_bytes * 2 > 1024 * 1024); - Mock::given(method("POST")) - .and(path_regex("^/api/codex/ps/mcp/?$")) - .and(body_partial_json(json!({"method": "tools/call"}))) - .respond_with(move |request: &Request| { - let body: Value = serde_json::from_slice(&request.body).expect("MCP request"); - let query = body["params"]["arguments"]["query"] - .as_str() - .expect("query"); - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "jsonrpc": "2.0", "id": body["id"], - "result": { - "content": [{"type": "text", "text": format!("result for {query}")}], - "_meta": metadata_for_query(query), - "isError": false - } - })) - }) - .with_priority(/*p*/ 1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(/*s*/ 200)) - .mount(&server) - .await; - let mut events = vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_function_call_with_namespace( - "first", - SEARCH_CALENDAR_NAMESPACE, - SEARCH_CALENDAR_LIST_TOOL, - r#"{"query":"first"}"#, - ), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_response_created("resp-2"), - ev_function_call_with_namespace( - "second", - SEARCH_CALENDAR_NAMESPACE, - SEARCH_CALENDAR_LIST_TOOL, - r#"{"query":"second"}"#, - ), - ev_completed("resp-2"), - ]), - sse(vec![ev_response_created("resp-3"), ev_completed("resp-3")]), - ]; - if include_internal_metadata { - for query in ["fork", "resume"] { - events.push(sse(vec![ - ev_response_created(&format!("resp-{query}")), - ev_function_call_with_namespace( - query, - SEARCH_CALENDAR_NAMESPACE, - SEARCH_CALENDAR_LIST_TOOL, - &json!({"query": query}).to_string(), - ), - ev_completed(&format!("resp-{query}")), - ])); - events.push(sse(vec![ - ev_response_created(&format!("resp-{query}-done")), - ev_completed(&format!("resp-{query}-done")), - ])); - } - } - let responses = mount_sse_sequence(&server, events).await; - let mock_url = server.uri(); - let configure_metadata = move |config: &mut codex_core::config::Config| { - assert_eq!(config.chatgpt_base_url, mock_url); - assert_eq!( - config.model_provider.base_url.as_deref(), - Some(format!("{mock_url}/v1").as_str()) - ); - config.model_provider.include_internal_metadata = include_internal_metadata; - config.analytics_enabled = Some(true); - config - .features - .enable(Feature::ExecutedToolCallMetadata) - .expect("enable executed tool call metadata"); - config - .features - .disable(Feature::CodeMode) - .expect("disable code mode"); - config - .features - .disable(Feature::CodeModeOnly) - .expect("disable code-mode-only tools"); - }; - let mut builder = search_capable_apps_builder(apps.chatgpt_base_url.clone()) - .with_config(configure_metadata.clone()); - // build() always selects the local test environment; all network destinations are the mock. - let test = builder.build(&server).await?; - assert!(test.codex.analytics_enabled()); - wait_for_mcp_server(&test.codex, CODEX_APPS_MCP_SERVER_NAME).await?; - test.submit_turn_with_approval_and_permission_profile( - "Use [$calendar](app://calendar) to list events twice.", - AskForApproval::OnRequest, - PermissionProfile::read_only(), - ) - .await?; - - let calls = recorded_apps_tool_calls(&server).await; - assert_eq!(calls.len(), 2); - for (call, query) in calls.iter().zip(["first", "second"]) { - assert_eq!(call["params"]["name"], "calendar_list_events"); - assert_eq!(call["params"]["arguments"], json!({"query": query})); - } - let requests = responses.requests(); - assert_eq!(requests.len(), 3); - let first_output = requests[2].function_call_output("first"); - let second_output = requests[2].function_call_output("second"); - let history = test.codex.conversation_history_snapshot().await; - let history = serde_json::to_value(history.items().collect::>())?; - let recorded_outputs = [&first_output, &second_output].map(|output| { - history - .as_array() - .expect("history items") - .iter() - .find(|item| { - item["type"] == "function_call_output" && item["call_id"] == output["call_id"] - }) - .expect("original tool output in history") - }); - for ((wire, recorded), query) in [&first_output, &second_output] - .into_iter() - .zip(recorded_outputs) - .zip(["first", "second"]) - { - assert_eq!(wire["output"], recorded["output"]); - assert!( - wire["output"] - .to_string() - .contains(&format!("result for {query}")) - ); - let recorded_metadata = tool_call_metadata(recorded.clone()); - let wire_metadata = tool_call_metadata(wire.clone()); - assert_eq!(recorded_metadata["tool_calls_complete"], true); - assert_eq!( - recorded_metadata["executed_tool_calls"][0]["name"], - format!("{SEARCH_CALENDAR_NAMESPACE}{SEARCH_CALENDAR_LIST_TOOL}") - ); - assert_eq!( - recorded_metadata["executed_tool_calls"][0]["arguments"], - json!({"query": query}) - ); - let wire_result_metadata = - wire_metadata["executed_tool_calls"][0].get("tool_result_metadata"); - if include_internal_metadata { - assert_eq!(wire_result_metadata, Some(&metadata_for_query(query))); - } else { - // An ungranted provider must not receive internal result metadata. - assert!(wire_result_metadata.is_none()); - } - } - let first_metadata = tool_call_metadata(recorded_outputs[0].clone()); - let second_metadata = tool_call_metadata(recorded_outputs[1].clone()); - assert_eq!( - first_metadata["executed_tool_calls"][0]["tool_result_metadata"], - metadata_for_query("first") - ); - let marker = second_metadata["executed_tool_calls"][0]["tool_result_metadata"] - .as_str() - .expect("second result should have an omission marker"); - let overage = marker - .strip_prefix("omitted_due_to_size_limit (overage_bytes=") - .and_then(|value| value.strip_suffix(')')) - .and_then(|value| value.parse::().ok()) - .expect("marker should report omitted bytes"); - assert!(overage > 0); - if !include_internal_metadata { - return Ok(()); - } - - let rollout_path = test.codex.rollout_path().expect("rollout path"); - if fork_from_running_thread { - test.codex.flush_rollout().await?; - } else { - test.codex.shutdown_and_wait().await?; - test.thread_manager - .remove_thread(&test.session_configured.thread_id) - .await; - } - let rollout = tokio::fs::read_to_string(&rollout_path).await?; - let rollout = rollout - .lines() - .map(serde_json::from_str::) - .collect::>>()?; - for (call_id, expected) in [("first", &first_metadata), ("second", &second_metadata)] { - let item = rollout - .iter() - .find(|line| { - line["type"] == "response_item" - && line["payload"]["type"] == "function_call_output" - && line["payload"]["call_id"] == call_id - }) - .expect("persisted tool output"); - assert_eq!(tool_call_metadata(item["payload"].clone()), *expected); - } - let forked = test - .thread_manager - .fork_legacy_thread( - ForkSnapshot::Interrupted, - StartThreadOptions::new(test.config.clone()), - rollout_path.clone(), - ) - .await?; - wait_for_mcp_server(&forked.thread, CODEX_APPS_MCP_SERVER_NAME).await?; - forked - .thread - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "List events in the fork.".to_string(), - text_elements: Vec::new(), - }])) - .await?; - wait_for_event(&forked.thread, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - forked - .thread - .shutdown_and_wait() - .await - .expect("shutdown fork"); - - if fork_from_running_thread { - test.codex.shutdown_and_wait().await?; - } - - let resumed = search_capable_apps_builder(apps.chatgpt_base_url) - .with_config(configure_metadata) - .resume(&server, test.home.clone(), rollout_path) - .await - .expect("resume original thread"); - wait_for_mcp_server(&resumed.codex, CODEX_APPS_MCP_SERVER_NAME) - .await - .expect("start resumed MCP server"); - resumed - .submit_text_turn("List events after resume.") - .await - .expect("run resumed turn"); - resumed - .codex - .shutdown_and_wait() - .await - .expect("shutdown resumed thread"); - - let requests = responses.requests(); - assert_eq!(requests.len(), 7); - let expected_fork = if fork_from_running_thread { - "warm_fork" - } else { - "cold_fork" - }; - let initialization = requests - .iter() - .map(|request| { - let body = request.body_json(); - let metadata: Value = serde_json::from_str( - body["client_metadata"]["x-codex-turn-metadata"] - .as_str() - .expect("turn metadata"), - ) - .expect("valid turn metadata"); - metadata["history_initialization"].clone() - }) - .collect::>(); - assert_eq!( - Value::Array(initialization), - json!([ - "new", - "new", - "new", - expected_fork, - expected_fork, - "cold_resume", - "cold_resume" - ]) - ); - for request in &requests[3..] { - for original in [&first_output, &second_output] { - let call_id = original["call_id"].as_str().expect("call ID"); - let output = request.function_call_output(call_id); - assert_eq!(output["output"], original["output"]); - let passthrough = output.get("internal_chat_message_metadata_passthrough"); - assert!( - passthrough - .and_then(|meta| meta.get("executed_tool_calls")) - .is_none() - ); - assert!( - passthrough - .and_then(|meta| meta.get("tool_calls_complete")) - .is_none() - ); - } - } - for (request, query) in [(&requests[4], "fork"), (&requests[6], "resume")] { - let output = request.function_call_output(query); - assert!( - output["output"] - .to_string() - .contains(&format!("result for {query}")) - ); - let metadata = tool_call_metadata(output); - assert_eq!(metadata["tool_calls_complete"], true); - assert_eq!( - metadata["executed_tool_calls"].as_array().map(Vec::len), - Some(1) - ); - assert_eq!( - metadata["executed_tool_calls"][0]["name"], - format!("{SEARCH_CALENDAR_NAMESPACE}{SEARCH_CALENDAR_LIST_TOOL}") - ); - assert_eq!( - metadata["executed_tool_calls"][0]["arguments"], - json!({"query": query}) - ); - assert_eq!( - metadata["executed_tool_calls"][0]["tool_result_metadata"], - metadata_for_query(query) - ); - } - Ok(()) -} diff --git a/codex-rs/core/tests/suite/guardian_review.rs b/codex-rs/core/tests/suite/guardian_review.rs index 6c593c94..abb2e2c3 100644 --- a/codex-rs/core/tests/suite/guardian_review.rs +++ b/codex-rs/core/tests/suite/guardian_review.rs @@ -6,7 +6,6 @@ use chrono::DateTime; use chrono::Local; use chrono::Utc; use codex_config::types::McpServerConfig; -use codex_config::types::OtelExporterKind; use codex_core::SleepFuture; use codex_core::TimeFuture; use codex_core::TimeProvider; @@ -2397,14 +2396,12 @@ async fn interrupted_guardian_review_across_model_change_does_not_execute_the_co #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tracing_test::traced_test] -#[test_case(None, false, true; "legacy_fallback")] -#[test_case(None, true, true; "otel_enabled")] -#[test_case(Some("Acting model rejection instructions."), false, true; "catalog_override")] -#[test_case(Some(""), false, true; "empty_override")] -#[test_case(None, false, false; "feedback_disabled")] +#[test_case(None, true; "legacy_fallback")] +#[test_case(Some("Acting model rejection instructions."), true; "catalog_override")] +#[test_case(Some(""), true; "empty_override")] +#[test_case(None, false; "feedback_disabled")] async fn guardian_denial_rejects_tool_call_with_rationale( rejection_instructions: Option<&'static str>, - log_assessments: bool, feedback_enabled: bool, ) -> Result<()> { skip_if_no_network!(Ok(())); @@ -2455,12 +2452,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale( .with_config(move |config| { config.feedback_enabled = feedback_enabled; config.otel.log_user_prompt = true; - config.otel.log_guardian_assessments = log_assessments; - config.otel.exporter = OtelExporterKind::OtlpGrpc { - endpoint: "http://127.0.0.1:1".to_string(), - headers: Default::default(), - tls: None, - }; config.permissions.approval_policy = Constrained::allow_any(approval_policy); config .set_legacy_sandbox_policy(sandbox_policy_for_config) @@ -2669,8 +2660,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale( "Guardian-denied command unexpectedly executed" ); - // Approval workers do not inherit the test span, so select the conversation explicitly. - let thread_id = test.session_configured.thread_id; let logs = String::from_utf8( tracing_test::internal::global_buf() .lock() @@ -2696,24 +2685,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale( 1, "Guardian prompt telemetry: {prompt_events:?}" ); - let assessments: Vec<_> = logs - .lines() - .filter(|line| { - line.contains("codex.guardian_assessment") - && line.contains(&format!("conversation.id={thread_id}")) - }) - .collect(); - assert_eq!(assessments.len(), usize::from(log_assessments)); - if let Some(log) = assessments.first() { - for field in [ - "status=\"denied\"", - "outcome=\"deny\"", - "item.id=\"exec-call-denied\"", - "rationale=\"The requested write has unacceptable test risk.\"", - ] { - assert!(log.contains(field), "missing {field}: {log}"); - } - } Ok(()) } diff --git a/codex-rs/core/tests/suite/mcp_auth_elicitation.rs b/codex-rs/core/tests/suite/mcp_auth_elicitation.rs index 5247ac1a..2f45abc0 100644 --- a/codex-rs/core/tests/suite/mcp_auth_elicitation.rs +++ b/codex-rs/core/tests/suite/mcp_auth_elicitation.rs @@ -1,9 +1,6 @@ -//! Verify MCP prompts and elicitation analytics through actual turns. +//! Verify MCP prompts and elicitations through actual turns. use anyhow::Result; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::AppServerRpcTransport; -use codex_app_server_protocol as app; use codex_core::RestrictRootCapabilities; use codex_core::StartThreadOptions; use codex_core::TurnInputRequest; @@ -14,7 +11,6 @@ use codex_extension_api::McpToolResultInput; use codex_extension_api::ToolLifecycleContributor; use codex_extension_api::ToolLifecycleFuture; use codex_features::Feature; -use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_protocol::SessionId; use codex_protocol::approvals::ElicitationRequest; @@ -54,7 +50,6 @@ use wiremock::Respond; use wiremock::ResponseTemplate; use wiremock::matchers::body_partial_json; use wiremock::matchers::method; -use wiremock::matchers::path; use wiremock::matchers::path_regex; const CALL_ID: &str = "calendar-elicitation-call"; @@ -146,7 +141,7 @@ impl ToolLifecycleContributor for RemoveAuthMetadata { #[test_case(Scenario::LegacyCancelled; "legacy cancelled")] #[test_case(Scenario::ModernDeclined; "modern declined")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> { +async fn actual_turn_elicitations(scenario: Scenario) -> Result<()> { skip_if_no_network!(Ok(())); let modern = scenario != Scenario::LegacySuccess && scenario != Scenario::LegacyCancelled; @@ -158,12 +153,6 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> { ); let server = responses::start_mock_server().await; AppsTestServer::mount_searchable(&server).await?; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(/*status*/ 200)) - .mount(&server) - .await; - if auth_failure { Mock::given(method("POST")) .and(path_regex("^/api/codex/ps/mcp/?$")) @@ -200,42 +189,33 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> { ) .await; - let client = AnalyticsEventsClient::new( - codex_core::test_support::auth_manager_from_auth( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - server.uri(), - /*analytics_enabled*/ Some(true), - ); - let mut builder = search_capable_apps_builder(server.uri()) - .with_analytics_events_client(client.clone()) - .with_config(move |config| { - config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); - config.approvals_reviewer = ApprovalsReviewer::User; - if scenario != Scenario::DefaultAuth { - config - .features - .set_enabled(Feature::ToolCallMcpElicitation, modern) - .expect("approval feature should be configurable"); - } - let user_config_path = config.codex_home.join("config.toml").abs(); - let approval_mode = if scenario == Scenario::DefaultAuth { - "auto" - } else { - "prompt" - }; - let user_config = toml::from_str(&format!( - r#"[apps.calendar] + let mut builder = search_capable_apps_builder(server.uri()).with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config.approvals_reviewer = ApprovalsReviewer::User; + if scenario != Scenario::DefaultAuth { + config + .features + .set_enabled(Feature::ToolCallMcpElicitation, modern) + .expect("approval feature should be configurable"); + } + let user_config_path = config.codex_home.join("config.toml").abs(); + let approval_mode = if scenario == Scenario::DefaultAuth { + "auto" + } else { + "prompt" + }; + let user_config = toml::from_str(&format!( + r#"[apps.calendar] default_tools_approval_mode = "{approval_mode}" approvals_reviewer = "user" "#, - )) - .expect("apps config should parse"); - config.config_layer_stack = config - .config_layer_stack - .with_user_config(&user_config_path, user_config) - .expect("apps user config should be valid"); - }); + )) + .expect("apps config should parse"); + config.config_layer_stack = config + .config_layer_stack + .with_user_config(&user_config_path, user_config) + .expect("apps user config should be valid"); + }); if scenario == Scenario::AuthMetadataRemoved { let mut extensions = ExtensionRegistryBuilder::new(); extensions.tool_lifecycle_contributor(Arc::new(RemoveAuthMetadata)); @@ -243,31 +223,6 @@ approvals_reviewer = "user" } let test = builder.build_with_auto_env(&server).await?; let session = &test.session_configured; - let thread_id = session.thread_id.to_string(); - client.track_initialize( - /*connection_id*/ 1, - app::InitializeParams::default(), - "test-client".to_string(), - AppServerRpcTransport::Stdio, - ); - let thread_response = serde_json::from_value(json!({ - "thread": { - "id": thread_id, "sessionId": session.session_id.to_string(), "preview": "", - "ephemeral": false, "modelProvider": session.model_provider_id, - "createdAt": 1, "updatedAt": 1, "status": {"type": "idle"}, - "cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [], - }, - "model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd, - "approvalPolicy": app::AskForApproval::from(session.approval_policy), - "approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer), - "sandbox": app::SandboxPolicy::from(test.config.legacy_sandbox_policy()), - }))?; - client.track_response( - /*connection_id*/ 1, - app::RequestId::Integer(1), - &app::ClientResponsePayload::ThreadStart(thread_response), - ); - let request = TurnInputRequest::user_input(vec![UserInput::Text { text: "Use [$calendar](app://calendar) to create a calendar event.".to_string(), text_elements: Vec::new(), @@ -287,13 +242,6 @@ approvals_reviewer = "user" match event.msg { EventMsg::TurnStarted(started) => { assert_eq!(started.turn_id, turn_id); - client.track_notification(&app::ServerNotification::TurnStarted( - serde_json::from_value(json!({ - "threadId": thread_id, - "turn": {"id": started.turn_id, "items": [], - "status": "inProgress", "startedAt": started.started_at}, - }))?, - )); } message @ (EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_)) => { let (item, item_thread_id, item_turn_id, completed) = match &message { @@ -315,9 +263,6 @@ approvals_reviewer = "user" assert_eq!(item.connector_id.as_deref(), Some("calendar")); target_lifecycle[usize::from(completed)] += 1; } - let notification = - app::item_event_to_server_notification(message, &thread_id, &event_turn_id); - client.track_notification(¬ification); } EventMsg::RequestUserInput(request) => { assert!(!modern, "legacy approval requested for {scenario:?}"); @@ -381,15 +326,6 @@ approvals_reviewer = "user" } EventMsg::TurnComplete(completed) => { assert_eq!(completed.turn_id, turn_id); - client.track_notification(&app::ServerNotification::TurnCompleted( - serde_json::from_value(json!({ - "threadId": thread_id, - "turn": {"id": completed.turn_id, "items": [], "status": "completed", - "startedAt": completed.started_at, - "completedAt": completed.completed_at, - "durationMs": completed.duration_ms}, - }))?, - )); break; } EventMsg::Error(error) => { @@ -459,61 +395,6 @@ approvals_reviewer = "user" assert!(!output.to_string().contains(PRIVATE_SENTINEL)); } - tokio::time::timeout(Duration::from_secs(10), client.flush()).await?; - let mut events = Vec::new(); - for request in server.received_requests().await.unwrap_or_default() { - if request.method != "POST" || request.url.path() != "/codex/analytics-events/events" { - continue; - } - let payload: Value = serde_json::from_slice(&request.body)?; - let batch = payload["events"].as_array().expect("analytics events"); - events.extend(batch.iter().cloned()); - } - let mcp_events = events - .iter() - .filter(|event| { - event["event_type"] == "codex_mcp_tool_call_event" - && event["event_params"]["item_id"] == CALL_ID - }) - .collect::>(); - let app_used_events = events - .iter() - .filter(|event| { - event["event_type"] == "codex_app_used" - && event["event_params"]["connector_id"] == "calendar" - && event["event_params"]["turn_id"] == turn_id - }) - .collect::>(); - assert_eq!(mcp_events.len(), 1); - assert_eq!(app_used_events.len(), usize::from(approved)); - assert_eq!(mcp_events[0]["event_params"]["connector_id"], "calendar"); - assert_eq!(mcp_events[0]["event_params"]["thread_id"], thread_id); - assert_eq!(mcp_events[0]["event_params"]["turn_id"], turn_id); - assert_eq!( - mcp_events[0]["event_params"]["terminal_status"], - if scenario == Scenario::LegacySuccess { - "completed" - } else { - "failed" - } - ); - let expected = match scenario { - Scenario::DefaultAuth | Scenario::ModernAuth | Scenario::AuthMetadataRemoved => { - json!("auth_or_link") - } - Scenario::LegacySuccess => Value::Null, - Scenario::LegacyCancelled | Scenario::ModernDeclined => json!("approval"), - }; - for event in mcp_events.iter().chain(app_used_events.iter()) { - assert_eq!( - event["event_params"].get("elicitation_type"), - Some(&expected) - ); - } - let target_payload = serde_json::to_string(&(mcp_events, app_used_events))?; - assert!(!target_payload.contains(PRIVATE_SENTINEL)); - assert!(!target_payload.contains("https://chatgpt.com/apps/")); - Ok(()) } diff --git a/codex-rs/core/tests/suite/multi_agent_resume.rs b/codex-rs/core/tests/suite/multi_agent_resume.rs index 09c317d8..f11fb5f0 100644 --- a/codex-rs/core/tests/suite/multi_agent_resume.rs +++ b/codex-rs/core/tests/suite/multi_agent_resume.rs @@ -1,16 +1,13 @@ use anyhow::Result; -use codex_analytics::AnalyticsEventsClient; use codex_core::TurnInputRequest; use codex_core::config::AgentRoleConfig; use codex_features::Feature; -use codex_login::CodexAuth; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::user_input::UserInput; -use codex_thread_store::ReadThreadParams; use core_test_support::responses::assert_parent_turn; use core_test_support::responses::assert_root_turn; use core_test_support::responses::ev_assistant_message; @@ -30,10 +27,6 @@ use serde_json::json; use std::time::Duration; use tokio::time::Instant; use tokio::time::sleep; -use wiremock::Mock; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; #[path = "multi_agent_restore_tests.rs"] mod restore_tests; @@ -279,7 +272,6 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu }); let initial = initial_builder.build_with_auto_env(&server).await?; let root_thread_id = initial.session_configured.thread_id; - let root_session_id = initial.session_configured.session_id; initial .codex .start_or_steer_turn( @@ -400,16 +392,6 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu sibling_thread.flush_rollout().await?; worker_thread.flush_rollout().await?; initial.codex.flush_rollout().await?; - let worker_created_at = initial - .thread_store - .read_thread(ReadThreadParams { - thread_id: worker_thread_id, - include_archived: true, - include_history: false, - }) - .await? - .created_at - .timestamp(); sibling_thread.shutdown_and_wait().await?; worker_thread.shutdown_and_wait().await?; drop(sibling_thread); @@ -463,25 +445,10 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu ) .await; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(/* status */ 200)) - .mount(&server) - .await; - let analytics_client = AnalyticsEventsClient::new( - codex_core::test_support::auth_manager_from_auth( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - server.uri(), - /* analytics_enabled */ Some(true), - ); let resumed_model_provider_base_url = format!("{}/v1", server.uri()); - let mut resume_builder = test_codex() - .with_analytics_events_client(analytics_client.clone()) - .with_config(move |config| { - configure_multi_agent_v2_with_role(config, &resumed_model_provider_base_url); - config.analytics_enabled = Some(true); - }); + let mut resume_builder = test_codex().with_config(move |config| { + configure_multi_agent_v2_with_role(config, &resumed_model_provider_base_url); + }); let resumed = resume_builder.restart(&server, &initial).await?; resumed .codex @@ -578,44 +545,6 @@ openai_base_url = "{redirected_base_url}" matches!(event, EventMsg::TurnComplete(_)) }) .await; - tokio::time::timeout(Duration::from_secs(10), analytics_client.flush()).await?; - let mut worker_initializations = Vec::new(); - for request in server.received_requests().await.unwrap_or_default() { - if request.url.path() != "/codex/analytics-events/events" { - continue; - } - let payload: Value = serde_json::from_slice(&request.body)?; - worker_initializations.extend( - payload["events"] - .as_array() - .expect("analytics events") - .iter() - .filter(|event| { - event["event_type"] == "codex_thread_initialized" - && event["event_params"]["thread_id"] == worker_thread_id.to_string() - }) - .map(|event| { - let params = &event["event_params"]; - json!({ - "session_id": params["session_id"], - "parent_thread_id": params["parent_thread_id"], - "subagent_source": params["subagent_source"], - "initialization_mode": params["initialization_mode"], - "created_at": params["created_at"], - }) - }), - ); - } - assert_eq!( - worker_initializations, - vec![json!({ - "session_id": root_session_id.to_string(), - "parent_thread_id": root_thread_id.to_string(), - "subagent_source": "thread_spawn", - "initialization_mode": "resumed", - "created_at": worker_created_at, - })] - ); assert!(followup_child_request.requests().iter().any(|request| { request.body_contains_text(FOLLOWUP_TASK) && request.body_contains_text(ROLE_DEVELOPER_INSTRUCTIONS) diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index 47fd6f4f..cd2d48c4 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -3,12 +3,8 @@ use core_test_support::test_codex::local_requests; use std::sync::Arc; use std::time::Duration; -use std::time::Instant; use anyhow::Result; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::PluginMeasurementRow; -use codex_analytics::PluginMeasurementsInput; use codex_config::LoaderOverrides; use codex_core::TurnInputRequest; use codex_core::config::Config; @@ -28,12 +24,10 @@ use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_protocol::config_types::TrustLevel; -use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; #[cfg(unix)] -use codex_protocol::protocol::GranularApprovalConfig; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::user_input::UserInput; use codex_skills_extension::HostSkillsLoadInput; @@ -58,7 +52,6 @@ use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::skip_if_remote; #[cfg(unix)] -use core_test_support::skip_if_sandbox; use core_test_support::skip_if_target_windows; use core_test_support::stdio_server_bin; use core_test_support::submit_thread_settings; @@ -82,7 +75,6 @@ const SAMPLE_PLUGIN_CONFIG_NAME: &str = "sample@test"; const SAMPLE_REMOTE_PLUGIN_CONFIG_NAME: &str = "sample@openai-curated-remote"; const SAMPLE_PLUGIN_DISPLAY_NAME: &str = "sample"; const SAMPLE_PLUGIN_DESCRIPTION: &str = "inspect sample data"; -const SAMPLE_REMOTE_PLUGIN_ID: &str = "plugins~Plugin_sample"; const SAMPLE_PLUGIN_APP_NAMESPACE: &str = "mcp__codex_apps__google_calendar"; const SAMPLE_PLUGIN_MCP_NAMESPACE: &str = "mcp__sample"; const PLUGIN_APP_SEARCH_CALL_ID: &str = "plugin-app-search"; @@ -170,17 +162,6 @@ fn write_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf { write_sample_plugin_skill(write_sample_plugin_manifest_and_config(home)) } -fn write_remote_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf { - let plugin_root = home - .path() - .join("plugins/cache/openai-curated-remote/sample/local"); - write_sample_plugin_skill(write_sample_plugin_manifest_and_config_at_root( - home, - plugin_root, - SAMPLE_REMOTE_PLUGIN_CONFIG_NAME, - )) -} - fn write_sample_plugin_skill(plugin_root: std::path::PathBuf) -> std::path::PathBuf { let skill_dir = plugin_root.join("skills/sample-search"); std::fs::create_dir_all(skill_dir.as_path()).expect("create plugin skill dir"); @@ -285,21 +266,6 @@ fn write_plugin_app_plugin_with_name(home: &TempDir, app_name: &str) { .expect("write plugin app config"); } -async fn build_analytics_plugin_test_codex( - server: &MockServer, - codex_home: Arc, -) -> Result { - let chatgpt_base_url = server.uri(); - let mut builder = test_codex() - .with_home(codex_home) - .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) - .with_model("gpt-5.2") - .with_config(move |config| { - config.chatgpt_base_url = chatgpt_base_url; - }); - builder.build_with_auto_env(server).await -} - async fn build_apps_enabled_plugin_test_codex( server: &MockServer, codex_home: Arc, @@ -367,105 +333,6 @@ fn searched_plugin_tools( ) } -#[tokio::test] -async fn shared_analytics_client_preserves_session_products() -> Result<()> { - skip_if_no_network!(Ok(())); - let server = start_mock_server().await; - Mock::given(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - let client = AnalyticsEventsClient::new( - codex_core::test_support::auth_manager_from_auth( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - server.uri(), - /*analytics_enabled*/ Some(true), - ); - let mut products = [Some("aeon"), Some("tpp"), None]; - let mut sessions = Vec::new(); - for product in products { - sessions.push( - test_codex() - .with_analytics_events_client(client.clone()) - .with_config(move |config| { - config.apps_mcp_product_sku = product.map(str::to_string); - }) - .build_with_auto_env(&server) - .await?, - ); - } - // All Sessions have registered before events are interleaved on their shared client. - let mut expected = Vec::new(); - for (position, index) in [0, 1, 2, 0, 0].into_iter().enumerate() { - if position == 4 { - client.flush().await; - let session = &mut sessions[0]; - session.codex.ensure_rollout_materialized().await; - session.codex.shutdown_and_wait().await?; - session - .thread_manager - .remove_thread(&session.session_configured.thread_id) - .await; - let mut config = session.config.clone(); - config.analytics_enabled = Some(false); - let resumed = session - .thread_manager - .resume_legacy_thread_from_rollout( - config, - session.codex.rollout_path().expect("rollout path"), - session.thread_manager.auth_manager(), - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await?; - assert_eq!(resumed.thread_id, session.session_configured.thread_id); - session.codex = resumed.thread; - products[0] = None; - } - let thread_id = sessions[index].session_configured.thread_id.to_string(); - client.track_plugin_measurements(PluginMeasurementsInput { - thread_id: thread_id.clone(), - turn_id: "turn".into(), - item_id: "item".into(), - originator: "test_client".into(), - model_slug: None, - reasoning_effort: None, - plugin_id: "sample@test".into(), - execution_id: "execution".into(), - operation: "build".into(), - rows: vec![PluginMeasurementRow { - measurement_name: "duration_ms".into(), - number_value: 1.0, - dimensions: Default::default(), - }], - }); - expected.push((thread_id, products[index].map(str::to_string))); - } - client.flush().await; - let mut actual = Vec::new(); - for request in server.received_requests().await.unwrap_or_default() { - if request.url.path() != "/codex/analytics-events/events" { - continue; - } - let product = request - .headers - .get("x-openai-product-sku") - .map(|value| value.to_str().unwrap().to_string()); - let body: serde_json::Value = serde_json::from_slice(&request.body)?; - for event in body["events"].as_array().unwrap() { - if event["event_type"] == "codex_plugin_measurement_event" { - let thread_id = event["event_params"]["thread_id"].as_str().unwrap(); - actual.push((thread_id.to_string(), product.clone())); - } - } - } - actual.sort(); - expected.sort(); - assert_eq!(actual, expected); - Ok(()) -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn persisted_remote_plugin_command_attribution_flows_through_turn_context() -> Result<()> { skip_if_target_windows!(Ok(()), "executes a POSIX shell script"); @@ -478,19 +345,7 @@ async fn persisted_remote_plugin_command_attribution_flows_through_turn_context( let server = start_mock_server().await; let codex_home = Arc::new(TempDir::new()?); let script_path = write_remote_plugin_script_and_config(codex_home.as_ref()); - std::fs::write( - &script_path, - r#"printf '%s' '{"version":1,"measurements":[{"name":"files_scanned","value":7}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT" -"#, - )?; - let plugin_root = script_path - .parent() - .and_then(std::path::Path::parent) - .expect("plugin root"); - std::fs::write( - plugin_root.join("analytics.yaml"), - "version: 1\noperations: {scan: {path: ./scripts/run.sh, measurements: {files_scanned: {}}}}\n", - )?; + std::fs::write(&script_path, "printf done\n")?; let builder = test_codex(); let command = shlex::try_join(["/bin/sh", script_path.to_string_lossy().as_ref()])?; let call_id = "remote-plugin-command"; @@ -576,316 +431,6 @@ async fn persisted_remote_plugin_command_attribution_flows_through_turn_context( assert_eq!(script_path, Some("scripts/run.sh")); } - let measurement = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await; - assert_eq!( - serde_json::json!({ - "plugin_id": measurement["event_params"]["plugin_id"], - "operation": measurement["event_params"]["operation"], - "measurement_name": measurement["event_params"]["measurement_name"], - "number_value": measurement["event_params"]["number_value"], - }), - serde_json::json!({ - "plugin_id": REMOTE_PLUGIN_CONFIG_NAME, - "operation": "scan", - "measurement_name": "files_scanned", - "number_value": 7.0, - }) - ); - - Ok(()) -} - -#[cfg(unix)] -#[test_case(codex_exec_server::LOCAL_ENVIRONMENT_ID; "local")] -#[test_case(codex_exec_server::REMOTE_ENVIRONMENT_ID; "remote")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn plugin_metrics_stdin_works_with_sandbox_approval_disabled( - environment_id: &str, -) -> Result<()> { - skip_if_no_network!(Ok(())); - skip_if_sandbox!(Ok(())); - let server = start_mock_server().await; - let home = Arc::new(TempDir::new()?); - let script = write_remote_plugin_script_and_config(home.as_ref()); - std::fs::write( - &script, - r#"test -n "${CODEX_PLUGIN_METRICS_OUTPUT:-}" || exit 2 -IFS= read -r input -test "$input" = continue || exit 3 -printf '%s' '{"version":1,"measurements":[{"name":"files_scanned","value":7}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT" || exit 4 -printf 'STDIN_OK\n' -"#, - )?; - std::fs::write( - script - .parent() - .unwrap() - .parent() - .unwrap() - .join("analytics.yaml"), - "version: 1\noperations: {scan: {path: ./scripts/run.sh, measurements: {files_scanned: {}}}}\n", - )?; - let command = shlex::try_join(["/bin/sh", script.to_string_lossy().as_ref()])?; - let responses = mount_sse_sequence( - &server, - vec![ - sse(vec![ - ev_function_call( - "open", - "exec_command", - &serde_json::json!({ - "cmd": command, - "login": false, - "tty": true, - "yield_time_ms": 1000, - "environment_id": environment_id, - }) - .to_string(), - ), - ev_completed("opened"), - ]), - sse(vec![ - ev_function_call( - "input", - "write_stdin", - &serde_json::json!({ - "session_id": 1000, - "chars": "continue\n", - "yield_time_ms": 1000, - }) - .to_string(), - ), - ev_completed("sent"), - ]), - sse(vec![ev_completed("done")]), - ], - ) - .await; - let base_url = server.uri(); - let mut builder = test_codex() - .with_home(home) - .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) - .with_model("gpt-5.2") - .with_config(move |config| { - config.chatgpt_base_url = base_url; - config.analytics_enabled = Some(true); - config - .features - .enable(Feature::SkipHostSkillDiscovery) - .unwrap(); - }); - // Exercise both native and executor-managed sandboxes with the same plugin fixture. - let _executor = if environment_id == codex_exec_server::REMOTE_ENVIRONMENT_ID { - let executor = core_test_support::exec_server::ExecServerProcess::start().await?; - builder = builder.with_exec_server_url(executor.websocket_url.clone()); - Some(executor) - } else { - None - }; - let test = builder.build(&server).await?; - let (sandbox_policy, permission_profile) = - turn_permission_fields(PermissionProfile::read_only(), test.config.cwd.as_path()); - test.codex - .start_or_steer_turn( - TurnInputRequest::user_input(vec![UserInput::Text { - text: "send input to the plugin".into(), - text_elements: Vec::new(), - }]) - .with_thread_settings(ThreadSettingsOverrides { - approval_policy: Some(AskForApproval::Granular(GranularApprovalConfig { - sandbox_approval: false, - rules: false, - skill_approval: false, - request_permissions: false, - mcp_elicitations: false, - })), - sandbox_policy: Some(sandbox_policy), - permission_profile, - ..Default::default() - }), - ) - .await?; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - let output = responses.function_call_output_text("input").unwrap(); - assert!(output.contains("Process exited with code 0"), "{output}"); - assert!(output.contains("STDIN_OK"), "{output}"); - let measurement = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await; - assert_eq!( - serde_json::json!({ - "plugin_id": measurement["event_params"]["plugin_id"], - "measurement_name": measurement["event_params"]["measurement_name"], - "number_value": measurement["event_params"]["number_value"], - }), - serde_json::json!({ - "plugin_id": REMOTE_PLUGIN_CONFIG_NAME, - "measurement_name": "files_scanned", - "number_value": 7.0, - }), - ); - Ok(()) -} - -#[cfg(unix)] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn remote_plugin_measurements_require_the_frontend_version() -> Result<()> { - skip_if_no_network!(Ok(())); - // This fixture needs a real remote transport with separately controlled frontend - // and executor caches, rather than the runner's automatic executor selection. - let executor = core_test_support::exec_server::ExecServerProcess::start().await?; - let server = start_mock_server().await; - let home = Arc::new(TempDir::new()?); - let frontend_script = write_remote_plugin_script_and_config(home.as_ref()); - let script = r#"if [ -n "${CODEX_PLUGIN_METRICS_OUTPUT:-}" ]; then - printf '%s' '{"version":1,"measurements":[{"name":"duration_ms","value":7,"dimensions":{"release":"v1"}}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT" -else - printf 'no metrics sidecar\n' -fi -"#; - std::fs::write(&frontend_script, script)?; - std::fs::write( - frontend_script - .parent() - .unwrap() - .parent() - .unwrap() - .join("analytics.yaml"), - "version: 1\noperations:\n dependency_install:\n path: ./scripts/run.sh\n measurements:\n duration_ms:\n dimensions:\n release: [v1]\n", - )?; - let executor_home = TempDir::new()?; - let mut responses = Vec::new(); - for (version, call_id) in [("2.0.0", "wrong-version"), ("1.2.3", "matching-version")] { - let root = executor_home.path().join(format!( - "plugins/cache/openai-curated-remote/sample/{version}" - )); - std::fs::create_dir_all(root.join("scripts"))?; - let path = root.join("scripts/run.sh"); - std::fs::write(&path, script)?; - // The executor's declaration is never an authority, even for matching bytes. - std::fs::write( - root.join("analytics.yaml"), - "version: 1\noperations: {untrusted: {path: ./scripts/run.sh, measurements: {other: {}}}}\n", - )?; - // A plugin-shaped alias must use the canonical plugin's identity and version. - let alias = executor_home.path().join(format!( - "plugins/cache/openai-curated-remote/apparent-plugin/{version}" - )); - std::fs::create_dir_all(alias.parent().unwrap())?; - std::os::unix::fs::symlink(&root, &alias)?; - let alias_script = alias.join("scripts/run.sh"); - let command = shlex::try_join(["/bin/sh", alias_script.to_string_lossy().as_ref()])?; - responses.push(sse(vec![ - ev_response_created(call_id), - ev_function_call( - call_id, - "exec_command", - &serde_json::json!({ - "cmd": command, - "login": false, - "environment_id": codex_exec_server::REMOTE_ENVIRONMENT_ID, - "yield_time_ms": 1000, - }) - .to_string(), - ), - ev_completed(call_id), - ])); - } - responses.push(sse(vec![ - ev_response_created("done"), - ev_assistant_message("done-message", "done"), - ev_completed("done"), - ])); - let response_mock = mount_sse_sequence(&server, responses).await; - let base_url = server.uri(); - let mut builder = test_codex() - .with_exec_server_url(executor.websocket_url.clone()) - .with_home(home) - .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) - .with_model("gpt-5.2") - .with_config(move |config| { - config.chatgpt_base_url = base_url; - config.analytics_enabled = Some(true); - config - .features - .enable(Feature::SkipHostSkillDiscovery) - .unwrap(); - }); - let test = builder.build(&server).await?; - let manager = test.thread_manager.environment_manager(); - let remote = manager.default_environment().unwrap(); - tokio::time::timeout(Duration::from_secs(30), remote.wait_until_ready()).await??; - assert!(remote.is_remote()); - let (sandbox_policy, permission_profile) = - turn_permission_fields(PermissionProfile::Disabled, test.config.cwd.as_path()); - test.codex - .start_or_steer_turn( - TurnInputRequest::user_input(vec![UserInput::Text { - text: "run both plugin versions".into(), - text_elements: Vec::new(), - }]) - .with_thread_settings(ThreadSettingsOverrides { - approval_policy: Some(AskForApproval::Never), - sandbox_policy: Some(sandbox_policy), - permission_profile, - ..Default::default() - }), - ) - .await?; - for call_id in ["wrong-version", "matching-version"] { - let expected = (Some(REMOTE_PLUGIN_CONFIG_NAME), Some("scripts/run.sh")); - let begin = wait_for_event_match(&test.codex, |event| match event { - EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()), - _ => None, - }) - .await; - let end = wait_for_event_match(&test.codex, |event| match event { - EventMsg::ExecCommandEnd(event) if event.call_id == call_id => Some(event.clone()), - _ => None, - }) - .await; - assert_eq!(end.exit_code, 0, "{}", end.aggregated_output); - assert_eq!( - (begin.plugin_id.as_deref(), begin.script_path.as_deref()), - expected - ); - assert_eq!( - (end.plugin_id.as_deref(), end.script_path.as_deref()), - expected - ); - } - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - assert!( - response_mock - .function_call_output_text("wrong-version") - .unwrap() - .contains("no metrics sidecar") - ); - let event = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await; - assert_eq!( - serde_json::json!({ - "plugin_id": event["event_params"]["plugin_id"], - "operation": event["event_params"]["operation"], - "measurement_name": event["event_params"]["measurement_name"], - "number_value": event["event_params"]["number_value"], - "dimensions": event["event_params"]["dimensions"], - "thread_id": event["event_params"]["thread_id"], - "item_id": event["event_params"]["item_id"], - }), - serde_json::json!({ - "plugin_id": REMOTE_PLUGIN_CONFIG_NAME, - "operation": "dependency_install", - "measurement_name": "duration_ms", - "number_value": 7.0, - "dimensions": {"release": "v1"}, - "thread_id": test.session_configured.thread_id.to_string(), - "item_id": "matching-version", - }) - ); Ok(()) } @@ -2241,205 +1786,3 @@ async fn explicitly_requested_mcp_waits_for_startup(request: ExplicitMcpRequest) Ok(()) } - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn explicit_plugin_mentions_track_plugin_used_analytics() -> Result<()> { - skip_if_no_network!(Ok(())); - let server = start_mock_server().await; - let _resp_mock = mount_sse_once( - &server, - sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), - ) - .await; - - let codex_home = Arc::new(TempDir::new()?); - write_plugin_skill_plugin(codex_home.as_ref()); - let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?; - let codex = Arc::clone(&test_codex.codex); - - codex - .start_or_steer_turn( - TurnInputRequest::user_input(vec![codex_protocol::user_input::UserInput::Mention { - name: "sample".into(), - path: format!("plugin://{SAMPLE_PLUGIN_CONFIG_NAME}"), - }]) - .with_responses_metadata(Some(std::collections::HashMap::from([]))), - ) - .await?; - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - - let event = wait_for_analytics_event(&server, "codex_plugin_used").await; - assert_eq!(event["event_params"]["plugin_id"], "sample@test"); - assert_eq!(event["event_params"]["plugin_name"], "sample"); - assert_eq!(event["event_params"]["marketplace_name"], "test"); - assert_eq!(event["event_params"]["has_skills"], true); - assert_eq!(event["event_params"]["mcp_server_count"], 0); - assert_eq!( - event["event_params"]["mcp_server_names"], - serde_json::json!([]) - ); - assert_eq!( - event["event_params"]["connector_ids"], - serde_json::json!([]) - ); - assert_eq!( - event["event_params"]["product_client_id"], - serde_json::json!(codex_login::default_client::originator().value) - ); - assert_eq!(event["event_params"]["model_slug"], "gpt-5.2"); - assert!(event["event_params"]["thread_id"].as_str().is_some()); - assert!(event["event_params"]["turn_id"].as_str().is_some()); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn explicit_plugin_skill_invocation_tracks_remote_plugin_id() -> Result<()> { - skip_if_no_network!(Ok(())); - let server = start_mock_server().await; - let _resp_mock = mount_sse_once( - &server, - sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), - ) - .await; - - let codex_home = Arc::new(TempDir::new()?); - let skill_path = dunce::canonicalize(write_remote_plugin_skill_plugin(codex_home.as_ref()))?; - persist_sample_remote_plugin_id(codex_home.as_ref()); - let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?; - let codex = Arc::clone(&test_codex.codex); - - codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Skill { - name: "sample:sample-search".into(), - path: skill_path, - }])) - .await?; - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - - let event = wait_for_analytics_event(&server, "skill_invocation").await; - assert_eq!( - event["event_params"]["plugin_id"], - SAMPLE_REMOTE_PLUGIN_CONFIG_NAME - ); - assert_eq!( - event["event_params"]["remote_plugin_id"], - SAMPLE_REMOTE_PLUGIN_ID - ); - assert_eq!(event["event_params"]["invoke_type"], "explicit"); - - Ok(()) -} - -#[derive(Clone, Copy)] -enum ImplicitPluginSkillInvocation { - SkillDocumentRead, - SkillScriptRun, -} - -#[test_case(ImplicitPluginSkillInvocation::SkillDocumentRead; "skill document read")] -#[test_case(ImplicitPluginSkillInvocation::SkillScriptRun; "skill script run")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn implicit_plugin_skill_invocation_tracks_remote_plugin_id( - invocation: ImplicitPluginSkillInvocation, -) -> Result<()> { - skip_if_target_windows!(Ok(()), "executes POSIX cat and bash commands"); - skip_if_remote!(Ok(()), "shell commands use host plugin-cache paths"); - skip_if_no_network!(Ok(())); - let server = start_mock_server().await; - let codex_home = Arc::new(TempDir::new()?); - let skill_path = write_remote_plugin_skill_plugin(codex_home.as_ref()); - persist_sample_remote_plugin_id(codex_home.as_ref()); - let command = match invocation { - ImplicitPluginSkillInvocation::SkillDocumentRead => { - format!("cat {}", skill_path.display()) - } - ImplicitPluginSkillInvocation::SkillScriptRun => { - let script_path = skill_path - .parent() - .expect("skill path should have a parent") - .join("scripts/test.sh"); - std::fs::create_dir_all( - script_path - .parent() - .expect("script path should have a parent"), - )?; - std::fs::write(&script_path, "echo skill script invoked\n")?; - format!("bash {}", script_path.display()) - } - }; - let command_args = serde_json::json!({ - "cmd": command, - "login": false, - }) - .to_string(); - let _resp_mock = mount_sse_sequence( - &server, - vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_function_call("call-1", "exec_command", &command_args), - ev_completed("resp-1"), - ]), - sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]), - ], - ) - .await; - let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?; - let codex = Arc::clone(&test_codex.codex); - - codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "inspect the sample skill".into(), - text_elements: Vec::new(), - }])) - .await?; - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - - let event = wait_for_analytics_event(&server, "skill_invocation").await; - assert_eq!( - event["event_params"]["plugin_id"], - SAMPLE_REMOTE_PLUGIN_CONFIG_NAME - ); - assert_eq!( - event["event_params"]["remote_plugin_id"], - SAMPLE_REMOTE_PLUGIN_ID - ); - assert_eq!(event["event_params"]["invoke_type"], "implicit"); - - Ok(()) -} - -fn persist_sample_remote_plugin_id(home: &TempDir) { - let plugin_id = - PluginId::parse(SAMPLE_REMOTE_PLUGIN_CONFIG_NAME).expect("remote plugin id should parse"); - PluginStore::new(home.path().to_path_buf()) - .write_remote_plugin_id(&plugin_id, SAMPLE_REMOTE_PLUGIN_ID) - .expect("persist remote plugin id"); -} - -async fn wait_for_analytics_event(server: &MockServer, event_type: &str) -> serde_json::Value { - let deadline = Instant::now() + Duration::from_secs(10); - loop { - let requests = server.received_requests().await.unwrap_or_default(); - if let Some(event) = requests - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .find_map(|request| { - let payload: serde_json::Value = serde_json::from_slice(&request.body).ok()?; - payload["events"].as_array().and_then(|events| { - events - .iter() - .find(|event| event["event_type"] == event_type) - .cloned() - }) - }) - { - break event; - } - if Instant::now() >= deadline { - panic!("timed out waiting for {event_type} analytics request"); - } - tokio::time::sleep(Duration::from_millis(50)).await; - } -} diff --git a/codex-rs/core/tests/suite/request_plugin_install.rs b/codex-rs/core/tests/suite/request_plugin_install.rs index 38cb627e..fb0e5217 100644 --- a/codex-rs/core/tests/suite/request_plugin_install.rs +++ b/codex-rs/core/tests/suite/request_plugin_install.rs @@ -60,7 +60,6 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; -use std::time::Instant; use tempfile::TempDir; use test_case::test_case; use tokio::sync::Notify; @@ -1375,56 +1374,6 @@ async fn run_remote_plugin_install_metadata_case() -> Result<()> { assert_eq!(meta["remote_plugin_id"], REMOTE_PLUGIN_ID); assert_eq!(meta["app_connector_ids"], json!([APP_CONNECTOR_ID])); - let deadline = Instant::now() + Duration::from_secs(10); - let analytics_event = loop { - let requests = server.received_requests().await.unwrap_or_default(); - if let Some(event) = requests - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .find_map(|request| { - let payload: Value = serde_json::from_slice(&request.body).ok()?; - payload["events"].as_array().and_then(|events| { - events - .iter() - .find(|event| event["event_type"] == "codex_plugin_install_requested") - .cloned() - }) - }) - { - break event; - } - if Instant::now() >= deadline { - panic!("timed out waiting for plugin install request analytics"); - } - tokio::time::sleep(Duration::from_millis(50)).await; - }; - assert_eq!( - meta["suggestion_id"], - analytics_event["event_params"]["suggestion_id"] - ); - let thread_id = analytics_event["event_params"]["thread_id"].clone(); - let turn_id = analytics_event["event_params"]["turn_id"].clone(); - assert_eq!( - analytics_event, - json!({ - "event_type": "codex_plugin_install_requested", - "event_params": { - "suggestion_id": "request_plugin_install_install-github", - "plugins": [{ - "plugin_id": "github@openai-curated-remote", - "remote_plugin_id": REMOTE_PLUGIN_ID, - "plugin_name": "GitHub", - "connector_ids": [APP_CONNECTOR_ID], - }], - "source": "endpoint_recommendation", - "thread_id": thread_id, - "turn_id": turn_id, - "model_slug": "gpt-5.5", - "product_client_id": codex_login::default_client::originator().value, - } - }) - ); - resolve_install_elicitation(&test, elicitation, ElicitationAction::Decline).await?; let requests = mock.requests(); diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs index b5b8074c..cab9562f 100644 --- a/codex-rs/core/tests/suite/scenarios.rs +++ b/codex-rs/core/tests/suite/scenarios.rs @@ -18,7 +18,6 @@ use std::time::Duration; use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use codex_analytics::CompactionTrigger; use codex_config::ConfigLayerEntry; use codex_config::ConfigLayerSource; use codex_config::ConfigLayerStack; @@ -30,6 +29,7 @@ use codex_core::StartThreadOptions; use codex_core::TurnInput; use codex_core::TurnInputRequest; use codex_core::compact::AutoCompactionDisabled; +use codex_core::compaction_metadata::CompactionTrigger; use codex_core::config::Config; use codex_core::config::TokenBudgetConfig; use codex_exec_server::CreateDirectoryOptions; diff --git a/codex-rs/core/tests/suite/skills_extension.rs b/codex-rs/core/tests/suite/skills_extension.rs index eb5b6812..d043ac63 100644 --- a/codex-rs/core/tests/suite/skills_extension.rs +++ b/codex-rs/core/tests/suite/skills_extension.rs @@ -36,10 +36,6 @@ use codex_history::RolloutItem; use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_models_manager::bundled_models_response; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; use codex_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC; use codex_protocol::capabilities::CapabilityRootLocation; use codex_protocol::capabilities::SelectedCapabilityRoot; @@ -120,16 +116,13 @@ use opentelemetry_sdk::metrics::data::MetricData; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; -use sha1::Digest; use tempfile::TempDir; use test_case::test_case; use tokio::time::Duration; -use tokio::time::Instant; use toml::toml; use tracing::Level; use tracing_subscriber::fmt::format::FmtSpan; use tracing_test::internal::MockWriter; -use wiremock::MockServer; #[path = "skills_extension/cloud_skill_tests.rs"] mod cloud_skill_tests; @@ -381,25 +374,6 @@ fn catalog_extensions( (Arc::new(extensions.build()), event_rx) } -async fn wait_for_analytics_events( - server: &MockServer, - event_type: &str, - expected_count: usize, -) -> Vec { - let deadline = Instant::now() + Duration::from_secs(10); - loop { - let events = responses::received_analytics_events(server, event_type).await; - if events.len() >= expected_count { - return events; - } - assert!( - Instant::now() < deadline, - "timed out waiting for {event_type} analytics" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - } -} - fn configure_catalog_test(config: &mut Config) { config.include_skill_instructions = true; config @@ -2562,15 +2536,6 @@ async fn executor_skill_invocation_is_environment_scoped_and_deduplicated() -> R ); } - let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 1).await; - assert_eq!(events.len(), 1, "executor skill should be counted once"); - assert_eq!(events[0]["skill_name"], "selected-environment-skill"); - assert_eq!( - events[0]["skill_id"], - format!("{:x}", sha1::Sha1::digest(SELECTED_RESOURCE.as_bytes())) - ); - assert_eq!(events[0]["event_params"]["invoke_type"], "implicit"); - Ok(()) } @@ -2732,27 +2697,16 @@ async fn assert_catalog_model_switch(max_context_tokens: Option) -> Resul ) .await; let codex_home = Arc::new(TempDir::new()?); - // Use the normal metrics sink to verify core's model attribution. - let telemetry = OtelProvider::try_new(&OtelSettings { - http_client_factory: codex_core::test_support::default_http_client_factory(), - environment: "test".to_string(), - service_name: "skills-model-switch".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: codex_home.path().to_path_buf(), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::OtlpHttp { - endpoint: format!("{}/metrics", server.uri()), - headers: Default::default(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - runtime_metrics: true, - span_attributes: Default::default(), - tracestate: Default::default(), - }) - .map_err(|error| anyhow::anyhow!("{error}"))? - .expect("metrics provider"); + // Use the process-global local metrics sink to verify core's model attribution. + let telemetry = codex_otel::install_global_metrics(codex_otel::MetricsClient::new( + codex_otel::MetricsConfig::in_memory( + "test", + "skills-model-switch", + env!("CARGO_PKG_VERSION"), + opentelemetry_sdk::metrics::InMemoryMetricExporter::default(), + ) + .with_runtime_reader(), + )?); let skill_count = 800; let catalog = SkillCatalog { is_partial: false, @@ -2932,7 +2886,7 @@ async fn assert_catalog_model_switch(max_context_tokens: Option) -> Resul expected_warnings.dedup(); assert_eq!(warnings, expected_warnings); - let snapshot = telemetry.metrics().expect("metrics client").snapshot()?; + let snapshot = telemetry.snapshot()?; let metric = snapshot .scope_metrics() .flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics) @@ -2964,9 +2918,7 @@ async fn assert_catalog_model_switch(max_context_tokens: Option) -> Resul (MODEL_B.to_string(), 1, included_counts[1] as f64), ] ); - telemetry - .shutdown_with_timeout(Duration::from_secs(/*secs*/ 5)) - .await?; + telemetry.shutdown()?; Ok(()) } @@ -3261,17 +3213,6 @@ async fn production_turn_uses_provider_host_catalog_and_core_snapshot_injection( let user_text = request.message_input_texts("user").join("\n"); assert!(user_text.contains(&snapshot_contents)); assert!(!user_text.contains(provider_contents)); - let app_mentioned_events = - wait_for_analytics_events(&server, "codex_app_mentioned", /*expected_count*/ 1).await; - let app_mentioned_event = &app_mentioned_events[0]; - assert_eq!( - app_mentioned_event["event_params"]["connector_id"], - "calendar" - ); - assert_eq!( - app_mentioned_event["event_params"]["invoke_type"], - "explicit" - ); Ok(()) } diff --git a/codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs b/codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs index 33e2e95e..dab866d4 100644 --- a/codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs +++ b/codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs @@ -4,9 +4,6 @@ use super::*; use pretty_assertions::assert_eq; use tokio::sync::Mutex; -#[path = "yielded_skill_tests.rs"] -mod yielded_skill_tests; - struct FakeCloudSkillProvider { catalog: SkillCatalog, resources: std::collections::HashMap, @@ -275,10 +272,6 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings, "next_cursor": null, }) ); - let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 1).await; - assert_eq!(events.len(), 1); - assert_eq!(events[0]["skill_name"], "demo:explicit-only"); - assert_eq!(events[0]["event_params"]["invoke_type"], "explicit"); let response = responses::mount_sse_sequence( &server, @@ -368,15 +361,6 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings, ); } - let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await; - assert_eq!(events.len(), 2, "repeated main reads must be deduplicated"); - assert_eq!(events[1]["skill_name"], "demo:explicit-only"); - assert_eq!( - events[1]["skill_id"], - format!("{:x}", sha1::Sha1::digest(MAIN_RESOURCE.as_bytes())) - ); - assert_eq!(events[1]["event_params"]["invoke_type"], "implicit"); - for (name, has_more) in [ ("alpha-visible", true), ("bravo-visible-skill", true), diff --git a/codex-rs/core/tests/suite/skills_extension/yielded_skill_tests.rs b/codex-rs/core/tests/suite/skills_extension/yielded_skill_tests.rs deleted file mode 100644 index a276697f..00000000 --- a/codex-rs/core/tests/suite/skills_extension/yielded_skill_tests.rs +++ /dev/null @@ -1,166 +0,0 @@ -//! Skill analytics retain the originating turn when Code Mode resumes a yielded cell. - -use super::*; -use codex_core::TurnInputSubmission; -use codex_protocol::openai_models::ToolMode; -use pretty_assertions::assert_eq; - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn yielded_skill_read_keeps_originating_turn_metadata() -> Result<()> { - skip_if_no_network!(Ok(())); - - const PACKAGE: &str = "skill://demo/yielded"; - const RESOURCE: &str = "skill://demo/yielded/SKILL.md"; - let server = responses::start_mock_server().await; - let mut extensions = ExtensionRegistryBuilder::new(); - install_with_providers( - &mut extensions, - SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider { - catalog: SkillCatalog { - is_partial: false, - entries: vec![SkillCatalogEntry::new( - SkillPackageId(PACKAGE.to_string()), - SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME), - "demo:yielded", - "Instructions for the yielded skill.", - SkillResourceId::new(RESOURCE), - )], - warnings: Vec::new(), - }, - resources: std::collections::HashMap::from([( - RESOURCE.to_string(), - "Yielded skill instructions.".to_string(), - )]), - reads: Mutex::default(), - read_barrier: None, - })), - |config: &Config| SkillsExtensionConfig { - include_instructions: config.include_skill_instructions, - catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas), - omit_descriptions: false, - max_context_tokens: config.skill_max_context_tokens, - bundled_skills_enabled: false, - cloud_skill_enabled: true, - shadow_selection_enabled: false, - }, - ); - let chatgpt_base_url = server.uri(); - let mut builder = test_codex() - .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) - .with_exec_server_url("none") - .with_extensions(Arc::new(extensions.build())) - .with_model_info_override("gpt-5.5", |model| { - model.tool_mode = Some(ToolMode::CodeMode); - model.experimental_supported_tools = vec!["test_sync_tool".to_string()]; - }) - .with_config(move |config| { - config.chatgpt_base_url = chatgpt_base_url; - config.cloud_skill_enabled = true; - config.features.enable(Feature::CodeMode).unwrap(); - config.features.enable(Feature::CodeModeHost).unwrap(); - }) - .with_code_mode_host_program(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?); - let test = builder.build_with_auto_env(&server).await?; - // A cannot read its skill until B has become the active turn. - let read_after_barrier = format!( - r#"await tools.test_sync_tool({{barrier: {{ - id: "yielded-skill-turns", participants: 2, timeout_ms: 60000 - }}}}); - text(await tools.skills__read({{package: "{PACKAGE}"}}));"# - ); - mount_sse_once( - &server, - sse(vec![ - ev_response_created("resp-a"), - responses::ev_custom_tool_call( - "call-a", - "exec", - &format!("// @exec: {{\"yield_time_ms\": 1}}\n{read_after_barrier}"), - ), - ev_completed("resp-a"), - ]), - ) - .await; - let yielded = mount_sse_once( - &server, - sse(vec![ - ev_response_created("resp-a-done"), - ev_completed("resp-a-done"), - ]), - ) - .await; - let request = TurnInputRequest::user_input(vec![UserInput::Text { - text: "Start a skill read and leave it running.".to_string(), - text_elements: Vec::new(), - }]); - let submitted = test.codex.start_or_steer_turn(request).await?; - let TurnInputSubmission::Started { - turn_id: turn_a, .. - } = submitted - else { - anyhow::bail!("expected turn A to start, got {submitted:?}"); - }; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - let (output, _) = yielded - .single_request() - .custom_tool_call_output_content_and_success("call-a") - .expect("yielded cell output"); - assert!( - output - .expect("yielded cell status") - .starts_with("Script running with cell ID ") - ); - - mount_sse_once( - &server, - sse(vec![ - ev_response_created("resp-b"), - responses::ev_custom_tool_call( - "call-b", - "exec", - &format!("// @exec: {{\"yield_time_ms\": 60000}}\n{read_after_barrier}"), - ), - ev_completed("resp-b"), - ]), - ) - .await; - mount_sse_once( - &server, - sse(vec![ - ev_response_created("resp-b-done"), - ev_completed("resp-b-done"), - ]), - ) - .await; - let submitted = test - .codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "Read the skill in this turn and release the previous read.".to_string(), - text_elements: Vec::new(), - }])) - .await?; - let TurnInputSubmission::Started { - turn_id: turn_b, .. - } = submitted - else { - anyhow::bail!("expected turn B to start, got {submitted:?}"); - }; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await; - assert_eq!(events.len(), 2); - for turn_id in [&turn_a, &turn_b] { - let event = events - .iter() - .find(|event| event["event_params"]["turn_id"] == *turn_id) - .expect("each skill read should retain its originating turn"); - assert_eq!(event["skill_name"], "demo:yielded"); - } - Ok(()) -} diff --git a/codex-rs/core/tests/suite/turn_phase_trace.rs b/codex-rs/core/tests/suite/turn_phase_trace.rs index 4c8a3789..9ae999b1 100644 --- a/codex-rs/core/tests/suite/turn_phase_trace.rs +++ b/codex-rs/core/tests/suite/turn_phase_trace.rs @@ -110,7 +110,7 @@ async fn steer_joins_existing_turn_without_extending_sampling( tracing_opentelemetry::layer() .with_tracer(telemetry.tracer("turn-phase-test")) .with_filter(tracing_subscriber::filter::filter_fn( - codex_otel::OtelProvider::trace_export_filter, + codex_otel::trace_export_filter, )), ) .try_init()?; diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index 1f5520c1..11643a5c 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -260,10 +260,7 @@ deny = [ # Third-party crates that own their reqwest integration. These are not part of the # first-party migration count above. "oauth2", - "opentelemetry-http", - "opentelemetry-otlp", "rmcp", - "sentry", "webrtc-sys-build", ], reason = "new direct reqwest dependencies must use codex-http-client; temporary wrappers track migration debt" }, ] diff --git a/codex-rs/exec-server-cli/src/exec_server_telemetry.rs b/codex-rs/exec-server-cli/src/exec_server_telemetry.rs index 8b337971..47c20882 100644 --- a/codex-rs/exec-server-cli/src/exec_server_telemetry.rs +++ b/codex-rs/exec-server-cli/src/exec_server_telemetry.rs @@ -1,13 +1,11 @@ -//! Executor telemetry and shutdown coordination shared by both entry points. +//! Local executor logging and shutdown coordination shared by both entry points. use std::future::Future; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; -const DEFAULT_ANALYTICS_ENABLED: bool = false; -const DEFAULT_LOG_FILTER: &str = "error,opentelemetry_sdk=off,opentelemetry_otlp=off"; -const OTEL_SERVICE_NAME: &str = "codex-exec-server"; +const DEFAULT_LOG_FILTER: &str = "error"; pub(crate) enum ParentLifetime { Independent, @@ -20,42 +18,17 @@ pub(crate) enum ShutdownBehavior { Graceful(tokio::sync::oneshot::Sender<()>), } +/// Installs local stderr logging. Telemetry is never exported: the returned +/// executor telemetry handle records nothing. pub(crate) fn init( - config: Option<&codex_core::config::Config>, + _config: Option<&codex_core::config::Config>, ) -> (impl Send + Sync, codex_exec_server::ExecServerTelemetry) { let fmt_layer = tracing_subscriber::fmt::layer() .with_writer(std::io::stderr) .with_filter(stderr_env_filter()); - let otel = match config { - Some(config) => codex_core::otel_init::build_provider( - config, - env!("CARGO_PKG_VERSION"), - Some(OTEL_SERVICE_NAME), - DEFAULT_ANALYTICS_ENABLED, - ) - .unwrap_or_else(|error| { - eprintln!("Could not create otel exporter: {error}"); - None - }), - None => None, - }; - let provider = otel.as_ref(); - codex_core::otel_init::record_process_start(provider, OTEL_SERVICE_NAME); - - let otel_logger_layer = provider.and_then(|otel| otel.logger_layer()); - let otel_tracing_layer = provider.and_then(|otel| otel.tracing_layer()); - let telemetry = provider - .and_then(|otel| otel.metrics()) - .cloned() - .map(codex_exec_server::ExecServerTelemetry::new) - .unwrap_or_default(); - let _ = tracing_subscriber::registry() - .with(fmt_layer) - .with(otel_tracing_layer) - .with(otel_logger_layer) - .try_init(); + let _ = tracing_subscriber::registry().with(fmt_layer).try_init(); tracing::callsite::rebuild_interest_cache(); - (otel, telemetry) + ((), codex_exec_server::ExecServerTelemetry::default()) } pub(super) fn monitor_stdin_close() -> tokio::sync::oneshot::Receiver<()> { diff --git a/codex-rs/exec-server/src/client.rs b/codex-rs/exec-server/src/client.rs index 82c3f7ca..42fefcf4 100644 --- a/codex-rs/exec-server/src/client.rs +++ b/codex-rs/exec-server/src/client.rs @@ -2182,7 +2182,7 @@ mod tests { let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let _subscriber_guard = tracing::subscriber::set_default(subscriber); tracing::callsite::rebuild_interest_cache(); diff --git a/codex-rs/exec-server/src/client/route_aware_http_client.rs b/codex-rs/exec-server/src/client/route_aware_http_client.rs index 66c82bc9..d18e4b57 100644 --- a/codex-rs/exec-server/src/client/route_aware_http_client.rs +++ b/codex-rs/exec-server/src/client/route_aware_http_client.rs @@ -188,8 +188,7 @@ impl RouteAwareHttpRequestRunner { http.response.status_code = tracing::field::Empty, error.type = tracing::field::Empty, ); - let mut headers = Self::build_headers(params.headers)?; - codex_otel::inject_span_w3c_trace_headers(&request_span, &mut headers); + let headers = Self::build_headers(params.headers)?; let mut request = self.client.request(method.clone(), url).headers(headers); if let Some(body) = params.body { request = request.body(body.into_inner()); diff --git a/codex-rs/exec-server/src/client/tests/network_policy_tests.rs b/codex-rs/exec-server/src/client/tests/network_policy_tests.rs index 1b3c2053..31c7b070 100644 --- a/codex-rs/exec-server/src/client/tests/network_policy_tests.rs +++ b/codex-rs/exec-server/src/client/tests/network_policy_tests.rs @@ -322,7 +322,7 @@ async fn policy_requests_use_process_decider_and_cancel_on_unregister() { let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer_provider.tracer("exec-server-test")) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let _subscriber = tracing::subscriber::set_default(subscriber); tracing::callsite::rebuild_interest_cache(); diff --git a/codex-rs/exec-server/src/relay_noise_tests.rs b/codex-rs/exec-server/src/relay_noise_tests.rs index 2defe4bd..86e14dc9 100644 --- a/codex-rs/exec-server/src/relay_noise_tests.rs +++ b/codex-rs/exec-server/src/relay_noise_tests.rs @@ -601,7 +601,7 @@ async fn malformed_handshakes_preserve_active_streams_and_admission_recovers() - .with( tracing_opentelemetry::layer() .with_tracer(tracer_provider.tracer("exec-server-noise-test")) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let environment_task = AbortOnDropHandle::new(tokio::spawn( run_multiplexed_environment( diff --git a/codex-rs/exec-server/src/rpc.rs b/codex-rs/exec-server/src/rpc.rs index e60530fd..98dbb683 100644 --- a/codex-rs/exec-server/src/rpc.rs +++ b/codex-rs/exec-server/src/rpc.rs @@ -1066,7 +1066,7 @@ mod tests { let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer_provider.tracer("exec-server-test")) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let _subscriber = tracing::subscriber::set_default(subscriber); tracing::callsite::rebuild_interest_cache(); @@ -1401,7 +1401,7 @@ mod tests { let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let _subscriber_guard = tracing::subscriber::set_default(subscriber); tracing::callsite::rebuild_interest_cache(); diff --git a/codex-rs/exec-server/src/server.rs b/codex-rs/exec-server/src/server.rs index 29f1440d..26320930 100644 --- a/codex-rs/exec-server/src/server.rs +++ b/codex-rs/exec-server/src/server.rs @@ -9,10 +9,6 @@ mod request_dispatcher; mod session_registry; mod transport; -#[cfg(all(test, unix))] -#[path = "server/process_otel_tests.rs"] -mod process_otel_tests; - pub(crate) use handler::ExecServerHandler; pub(crate) use processor::ConnectionProcessor; pub use request_dispatcher::ConcurrentRequestLimit; diff --git a/codex-rs/exec-server/src/server/process_otel_tests.rs b/codex-rs/exec-server/src/server/process_otel_tests.rs deleted file mode 100644 index 6b1d0b34..00000000 --- a/codex-rs/exec-server/src/server/process_otel_tests.rs +++ /dev/null @@ -1,758 +0,0 @@ -//! Verifies exported lifecycle and network logs retain launch identity without private payloads. - -#![allow(clippy::expect_used)] - -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::sync::Arc; -use std::time::Duration; - -use codex_exec_server_protocol::JSONRPCMessage; -use codex_exec_server_protocol::JSONRPCRequest; -use codex_exec_server_protocol::RequestId; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_network_proxy::NetworkProxyConfig; -use codex_network_proxy::RemoteNetworkProxyConfig; -use codex_network_proxy::RemoteNetworkProxyLaunchConfig; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; -use codex_protocol::protocol::W3cTraceContext; -use codex_utils_path_uri::PathUri; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use tokio::sync::mpsc; -use tracing::Instrument; -use tracing_subscriber::prelude::*; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; - -use super::ExecServerHandler; -use super::registry::build_router; -use super::session_registry::SessionRegistry; -use crate::ExecServerRuntimeOptions; -use crate::ExecServerTelemetry; -use crate::connection::JsonRpcConnectionEvent; -use crate::discover_v2::capability_manager::CapabilityManager; -use crate::protocol::EXEC_METHOD; -use crate::protocol::EXEC_READ_METHOD; -use crate::protocol::EXEC_TERMINATE_METHOD; -use crate::protocol::InitializeParams; -use crate::protocol::ReadResponse; -use crate::rpc::RpcNotificationSender; -use crate::rpc::RpcRouter; -use crate::rpc::RpcServerOutboundMessage; -use crate::telemetry::ExecutorRegistration; - -const PRIVATE_PAYLOAD: &str = "private-process-payload"; -const TRACE_ID: &str = "11111111111111111111111111111111"; -const LAUNCH_SPANS: [&str; 2] = ["2222222222222222", "3333333333333333"]; -const THREADS: [&str; 2] = [ - "11111111-1111-4111-8111-111111111111", - "22222222-2222-4222-8222-222222222222", -]; -const CALLS: [&str; 2] = ["call-first", "call-second"]; -const LATER_TRACE: &str = "00-44444444444444444444444444444444-5555555555555555-01"; - -#[test] -fn exported_process_and_network_logs_keep_the_validated_launch_reference() { - // Keep the subscriber on the runtime's only thread, including proxy background tasks. - for (export_traces, registered) in [(false, true), (true, true), (false, false)] { - let records = exported_logs(export_traces, |runtime, _, _| { - runtime.block_on(async { - let server = TestServer::new(); - let mut handlers = Vec::new(); - let mut session_ids = Vec::new(); - for client_name in ["first-orchestrator", "second-orchestrator"] { - let (handler, session_id) = server.new_orchestrator( - client_name, registered.then_some("original"), - ).await; - handlers.push(handler); - session_ids.push(session_id); - } - let proxy = RemoteNetworkProxyLaunchConfig::new( - RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig { - enabled: true, - ..NetworkProxyConfig::default() - }).expect("proxy config"), - ); - // Unsampled incoming context must still correlate logs-only export. - let flags = if export_traces { "01" } else { "00" }; - let launches = LAUNCH_SPANS.map(|span| format!("00-{TRACE_ID}-{span}-{flags}")); - for (batch, traces) in [ - [Some(launches[0].as_str()), Some(launches[1].as_str())], - [None, Some(PRIVATE_PAYLOAD)], - ].into_iter().enumerate() { - // Process IDs are session-scoped and deliberately reused across clients. - let process_id = format!("{PRIVATE_PAYLOAD}-{batch}"); - for (index, (handler, trace)) in handlers.iter().zip(traces).enumerate() { - let mut params = process_start_params( - &process_id, - json!(["/bin/sh", "-c", "printf '%s\\n' \"$HTTP_PROXY\"; read ignored", PRIVATE_PAYLOAD]), - PathUri::from_host_native_path(std::env::current_dir().expect("cwd")).expect("cwd URI"), - ); - params["metadata"] = if batch == 0 { - process_metadata(index) - } else { - json!({"toolCallId": if index == 0 { None } else { Some("private-process-payload\n") }}) - }; - params["metadata"]["executorRegistrationId"] = json!(PRIVATE_PAYLOAD); - params["metadata"]["environmentId"] = json!(PRIVATE_PAYLOAD); - params["executorRegistrationId"] = json!(PRIVATE_PAYLOAD); - params["environmentId"] = json!(PRIVATE_PAYLOAD); - params["pipeStdin"] = json!(true); - params["networkProxy"] = json!(proxy); - request(&server.router, handler, EXEC_METHOD, params, trace).await; - } - if batch == 0 { - handlers[0].shutdown().await; - let resumed = new_handler( - &server.sessions, server.outgoing.clone(), registered.then_some("resumed"), - ); - resumed.initialize(InitializeParams { - client_name: "resumed-orchestrator".to_string(), - resume_session_id: Some(session_ids[0].clone()), - }).await.expect("resume session"); - resumed.initialized().expect("initialized resumed orchestrator"); - handlers[0] = resumed; - } - for handler in &handlers { - let output: ReadResponse = serde_json::from_value(request( - &server.router, handler, EXEC_READ_METHOD, - json!({"processId": process_id, "waitMs": 1000}), Some(LATER_TRACE), - ).await).expect("read proxy address"); - let proxy_address = String::from_utf8(output.chunks.into_iter() - .flat_map(|chunk| chunk.chunk.into_inner()).collect()).expect("UTF-8 output"); - let mut connection = tokio::net::TcpStream::connect( - proxy_address.trim().strip_prefix("http://").expect("HTTP proxy address"), - ).await.expect("connect to process proxy"); - connection.write_all(b"CONNECT 8.8.8.8:443 HTTP/1.1\r\nHost: 8.8.8.8:443\r\n\r\n") - .await.expect("request denied destination"); - let mut response = [0_u8; 256]; - let length = tokio::time::timeout(Duration::from_secs(5), connection.read(&mut response)) - .await.expect("proxy response timeout").expect("proxy response"); - assert!(String::from_utf8_lossy(&response[..length]).starts_with("HTTP/1.1 403")); - request(&server.router, handler, EXEC_TERMINATE_METHOD, - json!({"processId": process_id}), Some(LATER_TRACE)).await; - read_until_closed(&server.router, handler, &process_id).await; - } - } - server.sessions.shutdown().await; - }); - }); - let mut events = Vec::new(); - for record in &records { - let name = attribute(record, "event.name").expect("event name"); - let trace = attribute(record, "launch.trace_id"); - let span = attribute(record, "launch.span_id"); - if export_traces - && name.starts_with("codex.exec_server.process_") - && let Some(span) = span - { - assert_eq!(record["traceId"].as_str(), trace); - assert_ne!(record["spanId"].as_str().expect("native child span"), span); - } - events.push(( - name.to_string(), - trace.map(str::to_string), - span.map(str::to_string), - attribute(record, "conversation.id").map(str::to_string), - attribute(record, "tool.call_id").map(str::to_string), - attribute(record, "executor.environment_id").map(str::to_string), - attribute(record, "executor.registration_id").map(str::to_string), - )); - } - let mut expected = Vec::new(); - for (index, span) in [Some(LAUNCH_SPANS[0]), Some(LAUNCH_SPANS[1]), None, None] - .into_iter() - .enumerate() - { - for name in [ - "codex.exec_server.process_start", - "codex.exec_server.process_exit", - "codex.network_proxy.policy_decision", - ] { - expected.push(( - name.to_string(), - span.map(|_| TRACE_ID.to_string()), - span.map(str::to_string), - (index < 2).then(|| THREADS[index].to_string()), - (index < 2).then(|| CALLS[index].to_string()), - registered.then(|| "environment".to_string()), - registered.then(|| if index == 2 { "resumed" } else { "original" }.to_string()), - )); - } - } - events.sort(); - expected.sort(); - assert_eq!(events, expected); - } -} - -#[test] -fn launch_rpc_span_finishes_before_its_process_exits() { - let mut observed = None; - let records = exported_logs(/*export_traces*/ true, |runtime, otel, collector| { - runtime.block_on(async { - let server = TestServer::new(); - let (handler, _) = server - .new_orchestrator("process-span-orchestrator", Some("original")) - .await; - let launch = format!("00-{TRACE_ID}-{}-01", LAUNCH_SPANS[0]); - let mut params = process_start_params( - PRIVATE_PAYLOAD, - json!(["/bin/sh", "-c", "read ignored", PRIVATE_PAYLOAD]), - PathUri::from_host_native_path(std::env::current_dir().expect("cwd")) - .expect("cwd URI"), - ); - params["metadata"] = process_metadata(/*index*/ 0); - params["pipeStdin"] = json!(true); - request(&server.router, &handler, EXEC_METHOD, params, Some(&launch)).await; - - // Flush completed spans while the process is still waiting on its open stdin. - // The old task's in_current_span() retains the RPC span, so this snapshot lacks it. - let spans_before_exit = flushed_spans(otel, collector).await; - let running: ReadResponse = serde_json::from_value( - request( - &server.router, - &handler, - EXEC_READ_METHOD, - json!({"processId": PRIVATE_PAYLOAD, "waitMs": 0}), - Some(LATER_TRACE), - ) - .await, - ) - .expect("read running process"); - request( - &server.router, - &handler, - EXEC_TERMINATE_METHOD, - json!({"processId": PRIVATE_PAYLOAD}), - Some(LATER_TRACE), - ) - .await; - let exited = read_until_closed(&server.router, &handler, PRIVATE_PAYLOAD).await; - server.sessions.shutdown().await; - let spans_after_exit = flushed_spans(otel, collector).await; - // Finish cleanup before asserting the regression so a failure leaves no child behind. - observed = Some((running, exited, spans_before_exit, spans_after_exit)); - }); - }); - let (running, exited, spans_before_exit, spans_after_exit) = - observed.expect("process observations"); - assert_eq!( - (running.exited, running.closed, running.exit_code), - (false, false, None) - ); - let launch_spans: Vec<_> = spans_before_exit - .iter() - .filter(|span| span["name"] == EXEC_METHOD) - .collect(); - assert_eq!( - launch_spans.len(), - 1, - "process/start span must export before child exit" - ); - let launch_span = launch_spans[0]; - assert_eq!( - ( - launch_span["traceId"].as_str(), - launch_span["parentSpanId"].as_str() - ), - (Some(TRACE_ID), Some(LAUNCH_SPANS[0])) - ); - let exit_record = records - .iter() - .find(|record| attribute(record, "event.name") == Some("codex.exec_server.process_exit")) - .expect("process exit log"); - let exit_span_id = exit_record["spanId"] - .as_str() - .expect("process exit span ID"); - // ProcessMetricGuard has the same span name; select the span that emitted the exit log. - let process_spans: Vec<_> = spans_after_exit - .iter() - .filter(|span| span["spanId"].as_str() == Some(exit_span_id)) - .collect(); - assert_eq!( - process_spans.len(), - 1, - "process completion has its own span" - ); - let process_span = process_spans[0]; - assert_eq!(process_span["name"], "codex.exec_server.process"); - assert_eq!( - ( - process_span["traceId"].as_str(), - process_span["parentSpanId"].as_str() - ), - (Some(TRACE_ID), Some(LAUNCH_SPANS[0])) - ); - assert_ne!(process_span["spanId"], launch_span["spanId"]); - let mut expected_exit = - expected_process_attributes("codex.exec_server.process_exit", /*index*/ 0, "None"); - expected_exit["process.exit_code"] = - json!({"intValue": exited.exit_code.expect("exit code").to_string()}); - expected_exit["process.termination_requested"] = json!({"boolValue": true}); - assert_exported_attributes( - &records, - vec![ - expected_process_attributes( - "codex.exec_server.process_start", - /*index*/ 0, - "None", - ), - expected_exit, - ], - ); - for record in &records { - assert_eq!(record["traceId"].as_str(), Some(TRACE_ID)); - let span = if attribute(record, "event.name") == Some("codex.exec_server.process_start") { - launch_span - } else { - process_span - }; - assert_eq!(record["spanId"], span["spanId"]); - } -} - -async fn flushed_spans(otel: &OtelProvider, collector: &MockServer) -> Vec { - let provider = otel - .tracer_provider - .as_ref() - .expect("trace exporter") - .clone(); - // The collector uses this runtime, so the synchronous export flush must not block it. - tokio::time::timeout( - Duration::from_secs(5), - tokio::task::spawn_blocking(move || provider.force_flush()), - ) - .await - .expect("trace flush timeout") - .expect("trace flush task") - .expect("trace flush"); - let mut spans = Vec::new(); - for request in collector - .received_requests() - .await - .expect("exported requests") - { - let body: Value = serde_json::from_slice(&request.body).expect("OTLP JSON"); - let Some(resources) = body["resourceSpans"].as_array() else { - continue; - }; - for resource in resources { - for scope in resource["scopeSpans"].as_array().expect("scope spans") { - spans.extend(scope["spans"].as_array().expect("spans").iter().cloned()); - } - } - } - spans -} - -#[test] -fn exported_spawn_failure_keeps_launch_identity_without_outcome_or_error_text() { - let records = exported_logs(/*export_traces*/ false, |runtime, _, _| { - runtime.block_on(async { - let server = TestServer::new(); - let (handler, _) = server - .new_orchestrator("spawn-failure-orchestrator", Some("original")) - .await; - let directory = tempfile::tempdir().expect("process directory"); - let missing_executable = directory.path().join(PRIVATE_PAYLOAD); - let launch = format!("00-{TRACE_ID}-{}-00", LAUNCH_SPANS[0]); - let mut params = process_start_params( - PRIVATE_PAYLOAD, - json!([missing_executable, PRIVATE_PAYLOAD]), - PathUri::from_host_native_path(directory.path()).expect("cwd URI"), - ); - params["metadata"] = process_metadata(/*index*/ 0); - let response = - request_result(&server.router, &handler, EXEC_METHOD, params, Some(&launch)).await; - let Some(RpcServerOutboundMessage::Error { error, .. }) = response else { - panic!("missing executable must fail to spawn: {response:?}"); - }; - assert_eq!(error.code, -32603); - assert!( - !error.message.is_empty(), - "caller still receives the spawn error" - ); - server.sessions.shutdown().await; - }); - }); - assert_exported_attributes( - &records, - vec![expected_process_attributes( - "codex.exec_server.process_spawn_failed", - /*index*/ 0, - "None", - )], - ); -} - -#[cfg(target_os = "macos")] -#[test] -fn exported_sandbox_denial_keeps_launch_identity_and_separate_exit_outcome() { - let records = exported_logs(/*export_traces*/ false, |runtime, _, _| { - runtime.block_on(async { - let server = TestServer::new(); - let (handler, _) = server.new_orchestrator("sandbox-denial-orchestrator", Some("original")).await; - let directory = tempfile::tempdir().expect("process directory"); - let private_file = directory.path().join(PRIVATE_PAYLOAD); - std::fs::write(&private_file, PRIVATE_PAYLOAD).expect("write test file"); - let cwd = PathUri::from_host_native_path(directory.path()).expect("cwd URI"); - let sandbox = crate::FileSystemSandboxContext::from_permission_profile( - codex_protocol::models::PermissionProfile::read_only(), - cwd.clone(), - ); - for (index, span) in LAUNCH_SPANS.into_iter().enumerate() { - let process_id = format!("{PRIVATE_PAYLOAD}-{index}"); - let launch = format!("00-{TRACE_ID}-{span}-00"); - let argv = if index == 0 { - json!(["/bin/cat", private_file]) - } else { - // Emit private output, then attempt a real denied write. Exit 23 is produced - // by the child shell only after that write fails, not by sandbox startup. - json!(["/bin/sh", "-c", - "printf '%s' \"$PRIVATE_TEST_VALUE\"; if printf changed > \"$1\"; then exit 0; else exit 23; fi", - PRIVATE_PAYLOAD, private_file]) - }; - let mut params = process_start_params(&process_id, argv, cwd.clone()); - params["metadata"] = process_metadata(index); - params["env"]["LC_ALL"] = json!("C"); - params["sandbox"] = json!(sandbox); - let started: crate::protocol::ExecResponse = serde_json::from_value(request( - &server.router, &handler, EXEC_METHOD, params, Some(&launch), - ).await).expect("start sandboxed process"); - assert_eq!(started.sandbox_type, Some(crate::protocol::ProcessSandboxType::MacosSeatbelt)); - let output = read_until_closed(&server.router, &handler, &process_id).await; - let stdout: Vec = output.chunks.iter() - .filter(|chunk| chunk.stream == crate::protocol::ExecOutputStream::Stdout) - .flat_map(|chunk| chunk.chunk.0.iter().copied()).collect(); - assert_eq!(stdout, PRIVATE_PAYLOAD.as_bytes()); - assert_eq!((output.exit_code, output.sandbox_denied), if index == 0 { - (Some(0), false) - } else { - (Some(23), true) - }); - if index == 1 { - let stderr: Vec = output.chunks.iter() - .filter(|chunk| chunk.stream == crate::protocol::ExecOutputStream::Stderr) - .flat_map(|chunk| chunk.chunk.0.iter().copied()).collect(); - assert!(String::from_utf8_lossy(&stderr).contains("Operation not permitted")); - } - } - assert_eq!(std::fs::read(&private_file).expect("read test file"), PRIVATE_PAYLOAD.as_bytes()); - server.sessions.shutdown().await; - }); - }); - let mut expected = Vec::new(); - for index in 0..2 { - expected.push(expected_process_attributes( - "codex.exec_server.process_start", - index, - "MacosSeatbelt", - )); - let mut exited = - expected_process_attributes("codex.exec_server.process_exit", index, "MacosSeatbelt"); - exited["process.exit_code"] = json!({"intValue": if index == 0 { "0" } else { "23" }}); - exited["process.termination_requested"] = json!({"boolValue": false}); - expected.push(exited); - } - let mut denied = expected_process_attributes( - "codex.exec_server.sandbox_denied", - /*index*/ 1, - "MacosSeatbelt", - ); - denied["reason"] = json!({"stringValue": "inferred_denial"}); - expected.push(denied); - assert_exported_attributes(&records, expected); -} - -async fn read_until_closed( - router: &RpcRouter, - handler: &Arc, - process_id: &str, -) -> ReadResponse { - tokio::time::timeout(Duration::from_secs(5), async { - loop { - let output: ReadResponse = serde_json::from_value( - request( - router, - handler, - EXEC_READ_METHOD, - json!({"processId": process_id, "waitMs": 100}), - Some(LATER_TRACE), - ) - .await, - ) - .expect("read process exit"); - if output.closed { - return output; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("process exits") -} - -fn expected_process_attributes(name: &str, index: usize, sandbox: &str) -> Value { - json!({ - "event.name": {"stringValue": name}, - "launch.trace_id": {"stringValue": TRACE_ID}, - "launch.span_id": {"stringValue": LAUNCH_SPANS[index]}, - "conversation.id": {"stringValue": THREADS[index]}, - "tool.call_id": {"stringValue": CALLS[index]}, - "executor.environment_id": {"stringValue": "environment"}, - "executor.registration_id": {"stringValue": "original"}, - "sandbox.type": {"stringValue": sandbox}, - }) -} - -fn assert_exported_attributes(records: &[Value], mut expected: Vec) { - let mut actual: Vec = records - .iter() - .map(|record| { - Value::Object( - record["attributes"] - .as_array() - .expect("log attributes") - .iter() - .map(|attribute| { - ( - attribute["key"] - .as_str() - .expect("attribute key") - .to_string(), - attribute["value"].clone(), - ) - }) - .collect(), - ) - }) - .collect(); - actual.sort_by_key(Value::to_string); - expected.sort_by_key(Value::to_string); - assert_eq!(actual, expected); -} - -async fn request( - router: &RpcRouter, - handler: &Arc, - method: &str, - params: Value, - traceparent: Option<&str>, -) -> Value { - let response = request_result(router, handler, method, params, traceparent).await; - let Some(RpcServerOutboundMessage::Response { result, .. }) = response else { - panic!("request failed: {response:?}"); - }; - result -} - -async fn request_result( - router: &RpcRouter, - handler: &Arc, - method: &str, - params: Value, - traceparent: Option<&str>, -) -> Option { - let request = JSONRPCRequest { - id: RequestId::Integer(1), - method: method.to_string(), - params: Some(params), - trace: traceparent.map(|traceparent| W3cTraceContext { - traceparent: Some(traceparent.to_string()), - tracestate: None, - }), - }; - let JsonRpcConnectionEvent::QueuedRequest { - request, - request_span, - .. - } = JsonRpcConnectionEvent::message(JSONRPCMessage::Request(request)) - else { - panic!("request span") - }; - let (_, route) = router - .request_route(method) - .expect("registered request route"); - request_span.record("otel.name", method); - route(Arc::clone(handler), request) - .instrument(request_span) - .await -} - -fn attribute<'a>(record: &'a Value, key: &str) -> Option<&'a str> { - record["attributes"] - .as_array() - .expect("log attributes") - .iter() - .find(|attribute| attribute["key"] == key) - .map(|attribute| { - attribute["value"]["stringValue"] - .as_str() - .expect("string attribute") - }) -} - -fn exported_logs( - export_traces: bool, - run: impl FnOnce(&tokio::runtime::Runtime, &OtelProvider, &MockServer), -) -> Vec { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("test runtime"); - let collector = runtime.block_on(MockServer::start()); - runtime.block_on( - Mock::given(method("POST")) - .respond_with(ResponseTemplate::new(200)) - .mount(&collector), - ); - let exporter = OtelExporter::OtlpHttp { - endpoint: format!("{}/v1/logs", collector.uri()), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }; - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: "test".to_string(), - service_name: "codex-exec-server".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: std::env::current_dir().expect("cwd"), - exporter, - trace_exporter: if export_traces { - OtelExporter::OtlpHttp { - endpoint: format!("{}/v1/traces", collector.uri()), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - } - } else { - OtelExporter::None - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .expect("OTEL settings") - .expect("OTEL provider"); - let subscriber = tracing_subscriber::registry() - .with(otel.tracing_layer()) - .with(otel.logger_layer()); - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - run(&runtime, &otel, &collector); - }); - runtime - .block_on(otel.shutdown_with_timeout(Duration::from_secs(5))) - .expect("flush OTEL"); - - let mut records = Vec::new(); - for request in runtime - .block_on(collector.received_requests()) - .expect("exported requests") - { - let body: Value = serde_json::from_slice(&request.body).expect("OTLP JSON"); - let Some(resources) = body["resourceLogs"].as_array() else { - continue; - }; - assert!(!String::from_utf8_lossy(&request.body).contains(PRIVATE_PAYLOAD)); - for resource in resources { - for scope in resource["scopeLogs"].as_array().expect("scope logs") { - for record in scope["logRecords"].as_array().expect("log records") { - assert!(record["body"].is_null(), "lifecycle logs have no raw body"); - records.push(record.clone()); - } - } - } - } - records -} - -struct TestServer { - sessions: Arc, - router: RpcRouter, - outgoing: mpsc::Sender, - _notifications: mpsc::Receiver, -} - -impl TestServer { - fn new() -> Self { - let (outgoing, notifications) = mpsc::channel(/*buffer*/ 128); - Self { - sessions: SessionRegistry::new(ExecServerTelemetry::default()), - router: build_router(), - outgoing, - _notifications: notifications, - } - } - - async fn new_orchestrator( - &self, - client_name: &str, - registration: Option<&str>, - ) -> (Arc, String) { - let handler = new_handler(&self.sessions, self.outgoing.clone(), registration); - let initialized = handler - .initialize(InitializeParams { - client_name: client_name.to_string(), - resume_session_id: None, - }) - .await - .expect("initialize orchestrator"); - handler.initialized().expect("initialized orchestrator"); - (handler, initialized.session_id) - } -} - -fn process_start_params(process_id: &str, argv: Value, cwd: PathUri) -> Value { - json!({ - "processId": process_id, - "argv": argv, - "cwd": cwd, - "env": {"PRIVATE_TEST_VALUE": PRIVATE_PAYLOAD}, - "tty": false, - "arg0": null, - }) -} - -fn process_metadata(index: usize) -> Value { - json!({"threadId": THREADS[index], "toolCallId": CALLS[index]}) -} - -fn new_handler( - sessions: &Arc, - outgoing: mpsc::Sender, - registration: Option<&str>, -) -> Arc { - let mut handler = ExecServerHandler::new( - Arc::clone(sessions), - CapabilityManager::new(crate::LocalFileSystem::default()), - RpcNotificationSender::new(outgoing), - ExecServerRuntimeOptions::new( - std::env::current_exe().expect("test executable"), - /*codex_linux_sandbox_exe*/ None, - ) - .expect("runtime paths"), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ); - handler.executor_registration = registration - .and_then(|registration| { - ExecutorRegistration::new("environment".to_string(), registration.to_string()) - }) - .map(Arc::new); - Arc::new(handler) -} diff --git a/codex-rs/exec-server/src/server/request_dispatcher_tests.rs b/codex-rs/exec-server/src/server/request_dispatcher_tests.rs index 680a4bea..f6d7bc9a 100644 --- a/codex-rs/exec-server/src/server/request_dispatcher_tests.rs +++ b/codex-rs/exec-server/src/server/request_dispatcher_tests.rs @@ -93,7 +93,7 @@ fn request_span_uses_bounded_name_wire_method_and_inbound_trace_parent() { let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let trace_id = TraceId::from_hex("00000000000000000000000000000001").expect("trace id"); let parent_span_id = SpanId::from_hex("0000000000000002").expect("span id"); @@ -157,7 +157,7 @@ async fn request_queue_waits_for_dispatcher_admission_before_recording_telemetry let subscriber = tracing_subscriber::registry().with( tracing_opentelemetry::layer() .with_tracer(tracer_provider.tracer("exec-server-test")) - .with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)), + .with_filter(filter_fn(codex_otel::trace_export_filter)), ); let _subscriber = tracing::subscriber::set_default(subscriber); tracing::callsite::rebuild_interest_cache(); diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 9ec793b3..fb882e97 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -180,8 +180,7 @@ use uuid::Uuid; use crate::cli::Command as ExecCommand; use crate::event_processor::EventProcessor; -const DEFAULT_ANALYTICS_ENABLED: bool = true; -const EXEC_DEFAULT_LOG_FILTER: &str = "error,opentelemetry_sdk=off,opentelemetry_otlp=off"; +const EXEC_DEFAULT_LOG_FILTER: &str = "error"; enum InitialOperation { ForkOnly, @@ -688,36 +687,8 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result std::process::exit(1); } - let otel = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - codex_core::otel_init::build_provider( - &config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - DEFAULT_ANALYTICS_ENABLED, - ) - })) { - Ok(Ok(otel)) => otel, - Ok(Err(e)) => { - eprintln!("Could not create otel exporter: {e}"); - None - } - Err(_) => { - eprintln!("Could not create otel exporter: panicked during initialization"); - None - } - }; - codex_core::otel_init::record_process_start(otel.as_ref(), "codex_exec"); - codex_core::otel_init::install_sqlite_telemetry(otel.as_ref(), "codex_exec"); - - let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); - - let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); - - let _ = tracing_subscriber::registry() - .with(fmt_layer) - .with(otel_tracing_layer) - .with(otel_logger_layer) - .try_init(); + // Logs stay local (stderr only); telemetry is never exported. + let _ = tracing_subscriber::registry().with(fmt_layer).try_init(); let exec_span = exec_root_span(); if let Some(context) = traceparent_context_from_env() { diff --git a/codex-rs/exec/src/lib_tests.rs b/codex-rs/exec/src/lib_tests.rs index af43049b..ef0c022f 100644 --- a/codex-rs/exec/src/lib_tests.rs +++ b/codex-rs/exec/src/lib_tests.rs @@ -13,10 +13,6 @@ use opentelemetry::trace::TraceId; use opentelemetry::trace::TracerProvider as _; use opentelemetry_sdk::trace::SdkTracerProvider; use pretty_assertions::assert_eq; -use std::io; -use std::io::Write; -use std::sync::Arc; -use std::sync::Mutex; use tempfile::tempdir; use tracing_opentelemetry::OpenTelemetrySpanExt; @@ -26,61 +22,6 @@ fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync { tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer)) } -#[derive(Clone)] -struct TestLogWriter { - buffer: Arc>>, -} - -struct TestLogSink { - buffer: Arc>>, -} - -impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter { - type Writer = TestLogSink; - - fn make_writer(&'a self) -> Self::Writer { - TestLogSink { - buffer: Arc::clone(&self.buffer), - } - } -} - -impl Write for TestLogSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.buffer.lock().expect("log buffer lock").extend(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[test] -fn exec_default_stderr_filter_suppresses_otel_self_diagnostics() { - let buffer = Arc::new(Mutex::new(Vec::new())); - let writer = TestLogWriter { - buffer: Arc::clone(&buffer), - }; - let subscriber = tracing_subscriber::registry().with( - tracing_subscriber::fmt::layer() - .with_ansi(false) - .with_writer(writer) - .with_filter(EnvFilter::try_new(EXEC_DEFAULT_LOG_FILTER).expect("default filter")), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::error!(target: "opentelemetry_sdk", "telemetry export failed"); - tracing::error!(target: "opentelemetry_otlp", "telemetry request failed"); - tracing::error!(target: "codex_exec_test", "real exec error"); - }); - - let logs = String::from_utf8(buffer.lock().expect("log buffer lock").clone()).expect("utf8"); - assert!(!logs.contains("telemetry export failed")); - assert!(!logs.contains("telemetry request failed")); - assert!(logs.contains("real exec error")); -} - #[test] fn exec_root_span_can_be_parented_from_trace_context() { let subscriber = test_tracing_subscriber(); diff --git a/codex-rs/exec/tests/suite/apply_patch.rs b/codex-rs/exec/tests/suite/apply_patch.rs index 71ab2483..50a6c244 100644 --- a/codex-rs/exec/tests/suite/apply_patch.rs +++ b/codex-rs/exec/tests/suite/apply_patch.rs @@ -349,171 +349,3 @@ async fn test_apply_patch_freeform_tool() -> anyhow::Result<()> { ); Ok(()) } - -#[cfg(not(target_os = "windows"))] -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn shutdown_flushes_completed_turn_and_file_diff() -> anyhow::Result<()> { - use codex_login::AuthDotJson; - use codex_login::AuthKeyringBackendKind; - use codex_login::TokenData; - use codex_login::save_auth; - use codex_login::token_data::IdTokenInfo; - use codex_protocol::auth::AuthMode; - use core_test_support::skip_if_no_network; - use core_test_support::test_codex_exec::test_codex_exec; - use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use std::time::Duration; - use wiremock::Mock; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - - skip_if_no_network!(Ok(())); - - let test = test_codex_exec(); - let run_dir = test.cwd_path(); - assert!( - std::process::Command::new("git") - .args(["init", "--quiet"]) - .current_dir(run_dir) - .status() - .context("initialize test git repository")? - .success() - ); - assert!( - std::process::Command::new("git") - .args([ - "remote", - "add", - "origin", - "https://github.com/test-org/turn-profile-test.git", - ]) - .current_dir(run_dir) - .status() - .context("add test git remote")? - .success() - ); - save_auth( - test.home_path(), - &AuthDotJson { - auth_mode: Some(AuthMode::Chatgpt), - openai_api_key: None, - tokens: Some(TokenData { - id_token: IdTokenInfo { - raw_jwt: "header.eyJhbGciOiJub25lIn0.eyJzdWIiOiJ1c2VyLTEyMyJ9.".to_string(), - ..Default::default() - }, - access_token: "test-access-token".to_string(), - refresh_token: "test-refresh-token".to_string(), - oauth_provenance: None, - login_owner_id: None, - account_id: None, - }), - last_refresh: None, - agent_identity: None, - personal_access_token: None, - bedrock_api_key: None, - bedrock_access_keys: None, - }, - codex_login::AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - )?; - - let server = start_mock_server().await; - let deliveries = Arc::new(AtomicUsize::new(0)); - let completed_deliveries = Arc::clone(&deliveries); - Mock::given(method("POST")) - .and(|request: &wiremock::Request| request.url.path().ends_with("events")) - .respond_with(move |_request: &wiremock::Request| { - // A request is counted only once its delayed handler has completed. - std::thread::sleep(Duration::from_millis(750)); - completed_deliveries.fetch_add(1, Ordering::Release); - ResponseTemplate::new(200) - }) - .expect(3..) - .mount(&server) - .await; - mount_sse_sequence( - &server, - vec![ - sse(vec![ - ev_apply_patch_custom_tool_call( - "request_0", - "*** Begin Patch\n*** Add File: flushed.md\n+persist this line\n*** End Patch", - ), - ev_completed("request_0"), - ]), - sse(vec![ev_completed("request_1")]), - ], - ) - .await; - - test.cmd_with_server(&server) - .env_remove("CODEX_API_KEY") - .env_remove("CODEX_ANALYTICS_EVENTS_CAPTURE_FILE") - .arg("--skip-git-repo-check") - .arg("-s") - .arg("danger-full-access") - .arg("-c") - .arg("model_provider=\"test\"") - .arg("-c") - .arg(format!( - "model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}", - format!("{}/v1", server.uri()) - )) - .arg("-c") - .arg("analytics.enabled=true") - .arg("-c") - .arg(format!("chatgpt_base_url={}", server.uri())) - .arg("write the file") - .assert() - .success(); - - let persisted = std::fs::read_to_string(run_dir.join("flushed.md")) - .context("read file written by apply_patch")?; - assert_eq!(persisted, "persist this line\n"); - - let requests = server - .received_requests() - .await - .context("read analytics requests")?; - let request_paths = requests - .iter() - .map(|request| request.url.path().to_string()) - .collect::>(); - let event_types = requests - .iter() - .filter(|request| request.url.path().ends_with("events")) - .flat_map(|request| { - serde_json::from_slice::(&request.body) - .ok() - .and_then(|body| { - body.get("events") - .and_then(serde_json::Value::as_array) - .cloned() - }) - .unwrap_or_default() - .into_iter() - .filter_map(|event| event["event_type"].as_str().map(str::to_owned)) - .collect::>() - }) - .collect::>(); - assert!( - deliveries.load(Ordering::Acquire) >= 3, - "the runtime exited before the delayed analytics deliveries completed (completed={}, events={event_types:?}, paths={request_paths:?})", - deliveries.load(Ordering::Acquire) - ); - assert!( - event_types.iter().any(|event| event == "codex_turn_event"), - "no completed event was delivered; request paths: {request_paths:?}" - ); - assert!( - event_types - .iter() - .any(|event| event == "codex_accepted_line_fingerprints"), - "no accepted-line event was delivered; request paths: {request_paths:?}" - ); - - Ok(()) -} diff --git a/codex-rs/ext/goal/Cargo.toml b/codex-rs/ext/goal/Cargo.toml index 3939da1a..723d712e 100644 --- a/codex-rs/ext/goal/Cargo.toml +++ b/codex-rs/ext/goal/Cargo.toml @@ -14,7 +14,6 @@ doctest = false workspace = true [dependencies] -codex-analytics = { workspace = true } codex-core = { workspace = true } codex-extension-api = { workspace = true } codex-otel = { workspace = true } diff --git a/codex-rs/ext/goal/src/analytics.rs b/codex-rs/ext/goal/src/analytics.rs deleted file mode 100644 index 82d34962..00000000 --- a/codex-rs/ext/goal/src/analytics.rs +++ /dev/null @@ -1,77 +0,0 @@ -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::CodexGoalEvent; -use codex_analytics::GoalEventKind; - -#[derive(Clone)] -pub(crate) struct GoalAnalytics { - client: AnalyticsEventsClient, -} - -pub(crate) enum GoalEventAttribution<'a> { - Turn(&'a str), - NoTurn, -} - -impl GoalAnalytics { - pub(crate) fn new(client: AnalyticsEventsClient) -> Self { - Self { client } - } - - pub(crate) fn created( - &self, - goal: &codex_state::ThreadGoal, - attribution: GoalEventAttribution<'_>, - ) { - self.track(goal, attribution, GoalEventKind::Created); - } - - pub(crate) fn usage_accounted( - &self, - goal: &codex_state::ThreadGoal, - attribution: GoalEventAttribution<'_>, - ) { - self.track(goal, attribution, GoalEventKind::UsageAccounted); - } - - pub(crate) fn status_changed( - &self, - goal: &codex_state::ThreadGoal, - previous_status: Option, - attribution: GoalEventAttribution<'_>, - ) { - if previous_status.is_some_and(|status| status != goal.status) { - self.track(goal, attribution, GoalEventKind::StatusChanged); - } - } - - pub(crate) fn cleared(&self, goal: &codex_state::ThreadGoal) { - self.track(goal, GoalEventAttribution::NoTurn, GoalEventKind::Cleared); - } - - fn track( - &self, - goal: &codex_state::ThreadGoal, - attribution: GoalEventAttribution<'_>, - event_kind: GoalEventKind, - ) { - let (cumulative_tokens_accounted, cumulative_time_accounted_seconds) = match event_kind { - GoalEventKind::UsageAccounted => (Some(goal.tokens_used), Some(goal.time_used_seconds)), - GoalEventKind::Created | GoalEventKind::StatusChanged | GoalEventKind::Cleared => { - (None, None) - } - }; - self.client.track_goal_event(CodexGoalEvent { - thread_id: goal.thread_id.to_string(), - turn_id: match attribution { - GoalEventAttribution::Turn(turn_id) => Some(turn_id.to_string()), - GoalEventAttribution::NoTurn => None, - }, - goal_id: goal.goal_id.clone(), - event_kind, - goal_status: goal.status, - has_token_budget: goal.token_budget.is_some(), - cumulative_tokens_accounted, - cumulative_time_accounted_seconds, - }); - } -} diff --git a/codex-rs/ext/goal/src/extension.rs b/codex-rs/ext/goal/src/extension.rs index 0f2f07f8..d023ab4d 100644 --- a/codex-rs/ext/goal/src/extension.rs +++ b/codex-rs/ext/goal/src/extension.rs @@ -1,7 +1,6 @@ use std::sync::Arc; use std::sync::Weak; -use codex_analytics::AnalyticsEventsClient; use codex_core::ThreadManager; use codex_core::TurnStartOptions; use codex_extension_api::ConfigContributor; @@ -38,7 +37,6 @@ use codex_protocol::protocol::TokenUsageInfo; use crate::accounting::BudgetLimitedGoalDisposition; use crate::accounting::GoalAccountingState; -use crate::analytics::GoalAnalytics; use crate::api::GoalService; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; @@ -59,7 +57,6 @@ pub struct GoalExtensionConfig { #[derive(Clone)] pub struct GoalExtension { state_dbs: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, thread_manager: Weak, @@ -76,7 +73,6 @@ impl std::fmt::Debug for GoalExtension { impl GoalExtension { pub(crate) fn new_with_host_capabilities( state_dbs: Arc, - analytics_events_client: AnalyticsEventsClient, event_sink: Arc, metrics_client: Option, thread_manager: Weak, @@ -85,7 +81,6 @@ impl GoalExtension { ) -> Self { Self { state_dbs, - analytics: GoalAnalytics::new(analytics_events_client), event_emitter: GoalEventEmitter::new(event_sink), metrics: GoalMetrics::new(metrics_client), thread_manager, @@ -149,7 +144,6 @@ where self.thread_manager.clone(), accounting_state, GoalRuntimeConfig { - analytics: self.analytics.clone(), enabled, tools_available_for_thread, tools_visible_for_thread, @@ -578,7 +572,6 @@ where runtime.thread_id(), Arc::clone(&self.state_dbs), runtime.accounting_state(), - self.analytics.clone(), self.event_emitter.clone(), self.metrics.clone(), ), @@ -586,7 +579,6 @@ where &runtime, self.thread_manager.clone(), Arc::clone(&self.state_dbs), - self.analytics.clone(), self.event_emitter.clone(), self.metrics.clone(), max_goal_token_budget, @@ -595,7 +587,6 @@ where runtime.thread_id(), Arc::clone(&self.state_dbs), runtime.accounting_state(), - self.analytics.clone(), self.event_emitter.clone(), self.metrics.clone(), ), @@ -613,7 +604,6 @@ where pub fn install_with_backend( registry: &mut ExtensionRegistryBuilder, state_dbs: Arc, - analytics_events_client: AnalyticsEventsClient, metrics_client: Option, thread_manager: Weak, goal_service: Arc, @@ -623,7 +613,6 @@ pub fn install_with_backend( { let extension = Arc::new(GoalExtension::new_with_host_capabilities( state_dbs, - analytics_events_client, registry.event_sink(), metrics_client, thread_manager, diff --git a/codex-rs/ext/goal/src/lib.rs b/codex-rs/ext/goal/src/lib.rs index ccd091af..bb640c6c 100644 --- a/codex-rs/ext/goal/src/lib.rs +++ b/codex-rs/ext/goal/src/lib.rs @@ -1,7 +1,6 @@ //! Extension crate for the `/goal` feature. mod accounting; -mod analytics; mod api; mod events; mod extension; diff --git a/codex-rs/ext/goal/src/runtime.rs b/codex-rs/ext/goal/src/runtime.rs index e966119b..213b9e01 100644 --- a/codex-rs/ext/goal/src/runtime.rs +++ b/codex-rs/ext/goal/src/runtime.rs @@ -12,8 +12,6 @@ use codex_protocol::protocol::ThreadGoal; use crate::accounting::BudgetLimitedGoalDisposition; use crate::accounting::GoalAccountingState; -use crate::analytics::GoalAnalytics; -use crate::analytics::GoalEventAttribution; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; use crate::steering::continuation_request; @@ -28,7 +26,6 @@ pub struct GoalRuntimeHandle { } pub(crate) struct GoalRuntimeConfig { - pub(crate) analytics: GoalAnalytics, pub(crate) enabled: bool, pub(crate) tools_available_for_thread: bool, pub(crate) tools_visible_for_thread: bool, @@ -45,7 +42,6 @@ pub(crate) enum ActiveGoalStopReason { struct GoalRuntimeInner { thread_id: ThreadId, state_dbs: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, thread_manager: Weak, @@ -99,7 +95,6 @@ impl GoalRuntimeHandle { inner: Arc::new(GoalRuntimeInner { thread_id, state_dbs, - analytics: config.analytics, event_emitter, metrics, thread_manager, @@ -201,9 +196,6 @@ impl GoalRuntimeHandle { .is_some_and(|previous_goal| previous_goal.goal_id != goal.goal_id); if previous_goal.is_none() || replaced_existing_goal { self.inner.metrics.record_created(); - self.inner - .analytics - .created(&goal, GoalEventAttribution::NoTurn); } let previous_status = previous_goal .as_ref() @@ -214,9 +206,6 @@ impl GoalRuntimeHandle { self.inner .metrics .record_terminal_if_status_changed(previous_status, &goal); - self.inner - .analytics - .status_changed(&goal, previous_status, GoalEventAttribution::NoTurn); let objective_changed = previous_goal.as_ref().is_some_and(|previous_goal| { !replaced_existing_goal && previous_goal.objective != goal.objective }); @@ -255,13 +244,11 @@ impl GoalRuntimeHandle { pub async fn apply_external_goal_clear( &self, - goal: codex_state::ThreadGoal, + _goal: codex_state::ThreadGoal, ) -> Result<(), String> { if !self.is_enabled() { return Ok(()); } - - self.inner.analytics.cleared(&goal); self.inner.accounting_state.clear_active_goal(); Ok(()) } @@ -392,11 +379,6 @@ impl GoalRuntimeHandle { self.inner .metrics .record_terminal_if_status_changed(previous_status, &goal); - self.inner.analytics.status_changed( - &goal, - previous_status, - GoalEventAttribution::Turn(turn_id), - ); self.inner.accounting_state.clear_active_goal(); let goal = protocol_goal_from_state(goal); self.inner.event_emitter.thread_goal_updated( @@ -581,14 +563,6 @@ impl GoalRuntimeHandle { self.inner .metrics .record_terminal_if_status_changed(previous_status, &goal); - self.inner - .analytics - .usage_accounted(&goal, GoalEventAttribution::Turn(turn_id)); - self.inner.analytics.status_changed( - &goal, - previous_status, - GoalEventAttribution::Turn(turn_id), - ); accounting.mark_progress_accounted_for_status( turn_id, &snapshot, @@ -643,14 +617,6 @@ impl GoalRuntimeHandle { self.inner .metrics .record_terminal_if_status_changed(previous_status, &goal); - self.inner - .analytics - .usage_accounted(&goal, GoalEventAttribution::NoTurn); - self.inner.analytics.status_changed( - &goal, - previous_status, - GoalEventAttribution::NoTurn, - ); accounting.mark_idle_progress_accounted_for_status( &snapshot, goal.status, diff --git a/codex-rs/ext/goal/src/tool.rs b/codex-rs/ext/goal/src/tool.rs index 85e7433c..b069fd52 100644 --- a/codex-rs/ext/goal/src/tool.rs +++ b/codex-rs/ext/goal/src/tool.rs @@ -18,8 +18,6 @@ use serde::Serialize; use crate::accounting::BudgetLimitedGoalDisposition; use crate::accounting::GoalAccountingState; -use crate::analytics::GoalAnalytics; -use crate::analytics::GoalEventAttribution; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; use crate::runtime::GoalRuntimeHandle; @@ -38,7 +36,6 @@ pub(crate) struct GoalToolExecutor { thread_id: ThreadId, state_db: Arc, accounting_state: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, max_goal_token_budget: Option, @@ -83,7 +80,6 @@ impl GoalToolExecutor { thread_id: ThreadId, state_db: Arc, accounting_state: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, ) -> Self { @@ -93,7 +89,6 @@ impl GoalToolExecutor { thread_id, state_db, accounting_state, - analytics, event_emitter, metrics, max_goal_token_budget: None, @@ -104,7 +99,6 @@ impl GoalToolExecutor { runtime: &GoalRuntimeHandle, thread_manager: Weak, state_db: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, max_goal_token_budget: Option, @@ -115,7 +109,6 @@ impl GoalToolExecutor { thread_id: runtime.thread_id(), state_db, accounting_state: runtime.accounting_state(), - analytics, event_emitter, metrics, max_goal_token_budget, @@ -126,7 +119,6 @@ impl GoalToolExecutor { thread_id: ThreadId, state_db: Arc, accounting_state: Arc, - analytics: GoalAnalytics, event_emitter: GoalEventEmitter, metrics: GoalMetrics, ) -> Self { @@ -136,7 +128,6 @@ impl GoalToolExecutor { thread_id, state_db, accounting_state, - analytics, event_emitter, metrics, max_goal_token_budget: None, @@ -253,10 +244,6 @@ impl GoalToolExecutor { .await; } self.metrics.record_created(); - self.analytics.created( - &goal, - GoalEventAttribution::Turn(invocation.turn_id.as_str()), - ); let goal = protocol_goal_from_state(goal); self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone()); goal_response(Some(goal), CompletionBudgetReport::Omit) @@ -317,11 +304,6 @@ impl GoalToolExecutor { })?; self.metrics .record_terminal_if_status_changed(previous_status, &goal); - self.analytics.status_changed( - &goal, - previous_status, - GoalEventAttribution::Turn(invocation.turn_id.as_str()), - ); let goal = protocol_goal_from_state(goal); let turn_id = self.accounting_state.clear_current_turn_goal(); self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone()); @@ -387,13 +369,6 @@ impl GoalToolExecutor { codex_state::GoalAccountingOutcome::Updated(goal) => { self.metrics .record_terminal_if_status_changed(previous_status, &goal); - self.analytics - .usage_accounted(&goal, GoalEventAttribution::Turn(turn_id.as_str())); - self.analytics.status_changed( - &goal, - previous_status, - GoalEventAttribution::Turn(turn_id.as_str()), - ); self.accounting_state.mark_progress_accounted_for_status( turn_id.as_str(), &snapshot, diff --git a/codex-rs/ext/goal/tests/goal_extension_backend.rs b/codex-rs/ext/goal/tests/goal_extension_backend.rs index 8faa045d..c84aeffd 100644 --- a/codex-rs/ext/goal/tests/goal_extension_backend.rs +++ b/codex-rs/ext/goal/tests/goal_extension_backend.rs @@ -8,7 +8,6 @@ use std::sync::PoisonError; use std::sync::Weak; use std::time::Duration; -use codex_analytics::AnalyticsEventsClient; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionEventSink; use codex_extension_api::ExtensionRegistryBuilder; @@ -1658,7 +1657,6 @@ async fn installed_tools_with_start( install_with_backend( &mut builder, runtime, - AnalyticsEventsClient::disabled(), /*metrics_client*/ None, Weak::new(), goal_service, @@ -1715,7 +1713,6 @@ impl GoalExtensionHarness { install_with_backend( &mut builder, runtime, - AnalyticsEventsClient::disabled(), /*metrics_client*/ None, Weak::new(), Arc::clone(&goal_service), diff --git a/codex-rs/ext/guardian-reviewer/Cargo.toml b/codex-rs/ext/guardian-reviewer/Cargo.toml index c6adf40e..adbe1695 100644 --- a/codex-rs/ext/guardian-reviewer/Cargo.toml +++ b/codex-rs/ext/guardian-reviewer/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] anyhow = { workspace = true } -codex-analytics = { workspace = true } codex-context-fragments = { workspace = true } codex-extension-api = { workspace = true } codex-features = { workspace = true } diff --git a/codex-rs/ext/guardian-reviewer/src/approval_request.rs b/codex-rs/ext/guardian-reviewer/src/approval_request.rs index 69c9d411..ae529623 100644 --- a/codex-rs/ext/guardian-reviewer/src/approval_request.rs +++ b/codex-rs/ext/guardian-reviewer/src/approval_request.rs @@ -1,7 +1,7 @@ //! Owns Guardian approval-request data, classification, and assessment/reporting mappings. //! Request debug output excludes action arguments, which may contain credentials. -use codex_analytics::GuardianReviewedAction; +use crate::GuardianReviewedAction; use codex_protocol::approvals::GuardianAssessmentAction; use codex_protocol::approvals::GuardianCommandSource; use codex_protocol::approvals::NetworkApprovalProtocol; diff --git a/codex-rs/ext/guardian-reviewer/src/completion.rs b/codex-rs/ext/guardian-reviewer/src/completion.rs index 4a355487..c19abe50 100644 --- a/codex-rs/ext/guardian-reviewer/src/completion.rs +++ b/codex-rs/ext/guardian-reviewer/src/completion.rs @@ -1,9 +1,9 @@ //! Converts reviewer outcomes into decisions and reports. The host publishes these //! reports and applies them only to the action whose evidence was reviewed. -use codex_analytics::GuardianReviewAnalyticsResult; -use codex_analytics::GuardianReviewDecision; -use codex_analytics::GuardianReviewTerminalStatus; +use crate::GuardianReviewDecision; +use crate::GuardianReviewDetails; +use crate::GuardianReviewTerminalStatus; use codex_prompts::ResolvedModelMessages; use codex_prompts::render_guardian_rejection; use codex_protocol::openai_models::ModelInfo; @@ -31,7 +31,7 @@ pub struct ReviewCompletion { /// Absent for actions reviewed without an action-specific client report. pub event: Option, pub warning: Option, - pub analytics: GuardianReviewAnalyticsResult, + pub details: GuardianReviewDetails, /// Only completed assessments may enter the evidence cache or count as policy denials. pub assessment_outcome: Option, } @@ -41,7 +41,7 @@ pub fn complete_review( model: &ModelInfo, require_guardian: bool, mut event: Option, - mut analytics: GuardianReviewAnalyticsResult, + mut details: GuardianReviewDetails, ) -> ReviewCompletion { let completed_assessment = match &outcome { GuardianReviewOutcome::Completed(assessment) => Some(assessment.outcome), @@ -54,43 +54,43 @@ pub fn complete_review( event.decision_source = None; event.rationale = Some("Approved using a current low-risk async score.".to_owned()); } - analytics.decision = GuardianReviewDecision::Approved; - analytics.terminal_status = GuardianReviewTerminalStatus::Approved; - analytics.failure_reason = None; + details.decision = GuardianReviewDecision::Approved; + details.terminal_status = GuardianReviewTerminalStatus::Approved; + details.failure_reason = None; return ReviewCompletion { decision: Some(ReviewDecision::Approved), event, warning: None, - analytics, + details, assessment_outcome: None, }; } GuardianReviewOutcome::Completed(assessment) => { let approved = matches!(assessment.outcome, GuardianAssessmentOutcome::Allow); - analytics.decision = if approved { + details.decision = if approved { GuardianReviewDecision::Approved } else { GuardianReviewDecision::Denied }; - analytics.terminal_status = if approved { + details.terminal_status = if approved { GuardianReviewTerminalStatus::Approved } else { GuardianReviewTerminalStatus::Denied }; - analytics.failure_reason = None; - analytics.risk_level = Some(assessment.risk_level); - analytics.user_authorization = Some(assessment.user_authorization); - analytics.outcome = Some(assessment.outcome); + details.failure_reason = None; + details.risk_level = Some(assessment.risk_level); + details.user_authorization = Some(assessment.user_authorization); + details.outcome = Some(assessment.outcome); assessment } GuardianReviewOutcome::Error(error) => { - analytics.failure_reason = Some(error.failure_reason()); + details.failure_reason = Some(error.failure_reason()); match error { GuardianReviewError::InputBudgetExceeded if !require_guardian => { let rationale = format!("Automatic approval review failed: {INPUT_BUDGET_MESSAGE}"); - analytics.decision = GuardianReviewDecision::Aborted; - analytics.terminal_status = GuardianReviewTerminalStatus::Aborted; + details.decision = GuardianReviewDecision::Aborted; + details.terminal_status = GuardianReviewTerminalStatus::Aborted; if let Some(event) = event.as_mut() { event.status = GuardianAssessmentStatus::Aborted; event.rationale = Some(rationale.clone()); @@ -99,14 +99,14 @@ pub fn complete_review( decision: None, event, warning: Some(rationale), - analytics, + details, assessment_outcome: None, }; } GuardianReviewError::Timeout => { let rationale = "Automatic approval review timed out while evaluating the requested approval.".to_string(); - analytics.decision = GuardianReviewDecision::Denied; - analytics.terminal_status = GuardianReviewTerminalStatus::TimedOut; + details.decision = GuardianReviewDecision::Denied; + details.terminal_status = GuardianReviewTerminalStatus::TimedOut; if let Some(event) = event.as_mut() { event.status = GuardianAssessmentStatus::TimedOut; event.rationale = Some(rationale.clone()); @@ -115,13 +115,13 @@ pub fn complete_review( decision: Some(ReviewDecision::TimedOut), event, warning: Some(rationale), - analytics, + details, assessment_outcome: None, }; } GuardianReviewError::Cancelled => { - analytics.decision = GuardianReviewDecision::Aborted; - analytics.terminal_status = GuardianReviewTerminalStatus::Aborted; + details.decision = GuardianReviewDecision::Aborted; + details.terminal_status = GuardianReviewTerminalStatus::Aborted; if let Some(event) = event.as_mut() { event.status = GuardianAssessmentStatus::Aborted; } @@ -129,7 +129,7 @@ pub fn complete_review( decision: Some(ReviewDecision::Abort), event, warning: None, - analytics, + details, assessment_outcome: None, }; } @@ -150,8 +150,8 @@ pub fn complete_review( "guardian review failed" } }; - analytics.decision = GuardianReviewDecision::Denied; - analytics.terminal_status = GuardianReviewTerminalStatus::FailedClosed; + details.decision = GuardianReviewDecision::Denied; + details.terminal_status = GuardianReviewTerminalStatus::FailedClosed; let rationale = format!("Automatic approval review failed: {message}"); // Keep the existing blocked status for client compatibility. if let Some(event) = event.as_mut() { @@ -164,7 +164,7 @@ pub fn complete_review( ))), event, warning: Some(rationale), - analytics, + details, assessment_outcome: None, }; } @@ -214,7 +214,7 @@ pub fn complete_review( decision: Some(decision), event, warning: Some(warning), - analytics, + details, assessment_outcome: completed_assessment, } } diff --git a/codex-rs/ext/guardian-reviewer/src/execution.rs b/codex-rs/ext/guardian-reviewer/src/execution.rs index 4a015397..3ba0a001 100644 --- a/codex-rs/ext/guardian-reviewer/src/execution.rs +++ b/codex-rs/ext/guardian-reviewer/src/execution.rs @@ -6,8 +6,8 @@ use crate::ReviewDeadline; use std::future::Future; use std::time::Duration; +use crate::GuardianReviewDetails; use anyhow::anyhow; -use codex_analytics::GuardianReviewAnalyticsResult; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -71,7 +71,7 @@ pub async fn wait_for_guardian_review( expected_turn_id: &str, deadline: ReviewDeadline, external_cancel: Option<&CancellationToken>, - analytics_result: &mut GuardianReviewAnalyticsResult, + details: &mut GuardianReviewDetails, ) -> ReviewTurnResult { let timeout = deadline.wait(); tokio::pin!(timeout); @@ -117,7 +117,7 @@ pub async fn wait_for_guardian_review( } Ok(event) => match event.msg { EventMsg::TurnComplete(turn_complete) => { - analytics_result.time_to_first_token_ms = turn_complete + details.time_to_first_token_ms = turn_complete .time_to_first_token_ms .and_then(|ms| u64::try_from(ms).ok()); if turn_complete.last_agent_message.is_none() diff --git a/codex-rs/ext/guardian-reviewer/src/lib.rs b/codex-rs/ext/guardian-reviewer/src/lib.rs index d8033587..712567da 100644 --- a/codex-rs/ext/guardian-reviewer/src/lib.rs +++ b/codex-rs/ext/guardian-reviewer/src/lib.rs @@ -41,6 +41,17 @@ mod reporting; mod retry; mod review; mod review_action; +mod review_result; +pub use review_result::GuardianAdditionalPermissions; +pub use review_result::GuardianApprovalRequestSource; +pub use review_result::GuardianReviewDecision; +pub use review_result::GuardianReviewDetails; +pub use review_result::GuardianReviewFailureReason; +pub use review_result::GuardianReviewSessionDetails; +pub use review_result::GuardianReviewSessionKind; +pub use review_result::GuardianReviewTerminalStatus; +pub use review_result::GuardianReviewedAction; +pub use review_result::now_unix_millis; mod review_evidence; mod review_state; pub use review_state::CheckpointRecovery; diff --git a/codex-rs/ext/guardian-reviewer/src/metrics.rs b/codex-rs/ext/guardian-reviewer/src/metrics.rs index 9bed7e42..85b45986 100644 --- a/codex-rs/ext/guardian-reviewer/src/metrics.rs +++ b/codex-rs/ext/guardian-reviewer/src/metrics.rs @@ -3,13 +3,13 @@ use std::time::Duration; -use codex_analytics::GuardianApprovalRequestSource; -use codex_analytics::GuardianReviewAnalyticsResult; -use codex_analytics::GuardianReviewDecision; -use codex_analytics::GuardianReviewFailureReason; -use codex_analytics::GuardianReviewSessionKind; -use codex_analytics::GuardianReviewTerminalStatus; -use codex_analytics::GuardianReviewedAction; +use crate::GuardianApprovalRequestSource; +use crate::GuardianReviewDecision; +use crate::GuardianReviewDetails; +use crate::GuardianReviewFailureReason; +use crate::GuardianReviewSessionKind; +use crate::GuardianReviewTerminalStatus; +use crate::GuardianReviewedAction; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_otel::GUARDIAN_REVIEW_COUNT_METRIC; use codex_otel::GUARDIAN_REVIEW_DURATION_METRIC; @@ -38,7 +38,7 @@ pub fn token_usage_delta(start: &TokenUsage, end: &TokenUsage) -> TokenUsage { pub(crate) fn emit_guardian_review_metrics( session_telemetry: &SessionTelemetry, - result: &GuardianReviewAnalyticsResult, + result: &GuardianReviewDetails, approval_request_source: GuardianApprovalRequestSource, reviewed_action: &GuardianReviewedAction, elapsed: Duration, @@ -129,7 +129,7 @@ fn emit_guardian_token_usage_histograms( } fn guardian_review_metric_tags( - result: &GuardianReviewAnalyticsResult, + result: &GuardianReviewDetails, approval_request_source: GuardianApprovalRequestSource, reviewed_action: &GuardianReviewedAction, ) -> Vec<(&'static str, String)> { @@ -469,7 +469,7 @@ mod tests { expected_mcp_tags: BTreeMap, ) { let session_telemetry = test_session_telemetry(); - let result = GuardianReviewAnalyticsResult { + let result = GuardianReviewDetails { attempt_count: 2, decision: GuardianReviewDecision::Approved, terminal_status: GuardianReviewTerminalStatus::Approved, @@ -491,7 +491,7 @@ mod tests { codex_rollout_budget_units: None, }), time_to_first_token_ms: Some(123), - ..GuardianReviewAnalyticsResult::without_session() + ..GuardianReviewDetails::without_session() }; emit_guardian_review_metrics( @@ -620,7 +620,7 @@ mod tests { ), retry_at: Some(start + Duration::from_secs(2)), }), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), None::<()>, ) }, diff --git a/codex-rs/ext/guardian-reviewer/src/outcome.rs b/codex-rs/ext/guardian-reviewer/src/outcome.rs index 612dcaea..4d89304a 100644 --- a/codex-rs/ext/guardian-reviewer/src/outcome.rs +++ b/codex-rs/ext/guardian-reviewer/src/outcome.rs @@ -2,7 +2,7 @@ //! completed assessments from failures without assigning risk to errors. use crate::GuardianAssessment; -use codex_analytics::GuardianReviewFailureReason; +use crate::GuardianReviewFailureReason; use codex_protocol::protocol::CodexErrorInfo; use tokio::time::Instant; diff --git a/codex-rs/ext/guardian-reviewer/src/pool.rs b/codex-rs/ext/guardian-reviewer/src/pool.rs index 5c3a2db1..5368cf86 100644 --- a/codex-rs/ext/guardian-reviewer/src/pool.rs +++ b/codex-rs/ext/guardian-reviewer/src/pool.rs @@ -10,8 +10,8 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; -use codex_analytics::GuardianReviewAnalyticsResult; -use codex_analytics::GuardianReviewSessionKind; +use crate::GuardianReviewDetails; +use crate::GuardianReviewSessionKind; use codex_extension_api::ExtensionFuture; use tokio::sync::Mutex; use tokio::sync::Semaphore; @@ -68,7 +68,7 @@ pub trait ReviewerRequest: Send + Sync { pub struct ReviewSessionResult { pub outcome: GuardianReviewSessionOutcome, pub disposition: SessionDisposition, - pub analytics: GuardianReviewAnalyticsResult, + pub details: GuardianReviewDetails, } /// How the pool may reuse a session and its committed history after an attempt. @@ -184,7 +184,7 @@ impl ReviewerPool { pub async fn review( &self, request: R, - ) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult) + ) -> (GuardianReviewSessionOutcome, GuardianReviewDetails) where R: ReviewerRequest, { @@ -242,11 +242,11 @@ impl ReviewerPool { Ok(Err(error)) => { return ( GuardianReviewSessionOutcome::PromptBuildFailed(error), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); } Err(outcome) => { - return (outcome, GuardianReviewAnalyticsResult::without_session()); + return (outcome, GuardianReviewDetails::without_session()); } }; let review_lock = Arc::new(Semaphore::new(/*permits*/ 1)); @@ -256,7 +256,7 @@ impl ReviewerPool { Err(error) => { return ( GuardianReviewSessionOutcome::PromptBuildFailed(error.into()), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); } }; @@ -270,14 +270,14 @@ impl ReviewerPool { } (state.as_ref().cloned(), context, reserved_permit) } - Err(outcome) => return (outcome, GuardianReviewAnalyticsResult::without_session()), + Err(outcome) => return (outcome, GuardianReviewDetails::without_session()), }; let Some(trunk) = trunk else { return ( GuardianReviewSessionOutcome::Completed(Err(anyhow::anyhow!( "guardian review session was not available after spawn" ))), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); }; if trunk.session.context() != &context || (requires_fresh_session && !spawned_trunk) { @@ -304,7 +304,7 @@ impl ReviewerPool { let ReviewSessionResult { outcome, disposition, - analytics, + details, } = request.run(&trunk.session, kind).await; if disposition == SessionDisposition::Rollback { // Publish retirement before releasing the permit. Concurrent reviews only @@ -326,7 +326,7 @@ impl ReviewerPool { state.take(); } } - (outcome, analytics) + (outcome, details) } /// Reviews in a temporary session without reading or changing the reusable reviewer. @@ -334,7 +334,7 @@ impl ReviewerPool { pub async fn review_isolated( &self, request: &R, - ) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult) + ) -> (GuardianReviewSessionOutcome, GuardianReviewDetails) where R: ReviewerRequest, { @@ -347,7 +347,7 @@ impl ReviewerPool { request: &R, context: S::Context, snapshot: Option, - ) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult) + ) -> (GuardianReviewSessionOutcome, GuardianReviewDetails) where R: ReviewerRequest, { @@ -370,17 +370,17 @@ impl ReviewerPool { Ok(Err(error)) => { return ( GuardianReviewSessionOutcome::PromptBuildFailed(error), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), ); } - Err(outcome) => return (outcome, GuardianReviewAnalyticsResult::without_session()), + Err(outcome) => return (outcome, GuardianReviewDetails::without_session()), }; let ReviewSessionResult { - outcome, analytics, .. + outcome, details, .. } = request .run(&session, GuardianReviewSessionKind::EphemeralForked) .await; - (outcome, analytics) + (outcome, details) } } diff --git a/codex-rs/ext/guardian-reviewer/src/pool_tests.rs b/codex-rs/ext/guardian-reviewer/src/pool_tests.rs index 9580b57b..69be6177 100644 --- a/codex-rs/ext/guardian-reviewer/src/pool_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/pool_tests.rs @@ -130,7 +130,7 @@ impl ReviewerRequest for Request { ReviewSessionResult { outcome: GuardianReviewSessionOutcome::Completed(Err(anyhow::anyhow!("test verdict"))), disposition: SessionDisposition::Reusable, - analytics: GuardianReviewAnalyticsResult::without_session(), + details: GuardianReviewDetails::without_session(), } } } diff --git a/codex-rs/ext/guardian-reviewer/src/reporting.rs b/codex-rs/ext/guardian-reviewer/src/reporting.rs index ecca70f7..b0da3ec5 100644 --- a/codex-rs/ext/guardian-reviewer/src/reporting.rs +++ b/codex-rs/ext/guardian-reviewer/src/reporting.rs @@ -8,11 +8,9 @@ use std::sync::Arc; use std::time::Duration; use std::time::Instant; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::GuardianApprovalRequestSource; -use codex_analytics::GuardianReviewAnalyticsResult; -use codex_analytics::GuardianReviewTrackContext; -use codex_analytics::GuardianReviewedAction; +use crate::GuardianApprovalRequestSource; +use crate::GuardianReviewDetails; +use crate::GuardianReviewedAction; use codex_extension_api::ExtensionData; use codex_otel::SessionTelemetry; use codex_protocol::approvals::GuardianAssessmentAction; @@ -51,7 +49,6 @@ pub struct ReviewMetadata { pub struct ReviewReport { started: Option, started_instant: Instant, - tracking: GuardianReviewTrackContext, approval_request_source: GuardianApprovalRequestSource, reviewed_action: GuardianReviewedAction, } @@ -59,17 +56,7 @@ pub struct ReviewReport { impl ReviewReport { pub fn new(metadata: ReviewMetadata) -> Self { let started_instant = Instant::now(); - let tracking = GuardianReviewTrackContext::new( - metadata.thread_id, - metadata.turn_id.clone(), - metadata.review_id.clone(), - metadata.target_item_id.clone(), - metadata.approval_request_source, - metadata.reviewed_action.clone(), - metadata - .timeout - .map_or(0, |timeout| timeout.as_millis() as u64), - ); + let started_at_ms = crate::now_unix_millis(); let started = metadata.action.map(|action| GuardianAssessmentEvent { review_reason: Some(metadata.review_reason), model_context: Some(metadata.model_context), @@ -78,7 +65,7 @@ impl ReviewReport { plugin_id: metadata.plugin_id, script_path: metadata.script_path, turn_id: metadata.turn_id, - started_at_ms: tracking.started_at_ms.try_into().unwrap_or_default(), + started_at_ms: started_at_ms.try_into().unwrap_or_default(), completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, @@ -90,7 +77,6 @@ impl ReviewReport { Self { started, started_instant, - tracking, approval_request_source: metadata.approval_request_source, reviewed_action: metadata.reviewed_action, } @@ -100,13 +86,13 @@ impl ReviewReport { self.started.clone() } - /// Completes the report and captures the elapsed duration to use when tracking it. + /// Completes the report and captures the elapsed duration used for local metrics. pub fn complete( &self, outcome: GuardianReviewOutcome, model: &ModelInfo, require_guardian: bool, - analytics: GuardianReviewAnalyticsResult, + details: GuardianReviewDetails, completed_at_ms: i64, ) -> (ReviewCompletion, Duration) { let elapsed = self.started_instant.elapsed(); @@ -116,17 +102,16 @@ impl ReviewReport { event.decision_source = Some(GuardianAssessmentDecisionSource::Agent); } ( - crate::complete_review(outcome, model, require_guardian, event, analytics), + crate::complete_review(outcome, model, require_guardian, event, details), elapsed, ) } - pub fn track( + /// Records local-only review metrics. Nothing is sent anywhere. + pub fn record_metrics( &self, telemetry: &SessionTelemetry, - analytics: &AnalyticsEventsClient, - result: GuardianReviewAnalyticsResult, - completed_at_ms: u64, + result: GuardianReviewDetails, elapsed: Duration, ) { crate::metrics::emit_guardian_review_metrics( @@ -136,7 +121,6 @@ impl ReviewReport { &self.reviewed_action, elapsed, ); - analytics.track_guardian_review(&self.tracking, result, completed_at_ms, elapsed); } } diff --git a/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs b/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs index f4c88ff6..94135856 100644 --- a/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/reporting_tests.rs @@ -71,10 +71,8 @@ fn review_completion_uses_one_monotonic_duration( reasoning_effort: None, }, }); - report.tracking.started_at_ms = 1_654_073_807_000; if let Some(event) = &mut report.started { - event.started_at_ms = - i64::try_from(report.tracking.started_at_ms).expect("start timestamp"); + event.started_at_ms = 1_654_073_807_000; } assert_eq!(report.started_event().is_some(), has_client_event); report.started_instant = Instant::now() - Duration::from_millis(456); @@ -97,14 +95,14 @@ fn review_completion_uses_one_monotonic_duration( GuardianReviewOutcome::Error(crate::GuardianReviewError::Timeout), &model, /*require_guardian*/ true, - GuardianReviewAnalyticsResult { + GuardianReviewDetails { attempt_count: 2, token_usage: Some(TokenUsage { input_tokens: 10, total_tokens: 10, ..Default::default() }), - ..GuardianReviewAnalyticsResult::without_session() + ..GuardianReviewDetails::without_session() }, /*completed_at_ms*/ 1_792_141_011_000, ); @@ -119,15 +117,9 @@ fn review_completion_uses_one_monotonic_duration( has_client_event.then_some((1_654_073_807_000, Some(1_792_141_011_000))) ); - // Simulate tracking later: the captured interval must not be measured again. + // Simulate recording later: the captured interval must not be measured again. report.started_instant -= Duration::from_secs(1); - report.track( - &telemetry, - &AnalyticsEventsClient::disabled(), - completed.analytics, - /*completed_at_ms*/ 1_792_141_011_000, - elapsed, - ); + report.record_metrics(&telemetry, completed.details, elapsed); let snapshot = telemetry.snapshot_metrics().expect("metrics snapshot"); let names = snapshot diff --git a/codex-rs/ext/guardian-reviewer/src/retry.rs b/codex-rs/ext/guardian-reviewer/src/retry.rs index 2f847c69..ed7589ab 100644 --- a/codex-rs/ext/guardian-reviewer/src/retry.rs +++ b/codex-rs/ext/guardian-reviewer/src/retry.rs @@ -2,10 +2,10 @@ //! Resubmissions are independent; this layer keeps no state between approval requests. //! Changed local evidence retries cooperatively without service backoff, under the same limits. +use crate::GuardianReviewDetails; use crate::GuardianReviewError; use crate::GuardianReviewOutcome; use crate::ReviewDeadline; -use codex_analytics::GuardianReviewAnalyticsResult; use codex_protocol::protocol::CodexErrorInfo; use rand::Rng; use std::future::Future; @@ -28,7 +28,7 @@ pub async fn run_with_retry( mut run_attempt: F, ) -> ( GuardianReviewOutcome, - GuardianReviewAnalyticsResult, + GuardianReviewDetails, Option, ) where @@ -36,7 +36,7 @@ where Attempt: Future< Output = ( GuardianReviewOutcome, - GuardianReviewAnalyticsResult, + GuardianReviewDetails, Option, ), >, @@ -49,12 +49,12 @@ where let mut attempt_count = 1; let mut context_changed = false; loop { - let (outcome, mut analytics_result, evidence) = run_attempt(deadline).await; - analytics_result.attempt_count = attempt_count; - context_changed |= analytics_result.context_changed; - analytics_result.context_changed = context_changed; + let (outcome, mut details, evidence) = run_attempt(deadline).await; + details.attempt_count = attempt_count; + context_changed |= details.context_changed; + details.context_changed = context_changed; if attempt_count >= max_attempts || !should_retry_guardian_review(&outcome) { - return (outcome, analytics_result, evidence); + return (outcome, details, evidence); } let retry_at = match &outcome { GuardianReviewOutcome::Error(GuardianReviewError::Session { retry_at, .. }) => { @@ -97,7 +97,7 @@ where } } if let Some(error) = wait_error { - return (GuardianReviewOutcome::Error(error), analytics_result, None); + return (GuardianReviewOutcome::Error(error), details, None); } attempt_count += 1; } diff --git a/codex-rs/ext/guardian-reviewer/src/retry_tests.rs b/codex-rs/ext/guardian-reviewer/src/retry_tests.rs index 6c75d25d..27ca0b2d 100644 --- a/codex-rs/ext/guardian-reviewer/src/retry_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/retry_tests.rs @@ -1,9 +1,9 @@ #[cfg(test)] use super::*; use crate::GuardianAssessment; +use crate::GuardianReviewFailureReason; use crate::GuardianReviewResponse; use crate::GuardianReviewSessionOutcome; -use codex_analytics::GuardianReviewFailureReason; use codex_protocol::protocol::GuardianAssessmentOutcome; use codex_protocol::protocol::GuardianRiskLevel; use codex_protocol::protocol::GuardianUserAuthorization; @@ -186,7 +186,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget( let mut attempts = 0; let started_at = Instant::now(); let deadline = ReviewDeadline::from_timeout(timeout); - let (outcome, analytics, evidence) = run_with_retry( + let (outcome, details, evidence) = run_with_retry( GuardianReviewSessionLimits { max_attempts: 3, deadline, @@ -204,7 +204,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget( } else { GuardianReviewOutcome::Error(GuardianReviewError::StaleAuthorization) }, - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), Some(attempt), ) } @@ -226,7 +226,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget( } let expected_attempts = success_on_attempt.min(3); assert_eq!( - (attempts, analytics.attempt_count, evidence), + (attempts, details.attempt_count, evidence), ( expected_attempts, expected_attempts, @@ -239,7 +239,7 @@ async fn stale_authorization_uses_the_shared_attempt_budget( async fn stale_authorization_does_not_extend_the_deadline() { let deadline = ReviewDeadline::At(Instant::now() + Duration::from_secs(/*secs*/ 1)); let mut attempts = 0; - let (outcome, analytics, _) = run_with_retry( + let (outcome, details, _) = run_with_retry( GuardianReviewSessionLimits { max_attempts: 3, deadline, @@ -253,7 +253,7 @@ async fn stale_authorization_does_not_extend_the_deadline() { deadline.wait().await; ( GuardianReviewOutcome::Error(GuardianReviewError::StaleAuthorization), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), None::<()>, ) } @@ -264,5 +264,5 @@ async fn stale_authorization_does_not_extend_the_deadline() { outcome, GuardianReviewOutcome::Error(GuardianReviewError::Timeout) )); - assert_eq!((attempts, analytics.attempt_count), (1, 1)); + assert_eq!((attempts, details.attempt_count), (1, 1)); } diff --git a/codex-rs/ext/guardian-reviewer/src/review.rs b/codex-rs/ext/guardian-reviewer/src/review.rs index 2f18f505..5c93b517 100644 --- a/codex-rs/ext/guardian-reviewer/src/review.rs +++ b/codex-rs/ext/guardian-reviewer/src/review.rs @@ -2,6 +2,7 @@ //! The host binds the original action, captures evidence and enforces authorization. //! Async approvals can return while cancelled attempts finish under the parent's task tracker. +use crate::GuardianReviewDetails; use crate::GuardianReviewError; use crate::GuardianReviewOutcome; use crate::GuardianReviewSessionLimits; @@ -9,7 +10,6 @@ use crate::ReviewDeadline; use crate::ReviewDenials; use crate::ReviewReport; use crate::ReviewRequest; -use codex_analytics::GuardianReviewAnalyticsResult; use codex_extension_api::ExtensionFuture; use codex_extension_api::SynchronousApprovalReviewer; use codex_protocol::approvals::GuardianReviewReason; @@ -59,7 +59,7 @@ pub trait ReviewHost: Clone + Send + Sync + 'static { ) -> impl Future< Output = ( GuardianReviewOutcome, - GuardianReviewAnalyticsResult, + GuardianReviewDetails, Option, ), > + Send; @@ -144,25 +144,25 @@ impl SynchronousApprovalReviewer for ReviewRequest<'_, H> { .await } }); - let (outcome, analytics, evidence) = if let Some(async_approval) = async_approval { + let (outcome, details, evidence) = if let Some(async_approval) = async_approval { tokio::select! { biased; result = &mut review => result, () = async_approval => { cancellation.cancel(); - let analytics = if let Some(runtime) = self.thread_store.get::() { + let details = if let Some(runtime) = self.thread_store.get::() { // Keep driving the same attempt: its pool reservation stays held // until it drains, and parent shutdown joins the tracked cleanup. runtime.tasks.spawn(async move { let _ = review.await; }); // Final session and usage metadata are not available yet. - GuardianReviewAnalyticsResult { + GuardianReviewDetails { attempt_count: attempts.load(Ordering::Relaxed), - ..GuardianReviewAnalyticsResult::without_session() + ..GuardianReviewDetails::without_session() } } else { // Hosts without a lifetime tracker must finish cleanup here. - let (_, analytics, _) = review.await; - analytics + let (_, details, _) = review.await; + details }; let outcome = if !self.host.cached_approval_is_current(&prepared).await || self.cancellation.is_cancelled() { @@ -172,35 +172,22 @@ impl SynchronousApprovalReviewer for ReviewRequest<'_, H> { } else { GuardianReviewOutcome::CachedApproval }; - (outcome, analytics, None) + (outcome, details, None) } } } else { review.await }; - let completed_at_ms = codex_analytics::now_unix_millis(); + let completed_at_ms = crate::now_unix_millis(); let cached_approval = matches!(outcome, GuardianReviewOutcome::CachedApproval); let (completed, elapsed) = report.complete( outcome, self.model, self.require_guardian, - analytics, + details, completed_at_ms.try_into().unwrap_or_default(), ); - if self.log_assessments - && !cached_approval - && let Some(event) = &completed.event - { - self.telemetry - .guardian_assessment(event, completed.assessment_outcome); - } - report.track( - self.telemetry, - self.analytics, - completed.analytics, - completed_at_ms, - elapsed, - ); + report.record_metrics(self.telemetry, completed.details, elapsed); if let Some(message) = completed.warning { self.host .emit(EventMsg::GuardianWarning(WarningEvent { message })) diff --git a/codex-rs/ext/guardian-reviewer/src/review_result.rs b/codex-rs/ext/guardian-reviewer/src/review_result.rs new file mode 100644 index 00000000..566b6da4 --- /dev/null +++ b/codex-rs/ext/guardian-reviewer/src/review_result.rs @@ -0,0 +1,218 @@ +//! Review result details used for local decisions and local-only metrics. +//! Nothing here is sent anywhere: aKode has no usage-data reporting. + +use codex_protocol::approvals::NetworkApprovalProtocol; +use codex_protocol::models::AdditionalPermissionProfile; +use codex_protocol::models::SandboxPermissions; +use codex_protocol::protocol::GuardianAssessmentOutcome; +use codex_protocol::protocol::GuardianCommandSource; +use codex_protocol::protocol::GuardianRiskLevel; +use codex_protocol::protocol::GuardianUserAuthorization; +use codex_protocol::protocol::TokenUsage; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuardianReviewDecision { + Approved, + Denied, + Aborted, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuardianReviewTerminalStatus { + Approved, + Denied, + Aborted, + TimedOut, + FailedClosed, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuardianReviewFailureReason { + StaleAuthorization, + Timeout, + Cancelled, + PromptBuildError, + SessionError, + ParseError, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuardianReviewSessionKind { + TrunkNew, + TrunkReused, + EphemeralForked, +} + +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuardianApprovalRequestSource { + /// Approval requested directly by the main Codex turn. + MainTurn, + /// Approval requested by a delegated subagent and routed through the parent + /// session for guardian review. + DelegatedSubagent, +} + +/// Path-free permission metadata for a Guardian reviewed action. +#[derive(Clone, Debug, Serialize)] +pub struct GuardianAdditionalPermissions { + network: Option, +} + +#[derive(Clone, Debug, Serialize)] +struct GuardianNetworkPermissions { + enabled: Option, +} + +impl From<&AdditionalPermissionProfile> for GuardianAdditionalPermissions { + fn from(permissions: &AdditionalPermissionProfile) -> Self { + Self { + network: permissions + .network + .as_ref() + .map(|network| GuardianNetworkPermissions { + enabled: network.enabled, + }), + } + } +} + +#[derive(Clone, Debug, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum GuardianReviewedAction { + NativeToolCall {}, + Shell { + sandbox_permissions: SandboxPermissions, + additional_permissions: Option, + }, + UnifiedExec { + sandbox_permissions: SandboxPermissions, + additional_permissions: Option, + tty: bool, + }, + WriteStdin { + tty: bool, + }, + Execve { + source: GuardianCommandSource, + additional_permissions: Option, + }, + ApplyPatch {}, + NetworkAccess { + protocol: NetworkApprovalProtocol, + port: u16, + }, + McpToolCall { + server: String, + tool_name: String, + connector_id: Option, + connector_name: Option, + tool_title: Option, + }, + RequestPermissions {}, +} + +/// Details of one completed review, used for local decisions and local metrics. +#[derive(Debug)] +pub struct GuardianReviewDetails { + pub guardian_context_mode: Option<&'static str>, + pub decision: GuardianReviewDecision, + pub terminal_status: GuardianReviewTerminalStatus, + pub failure_reason: Option, + pub attempt_count: i64, + /// An allow was validated against changed parent/root authorization or review context. + /// Retained across attempts; this does not identify the cause of a later cancellation. + pub context_changed: bool, + pub risk_level: Option, + pub user_authorization: Option, + pub outcome: Option, + pub guardian_thread_id: Option, + pub guardian_session_kind: Option, + pub guardian_model: Option, + pub guardian_reasoning_effort: Option, + pub guardian_default_review_model_id: Option, + pub guardian_catalog_contains_auto_review: Option, + pub guardian_review_model_overridden: Option, + pub guardian_review_model_override: Option, + pub guardian_model_provider_id: Option, + pub had_prior_review_context: Option, + pub reviewed_action_truncated: bool, + pub token_usage: Option, + pub time_to_first_token_ms: Option, +} + +impl GuardianReviewDetails { + pub fn without_session() -> Self { + Self { + guardian_context_mode: None, + decision: GuardianReviewDecision::Denied, + terminal_status: GuardianReviewTerminalStatus::FailedClosed, + failure_reason: None, + attempt_count: 1, + context_changed: false, + risk_level: None, + user_authorization: None, + outcome: None, + guardian_thread_id: None, + guardian_session_kind: None, + guardian_model: None, + guardian_reasoning_effort: None, + guardian_default_review_model_id: None, + guardian_catalog_contains_auto_review: None, + guardian_review_model_overridden: None, + guardian_review_model_override: None, + guardian_model_provider_id: None, + had_prior_review_context: None, + reviewed_action_truncated: false, + token_usage: None, + time_to_first_token_ms: None, + } + } + + pub fn from_session(params: GuardianReviewSessionDetails) -> Self { + Self { + guardian_thread_id: Some(params.guardian_thread_id), + guardian_session_kind: Some(params.guardian_session_kind), + guardian_model: Some(params.guardian_model), + guardian_reasoning_effort: params.guardian_reasoning_effort, + guardian_default_review_model_id: Some(params.guardian_default_review_model_id), + guardian_catalog_contains_auto_review: Some( + params.guardian_catalog_contains_auto_review, + ), + guardian_review_model_overridden: Some(params.guardian_review_model_overridden), + guardian_review_model_override: params.guardian_review_model_override, + guardian_model_provider_id: Some(params.guardian_model_provider_id), + had_prior_review_context: Some(params.had_prior_review_context), + ..Self::without_session() + } + } +} + +pub struct GuardianReviewSessionDetails { + pub guardian_thread_id: String, + pub guardian_session_kind: GuardianReviewSessionKind, + pub guardian_model: String, + pub guardian_reasoning_effort: Option, + pub guardian_default_review_model_id: String, + pub guardian_catalog_contains_auto_review: bool, + pub guardian_review_model_overridden: bool, + pub guardian_review_model_override: Option, + pub guardian_model_provider_id: String, + pub had_prior_review_context: bool, +} + +/// Milliseconds since the Unix epoch. +pub fn now_unix_millis() -> u64 { + u64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis(), + ) + .unwrap_or(u64::MAX) +} diff --git a/codex-rs/ext/guardian-reviewer/src/review_state.rs b/codex-rs/ext/guardian-reviewer/src/review_state.rs index a497be54..bae35371 100644 --- a/codex-rs/ext/guardian-reviewer/src/review_state.rs +++ b/codex-rs/ext/guardian-reviewer/src/review_state.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; -use codex_analytics::GuardianReviewSessionKind; +use crate::GuardianReviewSessionKind; use codex_history::InitialHistory; use codex_history::RolloutItem; use codex_protocol::models::ContentItem; diff --git a/codex-rs/ext/guardian-reviewer/src/review_tests.rs b/codex-rs/ext/guardian-reviewer/src/review_tests.rs index 78c2911e..cf8cc8f1 100644 --- a/codex-rs/ext/guardian-reviewer/src/review_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/review_tests.rs @@ -1,10 +1,9 @@ //! Exercises async approval and authorization at the host boundary while cleanup is gated. use super::*; +use crate::GuardianApprovalRequestSource; +use crate::GuardianReviewedAction; use crate::ReviewMetadata; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::GuardianApprovalRequestSource; -use codex_analytics::GuardianReviewedAction; use codex_extension_api::ExtensionData; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; @@ -82,11 +81,7 @@ impl ReviewHost for GatedHost { _: &(), _: ReviewDeadline, cancellation: &CancellationToken, - ) -> ( - GuardianReviewOutcome, - GuardianReviewAnalyticsResult, - Option<()>, - ) { + ) -> (GuardianReviewOutcome, GuardianReviewDetails, Option<()>) { self.started.notify_one(); cancellation.cancelled().await; self.cleaning.notify_one(); @@ -97,7 +92,7 @@ impl ReviewHost for GatedHost { GuardianReviewOutcome::Completed( crate::parse_guardian_assessment(r#"{"outcome":"deny"}"#).unwrap(), ), - GuardianReviewAnalyticsResult::without_session(), + GuardianReviewDetails::without_session(), Some(()), ) } @@ -157,7 +152,6 @@ async fn async_approval_revalidates_without_waiting_for_tracked_cleanup(state: A "test".into(), SessionSource::Exec, ); - let analytics = AnalyticsEventsClient::disabled(); let action = json!({}); let request = ReviewRequest { serving_assessment: None, @@ -182,8 +176,6 @@ async fn async_approval_revalidates_without_waiting_for_tracked_cleanup(state: A timeout: Some(crate::REVIEW_TIMEOUT), model: &model, telemetry: &telemetry, - log_assessments: false, - analytics: &analytics, metrics: None, }; let decision = request.review( diff --git a/codex-rs/ext/guardian-reviewer/src/routing.rs b/codex-rs/ext/guardian-reviewer/src/routing.rs index c173bd37..afe089fd 100644 --- a/codex-rs/ext/guardian-reviewer/src/routing.rs +++ b/codex-rs/ext/guardian-reviewer/src/routing.rs @@ -3,13 +3,11 @@ use crate::ReviewDenials; use crate::ReviewHost; -use codex_analytics::AnalyticsEventsClient; use codex_extension_api::ApprovalDecision; use codex_extension_api::ApprovalDecisionInput; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionMetrics; use codex_extension_api::ExtensionRegistry; -use codex_extension_api::GuardianV2Enabled; use codex_extension_api::SynchronousApprovalReviewer; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; @@ -50,9 +48,6 @@ pub struct ReviewRequest<'a, H> { pub timeout: Option, pub model: &'a ModelInfo, pub telemetry: &'a SessionTelemetry, - /// The host verified the assessment opt-in and an explicit OTLP log destination. - pub log_assessments: bool, - pub analytics: &'a AnalyticsEventsClient, pub metrics: Option>, } @@ -180,26 +175,12 @@ impl ReviewRequest<'_, H> { } pub(super) async fn cached_approval(&self) -> ReviewDecision { - let (turn_id, item_id) = match self.host.validate_action() { - Ok(target) => target, - Err(decision) => return decision, - }; + if let Err(decision) = self.host.validate_action() { + return decision; + } if self.cancellation.is_cancelled() { return ReviewDecision::Abort; } - if self.thread_store.get::().is_some() { - self.analytics - .track_guardian_v2_event(codex_analytics::GuardianV2Event { - thread_id: self.thread_id.to_string(), - turn_id: turn_id.to_owned(), - item_id: item_id.map(str::to_owned), - model: Some(self.model.slug.clone()), - occurred_at_ms: codex_analytics::now_unix_millis(), - kind: codex_analytics::GuardianV2EventKind::FastDecision { - decision: "approved", - }, - }); - } if let Some((turn_id, _)) = self.host.servicing_turn().await { ReviewDenials::for_thread(self.thread_store) .record_non_denial(&turn_id) diff --git a/codex-rs/ext/guardian-v2/Cargo.toml b/codex-rs/ext/guardian-v2/Cargo.toml index 649be85b..7fb258f1 100644 --- a/codex-rs/ext/guardian-v2/Cargo.toml +++ b/codex-rs/ext/guardian-v2/Cargo.toml @@ -16,7 +16,6 @@ workspace = true codex-agent-identity = { workspace = true } codex-runtime-agent-instance = { workspace = true } anyhow = { workspace = true } -codex-analytics = { workspace = true } codex-api = { workspace = true } codex-config = { workspace = true } codex-context-fragments = { workspace = true } diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs b/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs index c333349b..15f5ff2f 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs @@ -8,9 +8,6 @@ use std::sync::Arc; use std::time::Instant; use std::time::SystemTime; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::GuardianV2Event; -use codex_analytics::GuardianV2EventKind; use codex_core::CodexThread; use codex_core::GuardianAuthorizationVersion; use codex_core::GuardianRootSnapshot; @@ -62,7 +59,6 @@ pub(super) struct Classification { pub(super) score_progress: Arc, pub(super) parent_model: Option>, pub(super) metrics: Option>, - pub(super) analytics: Option>, pub(super) sampled_at: SystemTime, pub(super) tool_call_index: usize, pub(super) event_sink: Arc, @@ -116,7 +112,6 @@ impl Classification { score_progress, parent_model, metrics, - analytics, sampled_at, tool_call_index, event_sink, @@ -410,21 +405,6 @@ impl Classification { outcome, result.is_err().then_some(failure_reason), ); - if let Some(analytics) = analytics { - analytics.track_guardian_v2_event(GuardianV2Event { - thread_id: thread_id.clone(), - turn_id: turn_id.clone(), - item_id: Some(call_id), - model: parent_model.as_ref().map(|model| model.slug.clone()), - occurred_at_ms: codex_analytics::now_unix_millis(), - kind: GuardianV2EventKind::Classification { - guardian_context_mode: context_mode.as_str(), - outcome, - risk_level: classification_risk, - duration_ms: u64::try_from(duration.as_millis()).unwrap_or(u64::MAX), - }, - }); - } if matches!(result, Ok(ClassificationOutcome::Scored)) { truncations.emit(metrics.as_deref()); } diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/observation.rs b/codex-rs/ext/guardian-v2/src/async_scorer/observation.rs index 6bfcc4ee..46f1d0ae 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/observation.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/observation.rs @@ -5,7 +5,6 @@ use std::sync::Arc; use std::time::Instant; use std::time::SystemTime; -use codex_analytics::AnalyticsEventsClient; use codex_core::context::GuardianContextMode; use codex_core::context::GuardianReviewEvidence; use codex_core::context::NodeReplReviewEvidence; @@ -161,7 +160,6 @@ impl GuardianV2Extension { } let metrics = score_progress.metrics.clone(); let context_mode = GuardianContextMode::from_history(input.conversation_history.as_ref()); - let analytics = input.session_store.get::(); let sampled_at = SystemTime::now(); let Some(conversation) = input.thread_store.get::() else { let index = score_progress.observe(&input); @@ -411,7 +409,6 @@ impl GuardianV2Extension { score_progress, parent_model, metrics, - analytics, sampled_at, tool_call_index, event_sink, diff --git a/codex-rs/ext/guardian-v2/src/sync_reviewer/mod.rs b/codex-rs/ext/guardian-v2/src/sync_reviewer/mod.rs index fd2c5fa9..45d95488 100644 --- a/codex-rs/ext/guardian-v2/src/sync_reviewer/mod.rs +++ b/codex-rs/ext/guardian-v2/src/sync_reviewer/mod.rs @@ -85,7 +85,7 @@ impl ThreadLifecycleContributor for GuardianExtension { let (mut options, state) = context.thread_options(kind, snapshot).await; if matches!( kind, - codex_analytics::GuardianReviewSessionKind::EphemeralForked + codex_guardian_reviewer::GuardianReviewSessionKind::EphemeralForked ) { options.config.ephemeral = true; } diff --git a/codex-rs/ext/guardian-v3/Cargo.toml b/codex-rs/ext/guardian-v3/Cargo.toml index 1f7d8995..49dfbac4 100644 --- a/codex-rs/ext/guardian-v3/Cargo.toml +++ b/codex-rs/ext/guardian-v3/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] anyhow = { workspace = true } -codex-analytics = { workspace = true } codex-extension-api = { workspace = true } codex-guardian-reviewer = { workspace = true } codex-history = { workspace = true } diff --git a/codex-rs/ext/guardian-v3/src/sampling.rs b/codex-rs/ext/guardian-v3/src/sampling.rs index 1f94ed6e..98e8c556 100644 --- a/codex-rs/ext/guardian-v3/src/sampling.rs +++ b/codex-rs/ext/guardian-v3/src/sampling.rs @@ -1,6 +1,6 @@ //! Typed Guardian operations through the existing isolated-turn executor. -use codex_analytics::GuardianReviewAnalyticsResult; +use codex_guardian_reviewer::GuardianReviewDetails; use codex_guardian_reviewer::GuardianReviewSessionOutcome; use codex_guardian_reviewer::ReviewDeadline; use codex_guardian_reviewer::ReviewerRuntime; @@ -106,7 +106,7 @@ pub(crate) async fn sample( &turn_id, deadline, Some(cancellation), - &mut GuardianReviewAnalyticsResult::without_session(), + &mut GuardianReviewDetails::without_session(), ) .await; let mut disposition = turn.disposition; diff --git a/codex-rs/ext/guardian-v3/tests/housekeeping.rs b/codex-rs/ext/guardian-v3/tests/housekeeping.rs index 470751b6..40722161 100644 --- a/codex-rs/ext/guardian-v3/tests/housekeeping.rs +++ b/codex-rs/ext/guardian-v3/tests/housekeeping.rs @@ -2,10 +2,10 @@ #![allow(clippy::expect_used)] -use codex_analytics::GuardianReviewSessionKind; use codex_core::guardian_review::prepare_review_prewarm; use codex_extension_api::SessionIsolation; use codex_extension_api::ToolPolicy; +use codex_guardian_reviewer::GuardianReviewSessionKind; use codex_guardian_reviewer::ReviewDeadline; use codex_guardian_reviewer::SessionDisposition; use codex_guardian_v3::EvidenceCursor; diff --git a/codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs b/codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs index 8d335235..3c43b7de 100644 --- a/codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs +++ b/codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs @@ -1,9 +1,9 @@ //! Whole originals enter a real retained conversation without scheduling inference. -use codex_analytics::GuardianReviewSessionKind; use codex_core::guardian_review::prepare_review_prewarm; use codex_extension_api::SessionIsolation; use codex_extension_api::ToolPolicy; +use codex_guardian_reviewer::GuardianReviewSessionKind; use codex_guardian_v3::DeliveryState; use codex_message_board::AgentMessageBoard; use codex_protocol::config_types::ApprovalsReviewer; diff --git a/codex-rs/ext/guardian-v3/tests/retrieval/selection.rs b/codex-rs/ext/guardian-v3/tests/retrieval/selection.rs index 4ee01e73..781f163f 100644 --- a/codex-rs/ext/guardian-v3/tests/retrieval/selection.rs +++ b/codex-rs/ext/guardian-v3/tests/retrieval/selection.rs @@ -1,9 +1,9 @@ //! Reviewer tools and model-driven selection share a fixed Guardian catalog. -use codex_analytics::GuardianReviewSessionKind; use codex_core::guardian_review::prepare_review_prewarm; use codex_extension_api::SessionIsolation; use codex_extension_api::ToolPolicy; +use codex_guardian_reviewer::GuardianReviewSessionKind; use codex_guardian_reviewer::ReviewDeadline; use codex_guardian_reviewer::SessionDisposition; use codex_guardian_v3::CHANNEL_SELECTION_INSTRUCTIONS; diff --git a/codex-rs/ext/history-notes/Cargo.toml b/codex-rs/ext/history-notes/Cargo.toml index 11e93ea9..a0029a2e 100644 --- a/codex-rs/ext/history-notes/Cargo.toml +++ b/codex-rs/ext/history-notes/Cargo.toml @@ -13,7 +13,6 @@ doctest = false workspace = true [dependencies] -codex-analytics = { workspace = true } codex-client = { workspace = true } codex-core = { workspace = true } codex-extension-api = { workspace = true } diff --git a/codex-rs/ext/history-notes/src/extension.rs b/codex-rs/ext/history-notes/src/extension.rs index e5590588..9063dd49 100644 --- a/codex-rs/ext/history-notes/src/extension.rs +++ b/codex-rs/ext/history-notes/src/extension.rs @@ -1,8 +1,5 @@ use std::sync::Arc; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::ThreadHintStatus; -use codex_analytics::ThreadHintStatusEvent; use codex_core::config::Config; use codex_extension_api::ConfigContributor; use codex_extension_api::ContentItemKind; @@ -116,15 +113,6 @@ impl ContextContributor for HistoryNotesExtension { let Some(identity) = thread_store.get::() else { return Vec::new(); }; - let track_status = |status| { - if let Some(analytics) = session_store.get::() { - analytics.track_thread_hint_status(ThreadHintStatusEvent { - thread_id: thread_store.level_id().to_string(), - status, - occurred_at_ms: codex_analytics::now_unix_millis(), - }); - } - }; let Ok(result) = config .backend .call( @@ -136,18 +124,14 @@ impl ContextContributor for HistoryNotesExtension { ) .await else { - track_status(ThreadHintStatus::Failed); return Vec::new(); }; let Some(text) = result.get("text").and_then(serde_json::Value::as_str) else { - track_status(ThreadHintStatus::Failed); return Vec::new(); }; if text.len() > MAX_THREAD_HINT_BYTES { - track_status(ThreadHintStatus::Failed); return Vec::new(); } - track_status(ThreadHintStatus::Succeeded); if text.is_empty() { return Vec::new(); } diff --git a/codex-rs/ext/items/src/image_generation.rs b/codex-rs/ext/items/src/image_generation.rs index 9f0ea1f4..3e8dfdcb 100644 --- a/codex-rs/ext/items/src/image_generation.rs +++ b/codex-rs/ext/items/src/image_generation.rs @@ -53,7 +53,7 @@ pub struct ImageGenerationItem { #[serde(default, skip_serializing_if = "Vec::is_empty")] #[ts(as = "Option<_>", optional)] pub input_images: Vec, - /// Exact nested ImageGen request ID retained only for in-process analytics. + /// Exact nested ImageGen request ID retained only in-process. /// /// This is deliberately excluded from the extension/app-server wire shape /// and rollout persistence because it is not a client-facing item field. diff --git a/codex-rs/ext/skills/Cargo.toml b/codex-rs/ext/skills/Cargo.toml index ee679767..fedcd4df 100644 --- a/codex-rs/ext/skills/Cargo.toml +++ b/codex-rs/ext/skills/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] blake3 = { workspace = true } -codex-analytics = { workspace = true } codex-config = { workspace = true } codex-exec-server = { workspace = true } codex-extension-api = { workspace = true } diff --git a/codex-rs/ext/skills/src/catalog.rs b/codex-rs/ext/skills/src/catalog.rs index 7e0dbb08..07f55e1e 100644 --- a/codex-rs/ext/skills/src/catalog.rs +++ b/codex-rs/ext/skills/src/catalog.rs @@ -189,7 +189,7 @@ pub struct SkillCatalogEntry { pub display_path: Option, pub canonical_skill_id: Option, pub plugin_id: Option, - pub analytics_scope: Option, + pub invocation_scope: Option, /// Plugin-service identity for cross-source matching. pub remote_plugin_id: Option, /// Alternate read routes that retain their original authority. @@ -220,7 +220,7 @@ impl SkillCatalogEntry { display_path: None, canonical_skill_id: None, plugin_id: None, - analytics_scope: None, + invocation_scope: None, remote_plugin_id: None, sources: Vec::new(), alias_root: None, diff --git a/codex-rs/ext/skills/src/extension.rs b/codex-rs/ext/skills/src/extension.rs index 4c1c7191..29da998a 100644 --- a/codex-rs/ext/skills/src/extension.rs +++ b/codex-rs/ext/skills/src/extension.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use crate::HostSkillsSnapshot; use crate::InjectedHostSkillPrompts; -use codex_analytics::InvocationType; use codex_exec_server::LOCAL_ENVIRONMENT_ID; use codex_extension_api::ConfigContributor; use codex_extension_api::ContextContributor; @@ -29,6 +28,7 @@ use codex_extension_api::WorldStateContributionInput; use codex_extension_api::WorldStateSectionContribution; use codex_mcp::McpResourceClient; use codex_otel::MetricsClient; +use codex_otel::SkillInvocationType as InvocationType; use codex_protocol::openai_models::ModelInfo; use crate::SkillsExtensionConfig; @@ -64,7 +64,7 @@ use crate::state::SkillsSessionState; use crate::state::SkillsThreadState; use crate::step_state::SkillsStepState; use crate::telemetry::SkillTelemetry; -use crate::tools::SkillAnalytics; +use crate::tools::SkillInvocationRecorder; use crate::tools::SkillToolAuthority; use crate::tools::skill_tools; use crate::warnings::bounded_warnings; @@ -430,7 +430,7 @@ where } let mut injected_host_skill_prompts = InjectedHostSkillPrompts::default(); - let analytics = SkillAnalytics::from_stores(session_store, thread_store); + let invocations = SkillInvocationRecorder::from_stores(session_store, thread_store); for entry in &selected_entries { match self .read_main_prompt( @@ -476,10 +476,10 @@ where fragments.push(Box::new(fragment)); if entry.authority.kind == SkillSourceKind::Host { injected_host_skill_prompts.insert_path(entry.main_prompt.as_str()); - } else if let Some(analytics) = analytics.as_ref() + } else if let Some(invocations) = invocations.as_ref() && let Some(model_info) = thread_store.get::() { - analytics.track_skill_invocation( + invocations.record_skill_invocation( entry, &entry.primary_source(), model_info.slug.clone(), diff --git a/codex-rs/ext/skills/src/invocation.rs b/codex-rs/ext/skills/src/invocation.rs index cc99a07b..f85ef367 100644 --- a/codex-rs/ext/skills/src/invocation.rs +++ b/codex-rs/ext/skills/src/invocation.rs @@ -1,8 +1,7 @@ -use codex_analytics::InvocationType; -use codex_analytics::SkillInvocation; -use codex_analytics::SkillInvocationLocation; use codex_exec_server::LOCAL_ENVIRONMENT_ID; use codex_extension_api::ExtensionData; +use codex_otel::SkillInvocationType as InvocationType; +use codex_protocol::protocol::SkillScope; use codex_skills::ImplicitSkillAccess; use codex_skills::detect_implicit_skill_invocation_for_command; use codex_skills::implicit_skill_accesses_for_command; @@ -16,6 +15,30 @@ use crate::catalog::SkillResourceId; use crate::catalog::SkillSourceKind; use crate::catalog::SkillSourceLocation; +/// A detected skill use, consumed by local logging, local metrics and skill contributors. +#[derive(Clone, Debug)] +pub struct SkillInvocation { + pub skill_name: String, + pub location: SkillInvocationLocation, + pub plugin_id: Option, + pub remote_plugin_id: Option, + pub invocation_type: InvocationType, +} + +/// Where the invoked skill was loaded from. +#[derive(Clone, Debug)] +pub enum SkillInvocationLocation { + Host { + path: PathUri, + scope: SkillScope, + }, + Resource { + id: String, + skill_id: Option, + scope: Option, + }, +} + impl SkillCatalogEntry { /// Uses merged identity and scope, with plugin attribution from the route actually used. pub(crate) fn invocation( @@ -28,7 +51,7 @@ impl SkillCatalogEntry { location: SkillInvocationLocation::Resource { id: self.main_prompt.as_str().to_owned(), skill_id: self.canonical_skill_id.clone(), - scope: self.analytics_scope, + scope: self.invocation_scope, }, plugin_id: source.plugin_id.clone(), remote_plugin_id: self.remote_plugin_id.clone(), diff --git a/codex-rs/ext/skills/src/lib.rs b/codex-rs/ext/skills/src/lib.rs index 8a22ab47..8839ae32 100644 --- a/codex-rs/ext/skills/src/lib.rs +++ b/codex-rs/ext/skills/src/lib.rs @@ -44,6 +44,8 @@ pub use host_service::HostSkillsLoadInput; pub use host_service::HostSkillsRequest; pub use host_service::HostSkillsService; pub use host_snapshot::HostSkillsSnapshot; +pub use invocation::SkillInvocation; +pub use invocation::SkillInvocationLocation; pub use invocation::detect_implicit_skill_invocation; pub use provider::ExecutorSkillProvider; pub use provider::FrozenCloudSkillProvider; diff --git a/codex-rs/ext/skills/src/provider/executor.rs b/codex-rs/ext/skills/src/provider/executor.rs index 01292d9c..44f3971b 100644 --- a/codex-rs/ext/skills/src/provider/executor.rs +++ b/codex-rs/ext/skills/src/provider/executor.rs @@ -73,7 +73,7 @@ pub(crate) fn attribute_executor_plugins( .find(|plugin| plugin.selected_root_id.as_ref() == Some(&skill.authority.id)) { skill.plugin_id = Some(plugin.plugin_id.as_str().to_string()); - skill.analytics_scope = Some(SkillScope::User); + skill.invocation_scope = Some(SkillScope::User); } } } diff --git a/codex-rs/ext/skills/src/provider/executor/discovery_v2.rs b/codex-rs/ext/skills/src/provider/executor/discovery_v2.rs index 3a5a3f7c..791b2059 100644 --- a/codex-rs/ext/skills/src/provider/executor/discovery_v2.rs +++ b/codex-rs/ext/skills/src/provider/executor/discovery_v2.rs @@ -45,7 +45,7 @@ impl ExecutorSkillProvider { }; entry.remote_plugin_id = plugin.remote_plugin_id.clone(); entry.plugin_id = Some(plugin.id.clone()); - entry.analytics_scope = Some(SkillScope::User); + entry.invocation_scope = Some(SkillScope::User); catalog.push_entry(entry); } } diff --git a/codex-rs/ext/skills/src/telemetry.rs b/codex-rs/ext/skills/src/telemetry.rs index 7728119e..070cbb97 100644 --- a/codex-rs/ext/skills/src/telemetry.rs +++ b/codex-rs/ext/skills/src/telemetry.rs @@ -25,7 +25,6 @@ pub fn record_plugin_turn_usage(turn_store: &ExtensionData, plugin_id: Option<&s pub(crate) struct SkillTurnMetrics { pub(crate) turn_id: String, - pub(crate) turn_metadata: Option>, model_slug: String, pub(crate) reasoning_effort: String, started_at: Instant, @@ -112,10 +111,6 @@ impl TurnLifecycleContributor for SkillTelemetry { .unwrap_or_else(|| "default".to_string()); input.turn_store.insert(SkillTurnMetrics { turn_id: input.turn_id.to_string(), - turn_metadata: input - .turn_store - .get::>() - .map(|metadata| metadata.as_ref().clone()), model_slug: sanitize_metric_tag_value(input.collaboration_mode.model()), reasoning_effort, started_at: Instant::now(), diff --git a/codex-rs/ext/skills/src/tools/mod.rs b/codex-rs/ext/skills/src/tools/mod.rs index 8032e64d..5b0c306e 100644 --- a/codex-rs/ext/skills/src/tools/mod.rs +++ b/codex-rs/ext/skills/src/tools/mod.rs @@ -3,15 +3,11 @@ use std::hash::Hash; use std::hash::Hasher; use std::sync::Arc; -use codex_analytics::AnalyticsEventsClient; -use codex_analytics::InvocationType; -use codex_analytics::build_track_events_context; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionMetrics; use codex_extension_api::FunctionCallError; use codex_extension_api::JsonToolOutput; use codex_extension_api::ResponsesApiTool; -use codex_extension_api::ThreadOriginator; use codex_extension_api::ToolCall; use codex_extension_api::ToolExecutor; use codex_extension_api::ToolName; @@ -22,7 +18,7 @@ use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::McpResourceClient; use codex_otel::SessionTelemetry; use codex_otel::SkillInvocationEvent; -use codex_otel::SkillInvocationType; +use codex_otel::SkillInvocationType as InvocationType; use codex_otel::sanitize_metric_tag_value; use codex_tools::ResponsesApiNamespace; use codex_tools::ResponsesApiNamespaceTool; @@ -72,7 +68,7 @@ pub(crate) fn skill_tools( let mcp_resources = session_store .get::() .and_then(|state| state.mcp_resources.clone()); - let analytics = SkillAnalytics::from_stores(session_store, thread_store); + let invocations = SkillInvocationRecorder::from_stores(session_store, thread_store); let metrics = step_store .get::>() .map(|metrics| Arc::clone(metrics.as_ref())); @@ -81,7 +77,7 @@ pub(crate) fn skill_tools( providers, mcp_resources, thread_state, - analytics, + invocations, step_state, }; let mut tools: Vec ToolExecutor>>> = vec![ @@ -102,26 +98,20 @@ pub(crate) fn skill_tools( tools } +/// Records skill invocations to local logs and local metrics only. #[derive(Clone)] -pub(crate) struct SkillAnalytics { - client: AnalyticsEventsClient, +pub(crate) struct SkillInvocationRecorder { telemetry: Option>, metrics: Option>, turn_metrics: Option>, - thread_id: String, - product_client_id: String, } -impl SkillAnalytics { +impl SkillInvocationRecorder { pub(crate) fn from_stores( session_store: &ExtensionData, thread_store: &ExtensionData, ) -> Option { - let client = session_store.get::()?; - let originator = thread_store.get::()?; - Some(Self { - client: client.as_ref().clone(), telemetry: session_store.get::(), metrics: session_store .get::() @@ -133,12 +123,10 @@ impl SkillAnalytics { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .upgrade(), - thread_id: thread_store.level_id().to_string(), - product_client_id: originator.0.clone(), }) } - pub(crate) fn track_skill_invocation( + pub(crate) fn record_skill_invocation( &self, skill: &SkillCatalogEntry, source: &SkillSourceLocation, @@ -155,12 +143,9 @@ impl SkillAnalytics { .skill_invocation(SkillInvocationEvent { turn_id: &turn_id, skill_name: &skill.name, - scope: skill.analytics_scope, + scope: skill.invocation_scope, plugin_id: invocation.plugin_id.as_deref(), - invocation_type: match invocation_type { - InvocationType::Explicit => SkillInvocationType::Explicit, - InvocationType::Implicit => SkillInvocationType::Implicit, - }, + invocation_type, }); } let turn_metrics = self @@ -197,16 +182,6 @@ impl SkillAnalytics { ], ); } - self.client.track_skill_invocations( - build_track_events_context( - model, - self.thread_id.clone(), - turn_id, - self.product_client_id.clone(), - turn_metrics.and_then(|turn| turn.turn_metadata.clone()), - ), - vec![invocation], - ); } } @@ -216,7 +191,7 @@ struct SkillToolContext { providers: SkillProviders, mcp_resources: Option>, thread_state: Arc, - analytics: Option, + invocations: Option, step_state: Arc, } diff --git a/codex-rs/ext/skills/src/tools/read.rs b/codex-rs/ext/skills/src/tools/read.rs index ecf65c23..9e8f558c 100644 --- a/codex-rs/ext/skills/src/tools/read.rs +++ b/codex-rs/ext/skills/src/tools/read.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use codex_analytics::InvocationType; use codex_extension_api::ExtensionMetrics; use codex_extension_api::FunctionCallError; use codex_extension_api::ToolCall; @@ -8,6 +7,7 @@ use codex_extension_api::ToolExecutor; use codex_extension_api::ToolExecutorFuture; use codex_extension_api::ToolName; use codex_extension_api::ToolSpec; +use codex_otel::SkillInvocationType as InvocationType; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -433,9 +433,9 @@ impl<'call> ToolExecutor> for ReadTool { if requested_resource == main_prompt && args.cursor.is_none() - && let Some(analytics) = self.context.analytics.as_ref() + && let Some(invocations) = self.context.invocations.as_ref() { - analytics.track_skill_invocation( + invocations.record_skill_invocation( skill_entry, &selected_source, call.model.clone(), diff --git a/codex-rs/ext/skills/tests/skills_extension/merge_catalog_tests.rs b/codex-rs/ext/skills/tests/skills_extension/merge_catalog_tests.rs index 04d2c4aa..dd72994f 100644 --- a/codex-rs/ext/skills/tests/skills_extension/merge_catalog_tests.rs +++ b/codex-rs/ext/skills/tests/skills_extension/merge_catalog_tests.rs @@ -1228,7 +1228,7 @@ async fn v2_implicit_and_explicit_invocations_retain_their_step_catalog() -> Tes let original = detect(&harness.step_store).expect("prepared step skill"); assert_eq!(original.remote_plugin_id, cloud.remote_plugin_id); assert_eq!(original.plugin_id.as_deref(), Some("matching")); - assert_matches!(&original.location, codex_analytics::SkillInvocationLocation::Resource { id, .. } if id == cloud.main_prompt.as_str()); + assert_matches!(&original.location, codex_skills_extension::SkillInvocationLocation::Resource { id, .. } if id == cloud.main_prompt.as_str()); let next_step = ExtensionData::new("step-2"); harness.turn_store.insert(SelectedPluginSnapshot::default()); diff --git a/codex-rs/ext/skills/tests/skills_extension/source_telemetry_tests.rs b/codex-rs/ext/skills/tests/skills_extension/source_telemetry_tests.rs index bed10e5c..9311dd43 100644 --- a/codex-rs/ext/skills/tests/skills_extension/source_telemetry_tests.rs +++ b/codex-rs/ext/skills/tests/skills_extension/source_telemetry_tests.rs @@ -58,7 +58,7 @@ async fn source_events_cover_cached_cloud_and_explicit_executor_reads() -> TestR harness.render().await?; let events = ReadEvents::default(); let subscriber = tracing_subscriber::registry().with(events.clone().with_filter( - tracing_subscriber::filter::filter_fn(codex_otel::OtelProvider::trace_export_filter), + tracing_subscriber::filter::filter_fn(codex_otel::trace_export_filter), )); // Prevent parallel tests with no subscriber from disabling this callsite globally. let _interest_cache_guard = diff --git a/codex-rs/external-agent-migration/Cargo.toml b/codex-rs/external-agent-migration/Cargo.toml index 3f49a1ae..8368983e 100644 --- a/codex-rs/external-agent-migration/Cargo.toml +++ b/codex-rs/external-agent-migration/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] chrono = { workspace = true } -codex-analytics = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-core-plugins = { workspace = true } diff --git a/codex-rs/external-agent-migration/src/plugins.rs b/codex-rs/external-agent-migration/src/plugins.rs index 1382d1a8..e985dfc5 100644 --- a/codex-rs/external-agent-migration/src/plugins.rs +++ b/codex-rs/external-agent-migration/src/plugins.rs @@ -1,4 +1,3 @@ -use codex_analytics::PluginInstallSource; use codex_core::config::ConfigBuilder; use codex_core::plugins_manager_for_config_with_runtime; use codex_core_plugins::PluginInstallError; @@ -109,11 +108,7 @@ impl ExternalAgentConfigService { let plugins_manager = plugins_manager_for_config_with_runtime(&config, Arc::clone(&self.auth_manager)) .await - .map_err(io::Error::other)? - .with_plugin_install_source(PluginInstallSource::ExternalAgentMigration); - if let Some(analytics_events_client) = self.analytics_events_client.clone() { - plugins_manager.set_analytics_events_client(analytics_events_client); - } + .map_err(io::Error::other)?; let configured_marketplace_paths = plugins_manager .list_marketplaces_for_config( &config.plugins_config_input(), diff --git a/codex-rs/external-agent-migration/src/service.rs b/codex-rs/external-agent-migration/src/service.rs index 3d04a1f6..7c79b61f 100644 --- a/codex-rs/external-agent-migration/src/service.rs +++ b/codex-rs/external-agent-migration/src/service.rs @@ -39,7 +39,6 @@ use crate::utils::invalid_data_error; use crate::utils::is_missing_or_empty_text_file; pub(super) use crate::utils::read_json_file as read_external_settings; use crate::utils::rewrite_external_agent_terms; -use codex_analytics::AnalyticsEventsClient; use codex_core::config::Config; use codex_core_plugins::PluginsManager; use codex_core_plugins::marketplace::MarketplacePluginInstallPolicy; @@ -70,7 +69,6 @@ pub struct ExternalAgentConfigService { pub(super) codex_home: PathBuf, pub(super) connector_metadata_roots: Vec, pub(crate) external_agent_home: PathBuf, - pub(crate) analytics_events_client: Option, pub(crate) auth_manager: Arc, pub(crate) source: ExternalAgentSource, pub(crate) session_import_limits: ExternalAgentSessionImportLimits, @@ -82,7 +80,6 @@ impl ExternalAgentConfigService { pub fn new( codex_home: PathBuf, auth_manager: Arc, - analytics_events_client: AnalyticsEventsClient, state_db: Option, ) -> Self { let source = ExternalAgentSource::default(); @@ -92,7 +89,6 @@ impl ExternalAgentConfigService { codex_home, connector_metadata_roots, external_agent_home, - analytics_events_client: Some(analytics_events_client), auth_manager, source, session_import_limits: ExternalAgentSessionImportLimits::default(), @@ -109,7 +105,6 @@ impl ExternalAgentConfigService { codex_home: self.codex_home.clone(), connector_metadata_roots, external_agent_home, - analytics_events_client: self.analytics_events_client.clone(), auth_manager: Arc::clone(&self.auth_manager), source, session_import_limits: self.session_import_limits, @@ -172,7 +167,6 @@ impl ExternalAgentConfigService { codex_home, connector_metadata_roots, external_agent_home, - analytics_events_client: None, auth_manager: codex_login::test_support::auth_manager_from_optional_auth( /*auth*/ None, ), diff --git a/codex-rs/feedback/Cargo.toml b/codex-rs/feedback/Cargo.toml index 80641bdd..6924d4e4 100644 --- a/codex-rs/feedback/Cargo.toml +++ b/codex-rs/feedback/Cargo.toml @@ -9,19 +9,12 @@ workspace = true [dependencies] anyhow = { workspace = true } -bytes = { workspace = true } -codex-http-client = { workspace = true } codex-login = { workspace = true } codex-protocol = { workspace = true } codex-rollout = { workspace = true } codex-state = { workspace = true } -flate2 = { workspace = true } -http = { workspace = true } -httpdate = { workspace = true } mime_guess = { workspace = true } -sentry = { version = "0.46", default-features = false } serde_json = { workspace = true } -tar = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["time"] } tracing = { workspace = true } @@ -32,7 +25,6 @@ zip = { workspace = true } log = { workspace = true } pretty_assertions = { workspace = true } tokio = { workspace = true, features = ["macros", "rt"] } -wiremock = { workspace = true } [lib] doctest = false diff --git a/codex-rs/feedback/src/archive_tests.rs b/codex-rs/feedback/src/archive_tests.rs index b789cdb3..26cd3d3e 100644 --- a/codex-rs/feedback/src/archive_tests.rs +++ b/codex-rs/feedback/src/archive_tests.rs @@ -1,13 +1,13 @@ use super::*; use crate::CodexFeedback; -use crate::FeedbackUploadOptions; +use crate::FeedbackSaveOptions; use pretty_assertions::assert_eq; use std::fs::File; use std::io::Read; use zip::ZipArchive; -fn options() -> FeedbackUploadOptions<'static> { - FeedbackUploadOptions { +fn options() -> FeedbackSaveOptions<'static> { + FeedbackSaveOptions { classification: "bug", reason: Some("synthetic feedback"), tags: None, @@ -126,7 +126,7 @@ fn save_preserves_report_and_log_consent() -> Result<()> { CodexFeedback::new() .snapshot(/*session_id*/ None) .save_feedback( - FeedbackUploadOptions { + FeedbackSaveOptions { include_logs, ..options() }, @@ -162,7 +162,7 @@ fn save_rejects_oversized_events_without_publishing() -> Result<()> { let error = CodexFeedback::new() .snapshot(/*session_id*/ None) .save_feedback( - FeedbackUploadOptions { + FeedbackSaveOptions { reason: Some(&reason), ..options() }, diff --git a/codex-rs/feedback/src/feedback_event_tests.rs b/codex-rs/feedback/src/feedback_event_tests.rs index 393201e8..ed8fdae1 100644 --- a/codex-rs/feedback/src/feedback_event_tests.rs +++ b/codex-rs/feedback/src/feedback_event_tests.rs @@ -1,14 +1,29 @@ -//! Feedback event contracts for titles, report grouping, and lossless comment bodies. +//! Local feedback report contracts for titles, tags, and lossless comment bodies. use crate::CodexFeedback; use pretty_assertions::assert_eq; -use sentry::protocol::Event; -use sentry::protocol::Exception; -use sentry::protocol::Level; +use serde_json::json; use std::collections::BTreeMap; +fn expected_report( + level: &str, + title: &str, + reason: Option<&str>, + tags: BTreeMap, +) -> serde_json::Value { + let mut report = json!({ + "level": level, + "message": title, + "tags": tags, + }); + if let Some(reason) = reason { + report["exception"] = json!({ "values": [{ "type": title, "value": reason }] }); + } + report +} + #[test] -fn custom_titles_preserve_comments_and_keep_submissions_separate() { +fn custom_titles_preserve_comments() { let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None); let tags = BTreeMap::from([ ( @@ -26,8 +41,8 @@ fn custom_titles_preserve_comments_and_keep_submissions_separate() { (Some(""), Some("")), (None, None), ] { - let event = - snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None); + let report = + snapshot.feedback_report("other", reason, Some(&tags), /*session_source*/ None); let mut expected_tags = tags.clone(); expected_tags.extend([ ("thread_id".to_string(), snapshot.thread_id.clone()), @@ -41,40 +56,20 @@ fn custom_titles_preserve_comments_and_keep_submissions_separate() { expected_tags.insert("reason".to_string(), reason_tag.to_string()); } assert_eq!( - event, - Event { - event_id: event.event_id, - timestamp: event.timestamp, - level: Level::Info, - message: Some(title.to_string()), - exception: reason - .map(|reason| Exception { - ty: title.to_string(), - value: Some(reason.to_string()), - ..Default::default() - }) - .into_iter() - .collect::>() - .into(), - tags: expected_tags, - fingerprint: vec![event.event_id.to_string().into()].into(), - ..Default::default() - } + report, + expected_report("info", title, reason, expected_tags) ); - let next_event = - snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None); - assert_ne!(event.fingerprint, next_event.fingerprint); } } #[test] -fn missing_or_blank_titles_preserve_session_titles_and_default_grouping() { +fn missing_or_blank_titles_preserve_session_titles() { let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None); let reason = " Feedback\nwith 🌍 context. "; for custom_title in [None, Some(""), Some(" \t\n\u{2003} ")] { let tags = custom_title .map(|title| BTreeMap::from([("feedback_title".to_string(), title.to_string())])); - let event = snapshot.feedback_event( + let report = snapshot.feedback_report( "bug", Some(reason), tags.as_ref(), @@ -95,21 +90,8 @@ fn missing_or_blank_titles_preserve_session_titles_and_default_grouping() { ), ]); assert_eq!( - event, - Event { - event_id: event.event_id, - timestamp: event.timestamp, - level: Level::Error, - message: Some(title.clone()), - exception: vec![Exception { - ty: title, - value: Some(reason.to_string()), - ..Default::default() - }] - .into(), - tags: expected_tags, - ..Default::default() - } + report, + expected_report("error", &title, Some(reason), expected_tags) ); } } @@ -128,26 +110,19 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() { ("a".repeat(201), "a".repeat(200)), (format!("{}extra", "界🌍".repeat(100)), "界🌍".repeat(100)), ] { - let event = snapshot.feedback_event( + let report = snapshot.feedback_report( "bug", Some(&reason), /*tags*/ None, /*session_source*/ None, ); assert_eq!( - event, - Event { - event_id: event.event_id, - timestamp: event.timestamp, - level: Level::Error, - message: Some(title.clone()), - exception: vec![Exception { - ty: title.clone(), - value: Some(reason), - ..Default::default() - }] - .into(), - tags: BTreeMap::from([ + report, + expected_report( + "error", + &title, + Some(&reason), + BTreeMap::from([ ("thread_id".to_string(), snapshot.thread_id.clone()), ("classification".to_string(), "bug".to_string()), ( @@ -156,8 +131,7 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() { ), ("reason".to_string(), preview), ]), - ..Default::default() - } + ) ); } } diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 6b651435..7b8773da 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -9,15 +9,8 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; -use std::time::Duration; -use std::time::Instant; -use anyhow::Context; use anyhow::Result; -use anyhow::anyhow; -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::RouteAwareClientPool; use codex_login::AuthEnvTelemetry; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; @@ -36,9 +29,6 @@ mod daemon_logs; pub use daemon_logs::daemon_log_attachments; pub(crate) mod feedback_diagnostics; mod guardian; -mod report_upload; -mod rollout_archive; -mod upload; pub use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; pub use feedback_diagnostics::FeedbackDiagnostic; pub use feedback_diagnostics::FeedbackDiagnostics; @@ -46,9 +36,6 @@ pub use guardian::GuardianReviewFailures; pub use guardian::GuardianReviewRecord; pub use guardian::guardian_review_failures; pub use guardian::record_guardian_review_failure; -pub use report_upload::FeedbackDelivery; -pub use report_upload::FeedbackTransport; -pub use report_upload::prepare_report_attachment; /// Filename used for the redacted `codex doctor --json` feedback attachment. pub const DOCTOR_REPORT_ATTACHMENT_FILENAME: &str = "codex-doctor-report.json"; @@ -59,24 +46,15 @@ pub const CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME: &str = "codex-app-direc /// Filename used for the Windows sandbox log feedback attachment. pub const WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME: &str = "windows-sandbox.log"; const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB -// aKode: the upstream Sentry DSN has been removed. This placeholder only keeps -// DSN parsing valid; `upload::send_envelope` refuses to send anything. -const SENTRY_DSN: &str = "https://disabled@127.0.0.1/0"; -const UPLOAD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 300); -// Raw collection budgets used by the report API, not the interactive upload. +// Raw collection budgets for rollout history attachments. pub const MAX_ATTACHMENT_BYTES: usize = 64 * 1024 * 1024; pub const MAX_ATTACHMENTS_BYTES: usize = 126 * 1024 * 1024; -// Bound decoded envelopes, including framing. Do not shorten attachments to fit: -// they may already be compressed, and callers need an error for incomplete delivery. -// This bounds the decoded request including framing, not guaranteed attachment storage. -// https://develop.sentry.dev/sdk/foundations/envelopes/#size-limits -const MAX_DECODED_UPLOAD_BYTES: usize = 200 * 1024 * 1024; const MAX_EVENT_BYTES: usize = 1024 * 1024; const FEEDBACK_TAGS_TARGET: &str = "feedback_tags"; // Leave room for every feature, usage settings, and request/auth diagnostics. const MAX_FEEDBACK_TAGS: usize = 512; -/// Structured request/auth fields that should be attached to feedback uploads. +/// Structured request/auth fields that should be attached to saved feedback reports. pub struct FeedbackRequestTags<'a> { pub endpoint: &'a str, pub auth_header_attached: bool, @@ -256,7 +234,7 @@ impl CodexFeedback { .with_filter( Targets::new() .with_default(Level::TRACE) - // Opted-in content belongs to the configured OTLP destination, not feedback. + // Opted-in content is never part of feedback. .with_target("codex_otel.log_only", LevelFilter::OFF) .with_target("codex_http_client::transport", LevelFilter::DEBUG) .with_target("codex_api::sse", LevelFilter::DEBUG) @@ -272,7 +250,7 @@ impl CodexFeedback { /// Returns a [`tracing_subscriber`] layer that collects structured metadata for feedback. /// /// Events with `target: "feedback_tags"` are treated as key/value tags to attach to feedback - /// uploads later. + /// saved reports later. pub fn metadata_layer(&self) -> impl Layer + Send + Sync + 'static where S: tracing::Subscriber + for<'a> LookupSpan<'a>, @@ -406,7 +384,7 @@ pub struct FeedbackSnapshot { pub struct FeedbackAttachmentPath { pub path: PathBuf, - /// Optional filename to use for the uploaded attachment instead of `path`'s basename. + /// Optional filename to use for the saved attachment instead of `path`'s basename. pub attachment_filename_override: Option, } @@ -511,32 +489,32 @@ impl FeedbackAttachmentPath { } } -/// In-memory attachment to include in a feedback upload. +/// In-memory attachment to include in a saved feedback report. /// /// Use this for generated diagnostics that should not be materialized on disk, /// such as the redacted doctor report. File-backed artifacts should use -/// `FeedbackAttachmentPath` so upload-time read failures can be logged and +/// `FeedbackAttachmentPath` so save-time read failures can be logged and /// skipped independently. pub struct FeedbackAttachment { - /// Attachment filename shown in Sentry and in the feedback consent UI. + /// Attachment filename shown in the saved archive and in the feedback consent UI. pub filename: String, /// Optional MIME type for consumers that render or classify attachments. pub content_type: Option, - /// Attachment bytes captured before the upload starts. + /// Attachment bytes captured before the report is saved. pub buffer: Vec, } -/// Inputs that control one feedback upload to Sentry. +/// Inputs that control one locally saved feedback report. /// /// The caller is responsible for applying any user-consent gate before setting /// `include_logs` or passing diagnostic attachments. This type only describes -/// what to upload once that decision has been made. -pub struct FeedbackUploadOptions<'a> { +/// what to save once that decision has been made. +pub struct FeedbackSaveOptions<'a> { pub classification: &'a str, pub reason: Option<&'a str>, pub tags: Option<&'a BTreeMap>, pub include_logs: bool, - /// Owned diagnostics and frozen rollout prefixes that are safe to upload. + /// Owned diagnostics and frozen rollout prefixes that are safe to save. /// /// Diagnostics follow `codex-logs.log`; rollout prefixes join the archive with /// path-backed rollouts. Callers must apply any user consent gate first. @@ -557,21 +535,17 @@ impl FeedbackSnapshot { .snapshot_bytes(); } - fn feedback_event( + /// Builds the local JSON report saved next to the feedback attachments. + fn feedback_report( &self, classification: &str, reason: Option<&str>, tags: Option<&BTreeMap>, session_source: Option<&SessionSource>, - ) -> sentry::protocol::Event<'static> { - use sentry::protocol::Event; - use sentry::protocol::Exception; - use sentry::protocol::Level; - use sentry::protocol::Values; - + ) -> serde_json::Value { let level = match classification { - "bug" | "bad_result" | "safety_check" => Level::Error, - _ => Level::Info, + "bug" | "bad_result" | "safety_check" => "error", + _ => "info", }; let custom_title = tags .and_then(|tags| tags.get("feedback_title")) @@ -587,24 +561,17 @@ impl FeedbackSnapshot { }, str::to_owned, ); - let mut event = Event { - level, - message: Some(title.clone()), - tags: self.upload_tags(classification, reason, tags, session_source), - ..Default::default() - }; - if custom_title.is_some() { - // A shared title must not merge independent reports and suppress new-issue alerts. - event.fingerprint = vec![event.event_id.to_string().into()].into(); - } + let mut report = serde_json::json!({ + "level": level, + "message": title, + "tags": self.report_tags(classification, reason, tags, session_source), + }); if let Some(reason) = reason { - event.exception = Values::from(vec![Exception { - ty: title, - value: Some(reason.to_string()), - ..Default::default() - }]); + report["exception"] = serde_json::json!({ + "values": [{ "type": title, "value": reason }], + }); } - event + report } pub fn log_attachment(&self, logs_override: Option>) -> FeedbackAttachment { @@ -632,28 +599,10 @@ impl FeedbackSnapshot { self.feedback_diagnostics.attachment_text() } - /// Submit feedback to Sentry with whole attachments within a shared deadline. - /// Success means HTTP acceptance, not durable attachment storage. Callers must - /// retain their source files; errors can occur after part of a report is accepted. - /// https://github.com/getsentry/relay/blob/master/relay-server/src/endpoints/common.rs - pub async fn upload_feedback( - &self, - options: FeedbackUploadOptions<'_>, - http_client_factory: &HttpClientFactory, - ) -> Result<()> { - self.upload_feedback_with_dsn( - options, - http_client_factory, - SENTRY_DSN, - Instant::now() + UPLOAD_TIMEOUT, - ) - .await - } - - /// Atomically saves the consent-selected report and attachments without uploading. + /// Atomically saves the consent-selected report and attachments to a local file. /// Existing paths are rejected and failures never publish a partial archive. - pub fn save_feedback(&self, options: FeedbackUploadOptions<'_>, path: &Path) -> Result<()> { - let report = serde_json::to_vec(&self.feedback_event( + pub fn save_feedback(&self, options: FeedbackSaveOptions<'_>, path: &Path) -> Result<()> { + let report = serde_json::to_vec(&self.feedback_report( options.classification, options.reason, options.tags, @@ -690,144 +639,7 @@ impl FeedbackSnapshot { ) } - async fn upload_feedback_with_dsn( - &self, - options: FeedbackUploadOptions<'_>, - http_client_factory: &HttpClientFactory, - dsn: &str, - deadline: Instant, - ) -> Result<()> { - use std::str::FromStr; - - use sentry::protocol::Envelope; - use sentry::protocol::EnvelopeItem; - use sentry::types::Dsn; - - let started_at = Instant::now(); - let dsn = Dsn::from_str(dsn).map_err(|error| anyhow!("invalid DSN: {error}"))?; - - let event = self.feedback_event( - options.classification, - options.reason, - options.tags, - options.session_source.as_ref(), - ); - let mut envelope = Envelope::new(); - envelope.add_item(EnvelopeItem::Event(event)); - let (event_body, event_bytes) = - upload::encode_envelope(&envelope).context("failed to serialize feedback event")?; - anyhow::ensure!( - event_bytes <= MAX_EVENT_BYTES, - "feedback event exceeds the size limit" - ); - let headers = envelope.headers().clone(); - drop(envelope); - let client_pool = RouteAwareClientPool::new_without_redirects_or_request_logging( - http_client_factory.clone(), - ClientRouteClass::Other, - ); - // Accept the report before reading diagnostics; all envelopes share one deadline. - let mut rate_limited = false; - let status = upload::send_envelope( - &client_pool, - &dsn, - event_body, - upload::EnvelopeKind::Event, - deadline, - &mut rate_limited, - ) - .await?; - anyhow::ensure!( - status.is_success(), - "Sentry rejected feedback upload with HTTP status {status}" - ); - - let mut attachments = self.feedback_attachments( - &headers, - options.include_logs, - options.extra_attachments, - options.extra_attachment_paths, - options.logs_override, - ); - let mut uploaded_attachments = 0; - let mut attachments_failed = false; - // Keep attachments linked to the accepted event, without replaying its contents. - // Inspect the upper bound without reading the next file after the deadline. - while attachments.size_hint().1 != Some(0) { - if rate_limited || Instant::now() >= deadline { - attachments_failed = true; - tracing::error!( - reason = if rate_limited { - "rate limit" - } else { - "upload deadline" - }, - "remaining feedback attachments skipped" - ); - break; - } - let Some(attachment) = attachments.next() else { - break; - }; - if Instant::now() >= deadline { - attachments_failed = true; - tracing::error!( - "remaining feedback attachments skipped: upload deadline reached while reading attachment" - ); - break; - } - let mut status = None; - let result: Result<()> = async { - let body = upload::encode_attachment_envelope(&headers, attachment?)?; - let response_status = upload::send_envelope( - &client_pool, - &dsn, - body, - upload::EnvelopeKind::Attachment, - deadline, - &mut rate_limited, - ) - .await - .map_err(|error| { - // Transport error strings can contain credential-bearing URLs. - if let Some(cause) = error.downcast_ref::() { - anyhow!( - "feedback transport failed: class={:?}, timeout={}, connect={}, request={}, body={}", - cause.failure_class(), cause.is_timeout(), cause.is_connect(), cause.is_request(), cause.is_body() - ) - } else { - error - } - })?; - - status = Some(response_status.as_u16()); - anyhow::ensure!(response_status.is_success(), "Sentry rejected attachment"); - Ok(()) - } - .await; - if let Err(error) = result { - attachments_failed = true; - // Keep trying other diagnostics before reporting the partial failure. - tracing::error!(status, error = %format!("{error:#}"), "feedback attachment upload failed; continuing"); - } else { - uploaded_attachments += 1; - } - } - tracing::info!( - thread_id = %self.thread_id, - uploaded_attachments, - attachments_failed, - elapsed_ms = started_at.elapsed().as_millis(), - "feedback event uploaded to Sentry" - ); - anyhow::ensure!( - !attachments_failed, - "feedback report was accepted, but some attachments failed to upload" - ); - Ok(()) - } - - fn upload_tags( + fn report_tags( &self, classification: &str, reason: Option<&str>, @@ -844,8 +656,8 @@ impl FeedbackSnapshot { tags.insert(String::from("session_source"), source.to_string()); } if let Some(reason) = reason { - // Sentry tags cannot contain newlines or exceed 200 characters. Keep the - // full comment in the exception body and a preview for tag consumers. + // Keep the full comment in the exception body and a single-line, + // 200-character preview for tag consumers. let preview = reason .chars() .take(200) @@ -882,105 +694,6 @@ impl FeedbackSnapshot { tags } - - fn feedback_attachments<'a>( - &'a self, - headers: &'a sentry::protocol::EnvelopeHeaders, - include_logs: bool, - extra_attachments: Vec, - extra_attachment_paths: &'a [FeedbackAttachmentPath], - logs_override: Option>, - ) -> impl Iterator> + 'a { - use sentry::protocol::Attachment; - - // Partition metadata without reading files before the event is accepted. Keep - // generated diagnostics first, then rollouts, then remaining files in caller order. - let (rollouts, diagnostics_attachments): (Vec<_>, Vec<_>) = - extra_attachments.into_iter().partition(|attachment| { - codex_rollout::rollout_id_from_path(Path::new(&attachment.filename)).is_some() - }); - let (rollout_paths, diagnostic_paths): (Vec<_>, Vec<_>) = - extra_attachment_paths.iter().partition(|attachment| { - codex_rollout::rollout_id_from_path(&attachment.path).is_some() - }); - let has_rollouts = !rollouts.is_empty() || !rollout_paths.is_empty(); - let archive = has_rollouts - .then_some((rollout_paths, rollouts)) - .into_iter() - .flat_map(move |(paths, rollouts)| { - let archive = - tempfile::tempdir() - .map_err(anyhow::Error::from) - .and_then(|directory| { - let output_path = directory.path().join("rollouts.tar.gz"); - let Some(archive) = rollout_archive::archive_rollouts( - &output_path, - paths.iter().copied(), - &rollouts, - MAX_DECODED_UPLOAD_BYTES, - )? - else { - return Ok(None); - }; - let attachment = archive - .read_attachment(MAX_DECODED_UPLOAD_BYTES)? - .context("rollout archive is missing or exceeds the size limit")?; - // Measure framing without copying the archive. Account for the extra - // decimal digits when the empty attachment's length becomes nonzero. - let mut envelope = - sentry::protocol::Envelope::new().with_headers(headers.clone()); - envelope.add_item(Attachment { - filename: attachment.filename.clone(), - content_type: attachment.content_type.clone(), - ..Default::default() - }); - let mut framing = Vec::new(); - envelope.to_writer(&mut framing)?; - let archive_bytes = attachment.buffer.len(); - let envelope_bytes = framing.len() - + archive_bytes - + archive_bytes.checked_ilog10().unwrap_or(0) as usize; - anyhow::ensure!( - envelope_bytes <= MAX_DECODED_UPLOAD_BYTES, - "rollout archive envelope exceeds the size limit" - ); - Ok(Some(attachment)) - }); - rollout_archive::with_individual_fallback( - archive, - paths, - rollouts, - MAX_DECODED_UPLOAD_BYTES, - ) - }); - let logs = include_logs.then(|| self.log_attachment(logs_override)); - let diagnostics = self - .feedback_diagnostics_attachment_text(include_logs) - .map(|text| FeedbackAttachment { - buffer: text.into_bytes(), - filename: FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME.to_string(), - content_type: Some("text/plain".to_string()), - }); - - logs.into_iter() - .chain(diagnostics_attachments) - .chain(diagnostics) - .map(Ok) - .chain(archive) - .chain(diagnostic_paths.into_iter().map(|attachment_path| { - attachment_path - .read_attachment(MAX_DECODED_UPLOAD_BYTES)? - .context("feedback attachment is not a regular file or exceeds the size limit") - })) - .map(|attachment| { - attachment.map(|attachment| Attachment { - buffer: attachment.buffer, - filename: attachment.filename, - content_type: attachment.content_type, - ty: None, - }) - }) - } } fn display_classification(classification: &str) -> String { diff --git a/codex-rs/feedback/src/lib_tests.rs b/codex-rs/feedback/src/lib_tests.rs index f11620fa..7bb92f03 100644 --- a/codex-rs/feedback/src/lib_tests.rs +++ b/codex-rs/feedback/src/lib_tests.rs @@ -2,16 +2,12 @@ //! Unit tests for the crate and its related test suites. -use std::ffi::OsStr; use std::fs; use super::*; -use crate::FeedbackDiagnostic; -use codex_http_client::OutboundProxyPolicy; use pretty_assertions::assert_eq; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; -use wiremock::MockServer; #[test] fn ring_buffer_drops_front_when_full() { @@ -94,132 +90,6 @@ fn metadata_layer_records_tags_from_feedback_target() { pretty_assertions::assert_eq!(snap.tags.get("cached").map(String::as_str), Some("true")); } -async fn upload_test_feedback( - feedback: &CodexFeedback, - dsn: &str, - extra_attachments: Vec, -) -> Result<()> { - feedback - .snapshot(/*session_id*/ None) - .with_feedback_diagnostics(FeedbackDiagnostics::default()) - .upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: Some("private feedback"), - tags: None, - include_logs: true, - extra_attachments, - extra_attachment_paths: &[], - session_source: Some(SessionSource::Cli), - logs_override: Some(b"private log contents".to_vec()), - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - dsn, - Instant::now() + UPLOAD_TIMEOUT, - ) - .await -} - -// aKode: feedback is never uploaded; the upload path fails without sending any request. -#[tokio::test] -async fn feedback_upload_is_disabled_and_sends_nothing() { - let server = MockServer::start().await; - let dsn = format!("http://public@{}/42", server.address()); - - upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new()) - .await - .expect_err("feedback upload must be disabled"); - - assert!(server.received_requests().await.unwrap().is_empty()); -} - -#[test] -fn feedback_attachments_gate_connectivity_diagnostics() { - let extra_filename = format!("codex-feedback-extra-{}.jsonl", ThreadId::new()); - let extra_path = std::env::temp_dir().join(&extra_filename); - let extra_attachment_path = FeedbackAttachmentPath { - path: extra_path.clone(), - attachment_filename_override: None, - }; - fs::write(&extra_path, "rollout").expect("extra attachment should be written"); - - let snapshot_with_diagnostics = CodexFeedback::new() - .snapshot(/*session_id*/ None) - .with_feedback_diagnostics(FeedbackDiagnostics::new(vec![FeedbackDiagnostic { - headline: "Proxy environment variables are set and may affect connectivity." - .to_string(), - details: vec!["HTTPS_PROXY = https://example.com:443".to_string()], - }])); - - let attachments_with_diagnostics = snapshot_with_diagnostics - .feedback_attachments( - &sentry::protocol::EnvelopeHeaders::default(), - /*include_logs*/ true, - vec![FeedbackAttachment { - filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(), - content_type: Some("application/json".to_string()), - buffer: b"{\"overallStatus\":\"ok\"}".to_vec(), - }], - &[extra_attachment_path], - Some(vec![1]), - ) - .collect::>>() - .unwrap(); - - assert_eq!( - attachments_with_diagnostics - .iter() - .map(|attachment| attachment.filename.as_str()) - .collect::>(), - vec![ - "codex-logs.log", - DOCTOR_REPORT_ATTACHMENT_FILENAME, - FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME, - extra_filename.as_str() - ] - ); - assert_eq!(attachments_with_diagnostics[0].buffer, vec![1]); - assert_eq!( - attachments_with_diagnostics[1].buffer, - b"{\"overallStatus\":\"ok\"}".to_vec() - ); - assert_eq!( - attachments_with_diagnostics[2].buffer, - b"Connectivity diagnostics\n\n- Proxy environment variables are set and may affect connectivity.\n - HTTPS_PROXY = https://example.com:443".to_vec() - ); - assert_eq!(attachments_with_diagnostics[3].buffer, b"rollout".to_vec()); - assert_eq!( - attachments_with_diagnostics[3].content_type.as_deref(), - Some("text/plain") - ); - assert_eq!( - OsStr::new(attachments_with_diagnostics[3].filename.as_str()), - OsStr::new(extra_filename.as_str()) - ); - let attachments_without_diagnostics = CodexFeedback::new() - .snapshot(/*session_id*/ None) - .with_feedback_diagnostics(FeedbackDiagnostics::default()) - .feedback_attachments( - &sentry::protocol::EnvelopeHeaders::default(), - /*include_logs*/ true, - Vec::new(), - &[], - Some(vec![1]), - ) - .collect::>>() - .unwrap(); - - assert_eq!( - attachments_without_diagnostics - .iter() - .map(|attachment| attachment.filename.as_str()) - .collect::>(), - vec!["codex-logs.log"] - ); - assert_eq!(attachments_without_diagnostics[0].buffer, vec![1]); - fs::remove_file(extra_path).expect("extra attachment should be removed"); -} - #[test] fn path_backed_attachments_use_binary_content_types() { let suffix = ThreadId::new(); @@ -232,26 +102,18 @@ fn path_backed_attachments_use_binary_content_types() { fs::write(&gzip_path, gzip_bytes).expect("gzip attachment should be written"); fs::write(&unknown_path, unknown_bytes).expect("unknown attachment should be written"); - let attachments = CodexFeedback::new() - .snapshot(/*session_id*/ None) - .feedback_attachments( - &sentry::protocol::EnvelopeHeaders::default(), - /*include_logs*/ false, - Vec::new(), - &[ - FeedbackAttachmentPath { - path: gzip_path.clone(), - attachment_filename_override: None, - }, - FeedbackAttachmentPath { - path: unknown_path.clone(), - attachment_filename_override: None, - }, - ], - /*logs_override*/ None, - ) - .collect::>>() - .unwrap(); + let attachments = [&gzip_path, &unknown_path] + .into_iter() + .map(|path| { + FeedbackAttachmentPath { + path: path.clone(), + attachment_filename_override: None, + } + .read_attachment(DEFAULT_MAX_BYTES) + .unwrap() + .expect("attachment should be readable") + }) + .collect::>(); fs::remove_file(gzip_path).expect("gzip attachment should be removed"); fs::remove_file(unknown_path).expect("unknown attachment should be removed"); @@ -280,7 +142,7 @@ fn path_backed_attachments_use_binary_content_types() { } #[test] -fn upload_tags_include_client_tags_and_preserve_reserved_fields() { +fn report_tags_include_client_tags_and_preserve_reserved_fields() { let mut tags = BTreeMap::new(); tags.insert("thread_id".to_string(), "wrong-thread".to_string()); tags.insert("turn_id".to_string(), "wrong-turn".to_string()); @@ -320,7 +182,7 @@ fn upload_tags_include_client_tags_and_preserve_reserved_fields() { client_tags.insert("model".to_string(), "mewthree".to_string()); client_tags.insert("effort".to_string(), "Some(Ultra)".to_string()); - let upload_tags = snapshot.upload_tags( + let report_tags = snapshot.report_tags( "bug", Some("actual reason"), Some(&client_tags), @@ -328,39 +190,39 @@ fn upload_tags_include_client_tags_and_preserve_reserved_fields() { ); assert_eq!( - upload_tags.get("thread_id").map(String::as_str), + report_tags.get("thread_id").map(String::as_str), Some("thread-123") ); assert_eq!( - upload_tags.get("turn_id").map(String::as_str), + report_tags.get("turn_id").map(String::as_str), Some("turn-456") ); assert_eq!( - upload_tags.get("classification").map(String::as_str), + report_tags.get("classification").map(String::as_str), Some("bug") ); assert_eq!( - upload_tags.get("session_source").map(String::as_str), + report_tags.get("session_source").map(String::as_str), Some("cli") ); assert_eq!( - upload_tags.get("reason").map(String::as_str), + report_tags.get("reason").map(String::as_str), Some("actual reason") ); assert_eq!( - upload_tags.get("account_id").map(String::as_str), + report_tags.get("account_id").map(String::as_str), Some("actual-account") ); assert_eq!( - upload_tags.get("model").map(String::as_str), + report_tags.get("model").map(String::as_str), Some("mewthree") ); assert_eq!( - upload_tags.get("effort").map(String::as_str), + report_tags.get("effort").map(String::as_str), Some("Some(Ultra)") ); assert_eq!( - upload_tags.get("client_tag").map(String::as_str), + report_tags.get("client_tag").map(String::as_str), Some("from-client") ); } diff --git a/codex-rs/feedback/src/metadata_tests.rs b/codex-rs/feedback/src/metadata_tests.rs index f214ccae..922d0309 100644 --- a/codex-rs/feedback/src/metadata_tests.rs +++ b/codex-rs/feedback/src/metadata_tests.rs @@ -1,10 +1,8 @@ -//! Exercise dynamic tag collection, upload serialization, and bounded updates. +//! Exercise dynamic tag collection, report serialization, and bounded updates. use crate::CodexFeedback; use crate::*; use pretty_assertions::assert_eq; -use sentry::protocol::Envelope; -use sentry::protocol::EnvelopeItem; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; @@ -35,7 +33,7 @@ fn refreshing_logs_preserves_captured_metadata() { } #[test] -fn dynamic_tags_survive_upload_alongside_static_fields() { +fn dynamic_tags_survive_in_report_alongside_static_fields() { let feedback = CodexFeedback::new(); let _guard = tracing_subscriber::registry() .with(feedback.metadata_layer()) @@ -57,7 +55,7 @@ fn dynamic_tags_survive_upload_alongside_static_fields() { expected.insert("model".to_string(), "test-model".to_string()); let snapshot = feedback.snapshot(/*session_id*/ None); assert_eq!(snapshot.tags, expected); - let event = snapshot.feedback_event( + let report = snapshot.feedback_report( "bug", /*reason*/ None, /*tags*/ None, /*session_source*/ None, ); expected.extend([ @@ -68,10 +66,8 @@ fn dynamic_tags_survive_upload_alongside_static_fields() { env!("CARGO_PKG_VERSION").to_string(), ), ]); - assert_eq!(event.tags, expected); - let mut envelope = Envelope::new(); - envelope.add_item(EnvelopeItem::Event(event)); - let (_, size) = crate::upload::encode_envelope(&envelope).unwrap(); + assert_eq!(report["tags"], serde_json::json!(expected)); + let size = serde_json::to_vec(&report).unwrap().len(); assert!(size < crate::MAX_EVENT_BYTES); } diff --git a/codex-rs/feedback/src/report_upload.rs b/codex-rs/feedback/src/report_upload.rs deleted file mode 100644 index 56f9ee54..00000000 --- a/codex-rs/feedback/src/report_upload.rs +++ /dev/null @@ -1,154 +0,0 @@ -use std::collections::BTreeMap; -use std::time::Duration; - -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::RouteAwareClientPool; -use codex_protocol::protocol::SessionSource; -use http::StatusCode; -use sentry::protocol::Attachment; -use sentry::protocol::Envelope; -use sentry::protocol::EnvelopeHeaders; -use sentry::protocol::EnvelopeItem; -use sentry::types::Dsn; -use sentry::types::Uuid; - -use crate::FeedbackAttachment; -use crate::FeedbackSnapshot; -use crate::MAX_DECODED_UPLOAD_BYTES; -use crate::MAX_EVENT_BYTES; -use crate::SENTRY_DSN; -use crate::upload; - -// Background parts must tolerate slow links without inheriting the interactive -// upload's ten-second budget. The report API can cancel the request at any time. -const REPORT_PART_UPLOAD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 300); - -/// The upstream HTTP result, not proof of durable storage in Sentry. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum FeedbackDelivery { - Accepted { - retry_after: Option, - }, - Rejected { - status: u16, - retry_after: Option, - }, - /// No response was received. The upstream may still have accepted the envelope. - Unconfirmed, -} - -/// Sends persisted report parts without retries or request diagnostics. -pub struct FeedbackTransport { - client_pool: RouteAwareClientPool, - dsn: Dsn, -} - -impl FeedbackTransport { - pub fn new(http_client_factory: HttpClientFactory) -> Result { - Ok(Self { - client_pool: RouteAwareClientPool::new_without_redirects_or_request_logging( - http_client_factory, - ClientRouteClass::Other, - ), - dsn: SENTRY_DSN - .parse() - .map_err(|_| anyhow!("invalid feedback DSN"))?, - }) - } - - /// Make one attempt. Callers own retry decisions and must retain the same bytes. - pub async fn send(&self, envelope: Vec) -> FeedbackDelivery { - let response = upload::envelope_request( - &self.client_pool, - &self.dsn, - envelope.into(), - REPORT_PART_UPLOAD_TIMEOUT, - ) - .send() - .await; - let Ok(response) = response else { - return FeedbackDelivery::Unconfirmed; - }; - let status = response.status(); - let headers = response.headers(); - let mut retry_after = headers - .get_all("Retry-After") - .iter() - .map(|value| { - upload::parse_retry_after(value.to_str().unwrap_or_default()) - .unwrap_or(upload::DEFAULT_RATE_LIMIT) - }) - .max(); - // Report events and attachments share one conservative cooldown. Honor quotas on - // successful responses too; ignore quotas for unrelated Sentry categories. - // https://develop.sentry.dev/sdk/foundations/transport/rate-limiting/ - retry_after = retry_after.max(upload::sentry_rate_limit_delay(headers)); - if status == StatusCode::TOO_MANY_REQUESTS && retry_after.is_none() { - retry_after = Some(upload::DEFAULT_RATE_LIMIT); - } - if status.is_success() { - FeedbackDelivery::Accepted { retry_after } - } else { - FeedbackDelivery::Rejected { - status: status.as_u16(), - retry_after, - } - } - } -} - -impl FeedbackSnapshot { - /// Prepare only the core report, using the caller's stable UUID as its Sentry event ID. - pub fn prepare_report_event( - &self, - report_id: &str, - classification: &str, - reason: Option<&str>, - tags: Option<&BTreeMap>, - session_source: Option<&SessionSource>, - ) -> Result> { - let mut event = self.feedback_event(classification, reason, tags, session_source); - // Auth tags must come from this report's caller, not metadata retained - // from an earlier account in the process-wide tracing layer. - event.tags.retain(|key, _| { - !matches!(key.as_str(), "account_id" | "chatgpt_user_id") - || tags.is_some_and(|tags| tags.contains_key(key)) - }); - event.event_id = - Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?; - let mut envelope = Envelope::new(); - envelope.add_item(EnvelopeItem::Event(event)); - prepare_envelope(envelope, MAX_EVENT_BYTES) - } -} - -/// Prepare one whole attachment linked to an existing report, without replaying its event. -/// The caller must apply consent and the report's cumulative attachment budget first. -pub fn prepare_report_attachment( - report_id: &str, - attachment: FeedbackAttachment, -) -> Result> { - let event_id = Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?; - let mut envelope = Envelope::new().with_headers(EnvelopeHeaders::new().with_event_id(event_id)); - envelope.add_item(EnvelopeItem::Attachment(Attachment { - buffer: attachment.buffer, - filename: attachment.filename, - content_type: attachment.content_type, - ty: None, - })); - prepare_envelope(envelope, MAX_DECODED_UPLOAD_BYTES) -} - -fn prepare_envelope(envelope: Envelope, max_decoded_bytes: usize) -> Result> { - let (bytes, decoded_bytes) = - upload::encode_envelope(&envelope).context("failed to serialize feedback envelope")?; - anyhow::ensure!( - decoded_bytes <= max_decoded_bytes, - "feedback envelope exceeds the size limit" - ); - Ok(bytes) -} diff --git a/codex-rs/feedback/src/rollout_archive.rs b/codex-rs/feedback/src/rollout_archive.rs deleted file mode 100644 index c68bd9a9..00000000 --- a/codex-rs/feedback/src/rollout_archive.rs +++ /dev/null @@ -1,148 +0,0 @@ -//! Writes selected rollouts to a bounded gzip tar at a caller-provided local path. -//! Invalid inputs are logged and skipped; only a complete archive is published. -//! Archive failures fall back to lazy individual attachments using the original sources. - -use std::collections::HashSet; -use std::fs; -use std::io; -use std::io::BufWriter; -use std::io::Write; -use std::path::Path; - -use anyhow::Context; -use anyhow::Result; -use flate2::Compression; -use flate2::write::GzEncoder; - -use crate::FeedbackAttachment; -use crate::FeedbackAttachmentPath; - -pub(super) fn archive_rollouts<'a>( - output_path: &Path, - rollout_paths: impl IntoIterator, - rollouts: impl IntoIterator, - max_bytes: usize, -) -> Result> { - let parent = output_path - .parent() - .filter(|path| !path.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")); - fs::create_dir_all(parent).context("failed to create rollout archive directory")?; - let file = tempfile::NamedTempFile::new_in(parent)?; - let writer = BoundedWriter { - inner: BufWriter::new(file), - written: 0, - max_bytes, - }; - let mut archive = tar::Builder::new(GzEncoder::new(writer, Compression::default())); - let mut filenames = HashSet::new(); - for path in rollout_paths { - match path.read_attachment(max_bytes) { - Ok(Some(rollout)) => append_rollout(&mut archive, &mut filenames, &rollout, max_bytes)?, - Ok(None) => {} // The attachment reader already logs oversized or nonregular files. - Err(error) => tracing::error!(%error, "failed to read rollout; skipping attachment"), - } - } - for rollout in rollouts { - append_rollout(&mut archive, &mut filenames, rollout, max_bytes)?; - } - if filenames.is_empty() { - return Ok(None); - } - let writer = archive - .into_inner()? - .finish() - .context("failed to finish rollout archive")?; - let file = writer.inner.into_inner()?; - // Keep failed writes and incomplete gzip streams out of the destination path. - file.persist_noclobber(output_path)?; - Ok(Some(FeedbackAttachmentPath { - path: output_path.to_path_buf(), - attachment_filename_override: None, - })) -} - -pub(super) fn with_individual_fallback<'a>( - archive: Result>, - rollout_paths: Vec<&'a FeedbackAttachmentPath>, - rollouts: Vec, - max_bytes: usize, -) -> impl Iterator> + 'a { - let (archive, fallback) = match archive { - Ok(archive) => (archive, false), - Err(error) => { - tracing::error!(%error, "rollout archiving failed; uploading individual attachments"); - (None, true) - } - }; - archive - .into_iter() - .map(Ok) - .chain(fallback.then_some(rollouts).into_iter().flatten().map(Ok)) - .chain( - fallback - .then_some(rollout_paths) - .into_iter() - .flatten() - .map(move |path| { - path.read_attachment(max_bytes)?.context( - "feedback attachment is not a regular file or exceeds the size limit", - ) - }), - ) -} - -fn append_rollout( - archive: &mut tar::Builder, - filenames: &mut HashSet, - rollout: &FeedbackAttachment, - max_bytes: usize, -) -> Result<()> { - if rollout.buffer.len() > max_bytes { - tracing::error!( - bytes = rollout.buffer.len(), - max_bytes, - "rollout skipped: size limit exceeded" - ); - return Ok(()); - } - if rollout.filename.is_empty() - || matches!(rollout.filename.as_str(), "." | "..") - || rollout.filename.contains(['/', '\\', ':']) - || filenames.contains(&rollout.filename) - { - tracing::error!("rollout skipped: invalid or duplicate archive filename"); - return Ok(()); - } - let mut header = tar::Header::new_gnu(); - header.set_size(rollout.buffer.len() as u64); - header.set_mode(0o600); - header.set_mtime(0); - header.set_entry_type(tar::EntryType::Regular); - archive - .append_data(&mut header, &rollout.filename, rollout.buffer.as_slice()) - .context("failed to write rollout archive")?; - filenames.insert(rollout.filename.clone()); - Ok(()) -} - -struct BoundedWriter { - inner: W, - written: usize, - max_bytes: usize, -} - -impl Write for BoundedWriter { - fn write(&mut self, buffer: &[u8]) -> io::Result { - if buffer.len() > self.max_bytes.saturating_sub(self.written) { - return Err(io::Error::other("rollout archive exceeds the size limit")); - } - let written = self.inner.write(buffer)?; - self.written += written; - Ok(written) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} diff --git a/codex-rs/feedback/src/save_rollout_tests.rs b/codex-rs/feedback/src/save_rollout_tests.rs index 2036490d..1fa08609 100644 --- a/codex-rs/feedback/src/save_rollout_tests.rs +++ b/codex-rs/feedback/src/save_rollout_tests.rs @@ -90,18 +90,5 @@ fn save_preserves_duplicate_names_and_rejects_missing_selected_files() -> Result .unwrap_err(); assert!(format!("{error:#}").contains("selected attachment")); assert_eq!(fs::read_dir(output.path())?.count(), 0); - // Upload still uses its existing best-effort aggregation and skips the missing rollout. - let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None); - let uploaded = snapshot - .feedback_attachments( - &sentry::protocol::EnvelopeHeaders::default(), - /*include_logs*/ false, - Vec::new(), - &paths, - /*logs_override*/ None, - ) - .collect::>>()?; - assert_eq!(uploaded.len(), 1); - assert_eq!(uploaded[0].filename, "rollouts.tar.gz"); Ok(()) } diff --git a/codex-rs/feedback/src/upload.rs b/codex-rs/feedback/src/upload.rs deleted file mode 100644 index 256da2eb..00000000 --- a/codex-rs/feedback/src/upload.rs +++ /dev/null @@ -1,153 +0,0 @@ -use std::io; -use std::io::Write; -use std::time::Duration; -use std::time::Instant; -use std::time::SystemTime; - -use anyhow::Result; -use bytes::Bytes; -use codex_http_client::RequestBuilder; -use codex_http_client::RouteAwareClientPool; -use flate2::Compression; -use flate2::write::GzEncoder; -use http::HeaderMap; -use http::StatusCode; -use sentry::ClientOptions; -use sentry::protocol::Attachment; -use sentry::protocol::Envelope; -use sentry::protocol::EnvelopeHeaders; -use sentry::protocol::EnvelopeItem; -use sentry::types::Dsn; - -use crate::MAX_DECODED_UPLOAD_BYTES; - -pub(super) const DEFAULT_RATE_LIMIT: Duration = Duration::from_secs(/*secs*/ 60); - -pub(super) enum EnvelopeKind { - Event, - Attachment, -} - -pub(super) fn envelope_request( - client_pool: &RouteAwareClientPool, - dsn: &Dsn, - body: Bytes, - timeout: Duration, -) -> RequestBuilder { - let sentry_options = ClientOptions::default(); - let sentry_auth = dsn.to_auth(Some(sentry_options.user_agent.as_ref())); - let request = client_pool - .post(dsn.envelope_api_url().as_str()) - .header("X-Sentry-Auth", sentry_auth.to_string()); - // Persisted parts retain their encoding. Gzip's magic bytes cannot begin - // an uncompressed envelope, which starts with a JSON header. - let request = if body.starts_with(&[0x1f, 0x8b]) { - request.header("Content-Encoding", "gzip") - } else { - request - }; - request.body(body).timeout(timeout) -} - -/// Send an already-serialized envelope within the report's shared deadline. -/// -/// aKode: feedback is never uploaded to a remote service (upstream sent it to -/// Sentry). The signature is kept so callers compile; it always fails. -pub(super) async fn send_envelope( - _client_pool: &RouteAwareClientPool, - _dsn: &Dsn, - _body: Vec, - _kind: EnvelopeKind, - _deadline: Instant, - _rate_limited: &mut bool, -) -> Result { - anyhow::bail!("feedback upload is disabled in aKode; use the local save option instead") -} - -pub(super) fn sentry_rate_limit_delay(headers: &HeaderMap) -> Option { - let mut retry_after = None; - for value in headers.get_all("X-Sentry-Rate-Limits") { - for quota in value.to_str().unwrap_or_default().split(',') { - let mut fields = quota.trim().split(':'); - let seconds = fields.next().unwrap_or_default(); - let categories = fields.next().unwrap_or_default(); - if !categories.is_empty() - && !categories - .split(';') - .any(|category| matches!(category, "error" | "attachment")) - { - continue; - } - let delay = seconds - .parse::() - .ok() - .and_then(|seconds| Duration::try_from_secs_f64(seconds.ceil()).ok()) - .unwrap_or(DEFAULT_RATE_LIMIT); - retry_after = retry_after.max(Some(delay)); - } - } - retry_after -} - -pub(super) fn parse_retry_after(value: &str) -> Option { - value - .parse::() - .map(Duration::from_secs) - .or_else(|_| { - httpdate::parse_http_date(value) - .map(|date| date.duration_since(SystemTime::now()).unwrap_or_default()) - }) - .ok() -} - -pub(super) fn encode_envelope(envelope: &Envelope) -> io::Result<(Vec, usize)> { - let mut writer = CountingWriter { - inner: GzEncoder::new(Vec::new(), Compression::fast()), - bytes: 0, - }; - envelope.to_writer(&mut writer)?; - let decoded_bytes = writer.bytes; - let mut body = writer.inner.finish()?; - // Already-compressed attachments can grow beyond Sentry's 200 MiB wire limit. - // Reuse the buffer for the raw envelope when gzip does not make it smaller. - if body.len() >= decoded_bytes { - body.clear(); - envelope.to_writer(&mut body)?; - } - Ok((body, decoded_bytes)) -} - -pub(super) fn encode_attachment_envelope( - headers: &EnvelopeHeaders, - attachment: Attachment, -) -> Result> { - anyhow::ensure!( - attachment.buffer.len() <= MAX_DECODED_UPLOAD_BYTES, - "feedback attachment exceeds the size limit" - ); - let mut envelope = Envelope::new().with_headers(headers.clone()); - envelope.add_item(EnvelopeItem::Attachment(attachment)); - let (body, decoded_bytes) = encode_envelope(&envelope)?; - anyhow::ensure!( - decoded_bytes <= MAX_DECODED_UPLOAD_BYTES, - "feedback attachment envelope exceeds the size limit" - ); - Ok(body) -} - -struct CountingWriter { - inner: W, - bytes: usize, -} - -impl Write for CountingWriter { - fn write(&mut self, buf: &[u8]) -> io::Result { - let written = self.inner.write(buf)?; - self.bytes += written; - Ok(written) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} diff --git a/codex-rs/guardian-context/src/history.rs b/codex-rs/guardian-context/src/history.rs index 7c1e7f3e..ecdb81a6 100644 --- a/codex-rs/guardian-context/src/history.rs +++ b/codex-rs/guardian-context/src/history.rs @@ -160,7 +160,7 @@ impl TranscriptHistory { } return; } - // Analytics must not change which evidence fits Guardian's retention budget. + // Bookkeeping must not change which evidence fits Guardian's retention budget. size.bytes = size.bytes.saturating_sub(metadata_bytes); let is_user = item.is_user_message(); let (mut count, mut bytes) = self diff --git a/codex-rs/otel-trace-websocket/BUILD.bazel b/codex-rs/otel-trace-websocket/BUILD.bazel deleted file mode 100644 index ada1b13f..00000000 --- a/codex-rs/otel-trace-websocket/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "otel-trace-websocket", - crate_name = "codex_otel_trace_websocket", -) diff --git a/codex-rs/otel-trace-websocket/Cargo.toml b/codex-rs/otel-trace-websocket/Cargo.toml deleted file mode 100644 index 538666ec..00000000 --- a/codex-rs/otel-trace-websocket/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "codex-otel-trace-websocket" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lib] -test = false -doctest = false - -[lints] -workspace = true - -[dependencies] -anyhow = { workspace = true } -axum = { workspace = true, features = ["http1", "tokio", "ws"] } -futures = { workspace = true } -tokio = { workspace = true, features = ["macros", "net", "rt", "sync"] } -tracing = { workspace = true } diff --git a/codex-rs/otel-trace-websocket/src/lib.rs b/codex-rs/otel-trace-websocket/src/lib.rs deleted file mode 100644 index 33afa67d..00000000 --- a/codex-rs/otel-trace-websocket/src/lib.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Forwards loopback OTLP trace batches to a separate WebSocket listener. -//! -//! Forwarding is best effort: disconnected or lagging clients lose batches. -//! Callers must flush their trace provider before dropping the bridge. -//! Dropping the bridge aborts its listeners without draining queued batches. - -use std::net::SocketAddr; - -use anyhow::Context; -use anyhow::Result; -use axum::Router; -use axum::body::Body; -use axum::body::Bytes; -use axum::extract::State; -use axum::extract::ws::Message; -use axum::extract::ws::WebSocket; -use axum::extract::ws::WebSocketUpgrade; -use axum::http::Request; -use axum::http::StatusCode; -use axum::http::header::CONTENT_TYPE; -use axum::http::header::ORIGIN; -use axum::middleware; -use axum::middleware::Next; -use axum::response::IntoResponse; -use axum::response::Response; -use axum::routing::any; -use axum::routing::post; -use futures::SinkExt; -use futures::StreamExt; -use tokio::net::TcpListener; -use tokio::sync::broadcast; -use tokio::task::JoinSet; -use tracing::info; -use tracing::warn; - -const TRACE_CHANNEL_CAPACITY: usize = 1_024; -const MAX_TRACE_WEBSOCKET_FRAME_BYTES: usize = 4 * 1024 * 1024; - -/// Owns the loopback OTLP receiver and trace WebSocket listener tasks. -pub struct TraceWebSocket { - exporter_endpoint: String, - listen_addr: SocketAddr, - tasks: JoinSet>, -} - -impl TraceWebSocket { - /// Binds both listeners before returning, so startup reports address conflicts. - pub async fn start(listen_url: &str) -> Result { - let bind_address = listen_url - .strip_prefix("ws://") - .ok_or_else(|| anyhow::anyhow!("unsupported --otel-trace-listen URL '{listen_url}'"))? - .parse::() - .with_context(|| { - format!("invalid --otel-trace-listen URL '{listen_url}'; expected 'ws://IP:PORT'") - })?; - let websocket_listener = TcpListener::bind(bind_address) - .await - .with_context(|| format!("failed to bind OTEL trace websocket to {bind_address}"))?; - let listen_addr = websocket_listener - .local_addr() - .context("failed to read OTEL trace websocket listen address")?; - let otlp_listener = TcpListener::bind("127.0.0.1:0") - .await - .context("failed to bind loopback OTLP trace receiver")?; - let otlp_addr = otlp_listener - .local_addr() - .context("failed to read OTLP trace receiver listen address")?; - let exporter_endpoint = format!("http://{otlp_addr}/v1/traces"); - let (sender, _) = broadcast::channel(TRACE_CHANNEL_CAPACITY); - let otlp_router = Router::new() - .route("/v1/traces", post(receive_otlp_trace_batch)) - .with_state(sender.clone()); - let websocket_router = Router::new() - .route("/", any(trace_websocket_upgrade_handler)) - .layer(middleware::from_fn(reject_requests_with_origin_header)) - .with_state(sender); - let mut tasks = JoinSet::new(); - tasks.spawn(async move { - axum::serve(otlp_listener, otlp_router) - .await - .context("OTLP trace receiver failed") - }); - tasks.spawn(async move { - axum::serve(websocket_listener, websocket_router) - .await - .context("OTEL trace websocket listener failed") - }); - info!("OTLP trace receiver listening on http://{otlp_addr}"); - info!("OTEL trace websocket listening on ws://{listen_addr}"); - Ok(Self { - exporter_endpoint, - listen_addr, - tasks, - }) - } - - /// Returns the local OTLP/HTTP endpoint to configure with JSON trace export. - pub fn exporter_endpoint(&self) -> &str { - &self.exporter_endpoint - } - - /// Returns the bound WebSocket address, including an assigned ephemeral port. - pub fn listen_addr(&self) -> SocketAddr { - self.listen_addr - } - - /// Waits for either listener to stop, for use alongside the main server future. - pub async fn wait_for_failure(&mut self) -> Result<()> { - self.tasks - .join_next() - .await - .context("OTEL trace websocket server tasks stopped")? - .context("OTEL trace websocket server task failed")? - } -} - -async fn reject_requests_with_origin_header( - request: Request, - next: Next, -) -> std::result::Result { - if request.headers().contains_key(ORIGIN) { - warn!( - method = %request.method(), - uri = %request.uri(), - "rejecting OTEL trace websocket request with Origin header" - ); - Err(StatusCode::FORBIDDEN) - } else { - Ok(next.run(request).await) - } -} - -async fn receive_otlp_trace_batch( - State(sender): State>>, - body: Bytes, -) -> impl IntoResponse { - let _ = sender.send(body.to_vec()); - ([(CONTENT_TYPE, "application/json")], "{}") -} - -async fn trace_websocket_upgrade_handler( - websocket: WebSocketUpgrade, - State(sender): State>>, -) -> impl IntoResponse { - websocket - .max_frame_size(MAX_TRACE_WEBSOCKET_FRAME_BYTES) - .max_message_size(MAX_TRACE_WEBSOCKET_FRAME_BYTES) - .on_upgrade(move |stream| stream_trace_batches(stream, sender)) -} - -async fn stream_trace_batches(stream: WebSocket, sender: broadcast::Sender>) { - let (mut writer, mut reader) = stream.split(); - let mut receiver = sender.subscribe(); - info!("OTEL trace websocket client connected"); - loop { - tokio::select! { - incoming = reader.next() => match incoming { - Some(Ok(Message::Close(_))) | None => break, - Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Binary(_) | Message::Text(_))) => {} - Some(Err(error)) => { - warn!(%error, "OTEL trace websocket reader failed"); - break; - } - }, - outgoing = receiver.recv() => match outgoing { - Ok(batch) => { - if let Err(error) = writer.send(Message::Binary(batch.into())).await { - warn!(%error, "OTEL trace websocket writer failed"); - break; - } - } - Err(broadcast::error::RecvError::Lagged(skipped)) => { - warn!(skipped, "OTEL trace websocket client lagged"); - } - Err(broadcast::error::RecvError::Closed) => break, - }, - } - } -} diff --git a/codex-rs/otel/Cargo.toml b/codex-rs/otel/Cargo.toml index 5d603853..5c572ed3 100644 --- a/codex-rs/otel/Cargo.toml +++ b/codex-rs/otel/Cargo.toml @@ -13,44 +13,23 @@ path = "src/lib.rs" workspace = true [dependencies] -bytes = { workspace = true } -codex-http-client = { workspace = true } -opentelemetry-http = "0.31.0" chrono = { workspace = true } -codex-utils-absolute-path = { workspace = true } codex-utils-stream-parser = { workspace = true } codex-utils-string = { workspace = true } codex-api = { workspace = true } codex-protocol = { workspace = true } eventsource-stream = { workspace = true } -gethostname = { workspace = true } -opentelemetry = { workspace = true, features = ["logs", "metrics", "trace"] } -opentelemetry-appender-tracing = { workspace = true } -opentelemetry-otlp = { workspace = true, features = [ - "grpc-tonic", - "http-proto", - "http-json", - "logs", - "metrics", - "trace", - "reqwest-blocking-client", - "reqwest-rustls", - "tls", - "tls-roots", -]} +opentelemetry = { workspace = true, features = ["metrics", "trace"] } opentelemetry-semantic-conventions = { workspace = true } opentelemetry_sdk = { workspace = true, features = [ - "experimental_trace_batch_span_processor_with_async_runtime", "experimental_metrics_custom_reader", - "logs", "metrics", - "rt-tokio", "testing", "trace", ] } http = { workspace = true } +reqwest = { workspace = true } os_info = { workspace = true } -reqwest = { workspace = true, features = ["blocking", "rustls-tls"] } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } strum_macros = { workspace = true } @@ -61,16 +40,4 @@ tracing-opentelemetry = { workspace = true } tracing-subscriber = { workspace = true } [dev-dependencies] -opentelemetry_sdk = { workspace = true, features = [ - "experimental_metrics_custom_reader", - "testing", -] } pretty_assertions = { workspace = true } -rcgen = { workspace = true } -tempfile = { workspace = true } - -[target.'cfg(unix)'.dev-dependencies] -libc = { workspace = true } - -[target.'cfg(target_os = "linux")'.dev-dependencies] -seccompiler = { workspace = true } diff --git a/codex-rs/otel/src/agent_response.rs b/codex-rs/otel/src/agent_response.rs deleted file mode 100644 index 186cf682..00000000 --- a/codex-rs/otel/src/agent_response.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Exports opted-in live final responses, with turn-local deduplication and bounded text. -//! Hosts supply completed raw messages and attribution; stored history is never changed. - -use crate::SessionTelemetry; -use crate::events::shared::log_event; -use codex_protocol::AgentPath; -use codex_protocol::ResponseItemId; -use codex_protocol::models::ContentItem; -use codex_protocol::models::MessagePhase; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_utils_stream_parser::strip_citations; -use codex_utils_string::take_bytes_at_char_boundary; -use std::collections::HashSet; -use std::sync::Mutex; - -const MAX_RESPONSE_BYTES: usize = 65_536; - -/// Host-owned attribution for one live completed response item. -pub struct AgentResponseContext<'a> { - pub turn_id: &'a str, - pub session_source: &'a SessionSource, - pub parent_turn_id: Option, - pub root_turn_id: Option, - pub initiating_agent_path: Option<&'a AgentPath>, -} - -/// One turn's response-log state. Create a fresh instance for each turn; never replay history. -/// Only construct when response logging is opted in and an OTLP log exporter is configured. -#[derive(Default)] -pub struct AgentResponseLogger { - logged: Mutex>, -} - -impl AgentResponseLogger { - /// Record a live final message once, using the telemetry of its actual sampling step. - pub fn record( - &self, - telemetry: &SessionTelemetry, - item: &ResponseItem, - context: AgentResponseContext<'_>, - ) { - let ResponseItem::Message { - id: Some(item_id), - role, - phase: Some(MessagePhase::FinalAnswer), - content, - .. - } = item - else { - return; - }; - if role != "assistant" { - return; - } - let (agent_type, parent_conversation_id) = match context.session_source { - SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, .. - }) => ("subagent", Some(parent_thread_id.to_string())), - SessionSource::Cli - | SessionSource::VSCode - | SessionSource::Exec - | SessionSource::Mcp - | SessionSource::Custom(_) - | SessionSource::Unknown => ("main", None), - SessionSource::Internal(_) - | SessionSource::SubAgent( - SubAgentSource::Review - | SubAgentSource::Compact - | SubAgentSource::MemoryConsolidation - | SubAgentSource::Other(_), - ) => return, - }; - let text = content - .iter() - .filter_map(|content| match content { - ContentItem::OutputText { text, .. } => Some(text.as_str()), - ContentItem::InputText { .. } - | ContentItem::InputImage { .. } - | ContentItem::InputAudio { .. } => None, - }) - .collect::(); - // Keep plan content, stripping memory citations only from the exported copy. - let (text, _) = strip_citations(&text); - if text.trim().is_empty() - || !self - .logged - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(item_id.clone()) - { - return; - } - let response = take_bytes_at_char_boundary(&text, MAX_RESPONSE_BYTES); - log_event!( - telemetry, - event.name = "codex.agent_response", - agent.type = agent_type, - turn.id = context.turn_id, - item.id = item_id.as_str(), - parent.conversation.id = parent_conversation_id.as_deref(), - parent.turn.id = context.parent_turn_id.as_deref(), - root.turn.id = context.root_turn_id.as_deref(), - initiating.agent.path = context.initiating_agent_path.map(AgentPath::as_str), - response = response, - response_length = text.len() as u64, - response_truncated = response.len() < text.len(), - ); - } -} diff --git a/codex-rs/otel/src/config.rs b/codex-rs/otel/src/config.rs deleted file mode 100644 index 82e4bbe7..00000000 --- a/codex-rs/otel/src/config.rs +++ /dev/null @@ -1,102 +0,0 @@ -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::PathBuf; - -use codex_utils_absolute_path::AbsolutePathBuf; -use serde::Deserialize; -use serde::Serialize; - -/// aKode: the upstream built-in Statsig exporter (ab.chatgpt.com with an -/// embedded API key) has been removed. The `Statsig` variant is kept only so -/// old configuration files still parse; it always resolves to `None`, so no -/// telemetry is ever sent unless the user configures an explicit exporter. -pub(crate) fn resolve_exporter(exporter: &OtelExporter) -> OtelExporter { - match exporter { - OtelExporter::Statsig => OtelExporter::None, - _ => exporter.clone(), - } -} - -/// Validates configured span attributes before they are attached to exported spans. -pub fn validate_span_attributes(attributes: &HashMap) -> std::io::Result<()> { - if attributes.keys().any(String::is_empty) { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "configured span attribute key must not be empty", - )); - } - - Ok(()) -} - -#[derive(Clone, Debug)] -pub struct OtelSettings { - pub http_client_factory: codex_http_client::HttpClientFactory, - pub environment: String, - pub service_name: String, - pub service_version: String, - pub codex_home: PathBuf, - pub exporter: OtelExporter, - pub trace_exporter: OtelExporter, - pub metrics_exporter: OtelExporter, - pub runtime_metrics: bool, - pub span_attributes: HashMap, - pub tracestate: BTreeMap>, -} - -/// Resolved Statsig metrics settings that another process can use to recreate -/// the built-in metrics exporter configuration without receiving generic -/// exporter credentials in-process. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct StatsigMetricsSettings { - pub environment: String, -} - -#[derive(Clone, Debug)] -pub enum OtelHttpProtocol { - /// HTTP protocol with binary protobuf - Binary, - /// HTTP protocol with JSON payload - Json, -} - -#[derive(Clone, Debug, Default)] -pub struct OtelTlsConfig { - pub ca_certificate: Option, - pub client_certificate: Option, - pub client_private_key: Option, -} - -#[derive(Clone, Debug)] -pub enum OtelExporter { - None, - /// Statsig metrics ingestion exporter using Codex-internal defaults. - /// - /// This is intended for metrics only. - Statsig, - OtlpGrpc { - endpoint: String, - headers: HashMap, - tls: Option, - }, - OtlpHttp { - endpoint: String, - headers: HashMap, - protocol: OtelHttpProtocol, - tls: Option, - }, -} - -#[cfg(test)] -mod tests { - use super::OtelExporter; - use super::resolve_exporter; - - #[test] - fn statsig_default_metrics_exporter_is_disabled_in_debug_builds() { - assert!(matches!( - resolve_exporter(&OtelExporter::Statsig), - OtelExporter::None - )); - } -} diff --git a/codex-rs/otel/src/events/session_telemetry.rs b/codex-rs/otel/src/events/session_telemetry.rs index 74381ece..6b15e3a4 100644 --- a/codex-rs/otel/src/events/session_telemetry.rs +++ b/codex-rs/otel/src/events/session_telemetry.rs @@ -35,7 +35,6 @@ use crate::metrics::WEBSOCKET_REQUEST_COUNT_METRIC; use crate::metrics::WEBSOCKET_REQUEST_DURATION_METRIC; use crate::metrics::runtime_metrics::RuntimeMetricsSummary; use crate::metrics::timer::Timer; -use crate::provider::OtelProvider; use crate::sanitize_metric_tag_value; use crate::tool_result::ToolResultEvent; use crate::tool_result::emit_tool_result; @@ -204,13 +203,6 @@ impl SessionTelemetry { Ok(self.with_metrics(metrics)) } - pub fn with_provider_metrics(self, provider: &OtelProvider) -> Self { - match provider.metrics() { - Some(metrics) => self.with_metrics(metrics.clone()), - None => self, - } - } - pub fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) { let res: MetricsResult<()> = (|| { let Some(metrics) = &self.metrics else { diff --git a/codex-rs/otel/src/guardian_assessment.rs b/codex-rs/otel/src/guardian_assessment.rs deleted file mode 100644 index 561b3063..00000000 --- a/codex-rs/otel/src/guardian_assessment.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Exports opted-in terminal Guardian assessments with bounded rationale text. -//! Hosts supply the effective model outcome; review failures have no model outcome. - -use crate::SessionTelemetry; -use crate::events::shared::log_event; -use codex_protocol::protocol::GuardianAssessmentEvent; -use codex_protocol::protocol::GuardianAssessmentOutcome; -use codex_protocol::protocol::GuardianAssessmentStatus; -use codex_protocol::protocol::GuardianRiskLevel; -use codex_protocol::protocol::GuardianUserAuthorization; -use codex_utils_string::take_bytes_at_char_boundary; - -const MAX_RATIONALE_BYTES: usize = 65_536; - -impl SessionTelemetry { - /// Record one terminal review after the host checks the opt-in and OTLP destination. - /// `outcome` is absent for errors, timeouts and cancellations, including fail-closed denials. - pub fn guardian_assessment( - &self, - assessment: &GuardianAssessmentEvent, - outcome: Option, - ) { - let status = match assessment.status { - GuardianAssessmentStatus::InProgress => return, - GuardianAssessmentStatus::Approved => "approved", - GuardianAssessmentStatus::Denied => "denied", - GuardianAssessmentStatus::TimedOut => "timed_out", - GuardianAssessmentStatus::Aborted => "aborted", - }; - let outcome = outcome.map(|outcome| match outcome { - GuardianAssessmentOutcome::Allow => "allow", - GuardianAssessmentOutcome::Deny => "deny", - }); - let risk_level = assessment.risk_level.map(|risk| match risk { - GuardianRiskLevel::Low => "low", - GuardianRiskLevel::Medium => "medium", - GuardianRiskLevel::High => "high", - GuardianRiskLevel::Critical => "critical", - }); - let user_authorization = - assessment - .user_authorization - .map(|authorization| match authorization { - GuardianUserAuthorization::Unknown => "unknown", - GuardianUserAuthorization::Low => "low", - GuardianUserAuthorization::Medium => "medium", - GuardianUserAuthorization::High => "high", - }); - let rationale = assessment.rationale.as_deref(); - log_event!( - self, - event.name = "codex.guardian_assessment", - review.id = assessment.id.as_str(), - turn.id = assessment.turn_id.as_str(), - item.id = assessment.target_item_id.as_deref(), - status = status, - outcome = outcome, - risk_level = risk_level, - user_authorization = user_authorization, - started_at_ms = assessment.started_at_ms, - completed_at_ms = assessment.completed_at_ms, - rationale = - rationale.map(|text| take_bytes_at_char_boundary(text, MAX_RATIONALE_BYTES)), - rationale_length = rationale.map(|text| text.len() as u64), - rationale_truncated = rationale.map(|text| text.len() > MAX_RATIONALE_BYTES), - ); - } -} diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index b719515e..633faabe 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -1,14 +1,13 @@ +//! Local-only telemetry helpers for aKode. +//! +//! This crate records structured tracing events, W3C trace-context helpers and +//! optional in-process metrics. It contains no network exporter: nothing +//! recorded here ever leaves the machine. pub mod auth_storage; -pub(crate) mod config; mod events; pub(crate) mod metrics; -pub(crate) mod provider; pub(crate) mod trace_context; -mod agent_response; -mod guardian_assessment; -mod network_policy; -mod otlp; mod skill_invocation; mod targets; mod tool_result; @@ -18,14 +17,6 @@ use codex_protocol::auth::AuthMode; use serde::Serialize; use strum_macros::Display; -pub use crate::agent_response::AgentResponseContext; -pub use crate::agent_response::AgentResponseLogger; -pub use crate::config::OtelExporter; -pub use crate::config::OtelHttpProtocol; -pub use crate::config::OtelSettings; -pub use crate::config::OtelTlsConfig; -pub use crate::config::StatsigMetricsSettings; -pub use crate::config::validate_span_attributes; pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata; pub use crate::events::session_telemetry::SessionTelemetry; pub use crate::events::session_telemetry::SessionTelemetryMetadata; @@ -34,19 +25,16 @@ pub use crate::metrics::runtime_metrics::RuntimeMetricTotals; pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary; pub use crate::metrics::timer::Timer; pub use crate::metrics::*; -pub use crate::provider::OtelProvider; pub use crate::skill_invocation::SkillInvocationEvent; pub use crate::skill_invocation::SkillInvocationType; +pub use crate::targets::trace_export_filter; pub use crate::trace_context::context_from_w3c_trace_context; pub use crate::trace_context::current_span_trace_id; pub use crate::trace_context::current_span_w3c_trace_context; -pub use crate::trace_context::inject_span_w3c_trace_headers; pub use crate::trace_context::set_parent_from_context; pub use crate::trace_context::set_parent_from_w3c_trace_context; pub use crate::trace_context::span_w3c_trace_context; pub use crate::trace_context::traceparent_context_from_env; -pub use crate::trace_context::validate_tracestate_entries; -pub use crate::trace_context::validate_tracestate_member; pub use codex_utils_string::sanitize_metric_tag_value; #[derive(Debug, Clone, Serialize, Display)] @@ -79,7 +67,7 @@ impl From for TelemetryAuthMode { } } -/// Install externally managed, non-Statsig process-global metrics. +/// Install process-global, local-only metrics (for example an in-memory reader). /// /// Call this once during single-threaded startup, before any instruments are /// registered. Keep the returned handle to flush and shut down the exporter @@ -95,9 +83,3 @@ pub fn start_global_timer(name: &str, tags: &[(&str, &str)]) -> MetricsResult Option { - crate::metrics::global_statsig_settings() -} diff --git a/codex-rs/otel/src/metrics/buffered.rs b/codex-rs/otel/src/metrics/buffered.rs index 96d6e31b..16cdecf3 100644 --- a/codex-rs/otel/src/metrics/buffered.rs +++ b/codex-rs/otel/src/metrics/buffered.rs @@ -26,7 +26,6 @@ struct PendingOperation { enum State { Startup(Vec), Ready(MetricsClient), - Disabled, } pub(crate) struct BufferedMetrics { @@ -105,7 +104,6 @@ impl BufferedMetrics { Ok(()) } State::Ready(metrics) => record(metrics, count_name, duration_name, duration, tags), - State::Disabled => Ok(()), } } @@ -139,13 +137,6 @@ impl BufferedMetrics { *state = State::Ready(metrics); } - pub(crate) fn disable(&self) { - *self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = State::Disabled; - } - pub(super) fn suspend(&self, metrics: &MetricsClient) { let mut state = self .state diff --git a/codex-rs/otel/src/metrics/buffered_tests.rs b/codex-rs/otel/src/metrics/buffered_tests.rs index 3fc1c2c6..ae767ab5 100644 --- a/codex-rs/otel/src/metrics/buffered_tests.rs +++ b/codex-rs/otel/src/metrics/buffered_tests.rs @@ -104,27 +104,6 @@ fn startup_limits_and_validation_preserve_whole_pairs() { assert_eq!(totals(&metrics), (0, 0, 0.0)); } -#[test] -fn opt_out_discards_pending_and_live_observations_until_reenabled() { - let buffer = BufferedMetrics::new(); - observe(&buffer); - buffer.disable(); - observe(&buffer); - let first = client(); - buffer.enable(&first); - assert_eq!(totals(&first), (0, 0, 0.0)); - observe(&buffer); - assert_eq!(totals(&first), (1, 1, 7.0)); - buffer.disable(); - observe(&buffer); - assert_eq!(totals(&first), (0, 0, 0.0)); - let second = client(); - buffer.enable(&second); - observe(&buffer); - assert_eq!(totals(&second), (1, 1, 7.0)); - assert_eq!(totals(&first), (0, 0, 0.0)); -} - #[test] fn concurrent_installation_and_replacement_record_each_pair_once() { let buffer = BufferedMetrics::new(); diff --git a/codex-rs/otel/src/metrics/client.rs b/codex-rs/otel/src/metrics/client.rs index 0dee1695..cb20eadf 100644 --- a/codex-rs/otel/src/metrics/client.rs +++ b/codex-rs/otel/src/metrics/client.rs @@ -1,9 +1,6 @@ -use crate::config::OtelExporter; -use crate::config::OtelHttpProtocol; use crate::metrics::MetricsError; use crate::metrics::Result; use crate::metrics::config::MetricsConfig; -use crate::metrics::config::MetricsExporter; use crate::metrics::names::TURN_CRITICAL_PATH_COMPONENT_METRIC; use crate::metrics::names::TURN_CRITICAL_PATH_DURATION_METRIC; use crate::metrics::timer::Timer; @@ -18,13 +15,6 @@ use opentelemetry::metrics::Gauge; use opentelemetry::metrics::Histogram; use opentelemetry::metrics::Meter; use opentelemetry::metrics::MeterProvider as _; -use opentelemetry_otlp::OTEL_EXPORTER_OTLP_METRICS_TIMEOUT; -use opentelemetry_otlp::Protocol; -use opentelemetry_otlp::WithExportConfig; -use opentelemetry_otlp::WithHttpConfig; -use opentelemetry_otlp::WithTonicConfig; -use opentelemetry_otlp::tonic_types::metadata::MetadataMap; -use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig; use opentelemetry_sdk::Resource; use opentelemetry_sdk::metrics::InstrumentKind; use opentelemetry_sdk::metrics::ManualReader; @@ -45,10 +35,6 @@ use std::sync::Weak; use std::time::Duration; use tracing::debug; -#[cfg(test)] -#[path = "client_tests.rs"] -mod tests; - const ENV_ATTRIBUTE: &str = "env"; const METER_NAME: &str = "codex"; const MILLISECOND_DURATION_UNIT: &str = "ms"; @@ -121,7 +107,6 @@ impl MetricReader for SharedManualReader { #[derive(Debug)] pub(super) struct MetricsClientInner { - pub(super) network_policy: codex_http_client::NetworkPolicy, meter_provider: SdkMeterProvider, meter: Meter, counters: Mutex>>, @@ -129,8 +114,6 @@ pub(super) struct MetricsClientInner { histograms: Mutex>>, duration_histograms: Mutex>>, runtime_reader: Option>, - requires_analytics_consent: bool, - statsig_disabled_metrics: &'static [&'static str], default_tags: BTreeMap, } @@ -151,10 +134,6 @@ impl MetricsClientInner { } let attributes = self.attributes(tags)?; - if self.statsig_disabled_metrics.contains(&name) { - return Ok(()); - } - let mut counters = self .counters .lock() @@ -185,10 +164,6 @@ impl MetricsClientInner { validate_metric_name(name)?; let attributes = self.attributes(tags)?; - if self.statsig_disabled_metrics.contains(&name) { - return Ok(()); - } - let mut histograms = self .histograms .lock() @@ -214,10 +189,6 @@ impl MetricsClientInner { validate_metric_name(name)?; let attributes = self.attributes(tags)?; - if self.statsig_disabled_metrics.contains(&name) { - return Ok(()); - } - let mut gauges = self .gauges .lock() @@ -248,10 +219,6 @@ impl MetricsClientInner { validate_metric_name(name)?; let attributes = self.attributes(tags)?; - if self.statsig_disabled_metrics.contains(&name) { - return Ok(()); - } - let _gauge = self .meter .i64_observable_gauge(name.to_string()) @@ -273,10 +240,6 @@ impl MetricsClientInner { validate_metric_name(name)?; let attributes = self.attributes(tags)?; - if self.statsig_disabled_metrics.contains(&name) { - return Ok(()); - } - let mut histograms = self .duration_histograms .lock() @@ -332,10 +295,10 @@ impl MetricsClientInner { } } -/// OpenTelemetry metrics client used by Codex. +/// Local, in-process OpenTelemetry metrics client. It never exports over the network. #[derive(Clone, Debug)] pub struct MetricsClient { - // Keep the original provider so its owner only shuts down its own exporter. + // Keep the original provider so its owner only shuts down its own reader. pub(super) inner: Arc, // Installed clients share this slot, so existing clones follow account changes. pub(super) active: Option>>>, @@ -345,14 +308,12 @@ impl MetricsClient { /// Build a metrics client from configuration and validate defaults. pub fn new(config: MetricsConfig) -> Result { let MetricsConfig { - http_client_factory, environment, service_name, service_version, exporter, export_interval, runtime_reader, - statsig_disabled_metrics, default_tags, } = config; @@ -379,34 +340,11 @@ impl MetricsClient { ) }); - let requires_analytics_consent = - matches!(exporter, MetricsExporter::Otlp(OtelExporter::Statsig)); - let (meter_provider, meter) = match exporter { - MetricsExporter::InMemory(exporter) => { - build_provider(resource, exporter, export_interval, runtime_reader.clone()) - } - MetricsExporter::Otlp(exporter) => { - let temporality = otlp_metrics_temporality( - &exporter, - std::env::var("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") - .ok() - .as_deref(), - ); - let exporter = crate::network_policy::PolicyExporter { - exporter: build_otlp_metric_exporter( - exporter, - temporality, - &http_client_factory, - )?, - policy: http_client_factory.network_policy().clone(), - }; - build_provider(resource, exporter, export_interval, runtime_reader.clone()) - } - }; + let (meter_provider, meter) = + build_provider(resource, exporter, export_interval, runtime_reader.clone()); Ok(Self { inner: Arc::new(MetricsClientInner { - network_policy: http_client_factory.network_policy().clone(), meter_provider, meter, counters: Mutex::new(HashMap::new()), @@ -414,8 +352,6 @@ impl MetricsClient { histograms: Mutex::new(HashMap::new()), duration_histograms: Mutex::new(HashMap::new()), runtime_reader, - requires_analytics_consent, - statsig_disabled_metrics, default_tags, }), active: None, @@ -438,22 +374,6 @@ impl MetricsClient { .counter(name, /*description*/ None, inc, tags) } - /// Record a counter while applying analytics consent only to the built-in exporter. - /// The consent check and recording use the same exporter even during provider replacement. - pub fn counter_with_analytics_consent( - &self, - name: &str, - inc: i64, - tags: &[(&str, &str)], - analytics_enabled: bool, - ) -> Result<()> { - let inner = self.active_inner(); - if inner.requires_analytics_consent && !analytics_enabled { - return Ok(()); - } - inner.counter(name, /*description*/ None, inc, tags) - } - /// Send a single counter increment with an instrument description. pub fn counter_with_description( &self, @@ -639,104 +559,3 @@ where let meter = provider.meter(METER_NAME); (provider, meter) } - -fn otlp_metrics_temporality(exporter: &OtelExporter, preference: Option<&str>) -> Temporality { - // Select before resolving Statsig to OTLP so its built-in route stays Delta. - match exporter { - OtelExporter::None | OtelExporter::Statsig => Temporality::Delta, - OtelExporter::OtlpGrpc { .. } | OtelExporter::OtlpHttp { .. } => match preference { - Some(value) if value.eq_ignore_ascii_case("cumulative") => Temporality::Cumulative, - Some(value) if value.eq_ignore_ascii_case("lowmemory") => Temporality::LowMemory, - // Preserve Codex's existing default for unset, empty, or unknown values. - _ => Temporality::Delta, - }, - } -} - -fn build_otlp_metric_exporter( - exporter: OtelExporter, - temporality: Temporality, - factory: &codex_http_client::HttpClientFactory, -) -> Result { - match exporter { - OtelExporter::None => Err(MetricsError::ExporterDisabled), - OtelExporter::Statsig => build_otlp_metric_exporter( - crate::config::resolve_exporter(&OtelExporter::Statsig), - temporality, - factory, - ), - OtelExporter::OtlpGrpc { - endpoint, - headers, - tls, - } => { - debug!("Using OTLP Grpc exporter for metrics: {endpoint}"); - - let header_map = crate::otlp::build_header_map(&headers); - - let base_tls_config = ClientTlsConfig::new() - .with_enabled_roots() - .assume_http2(true); - - let tls_config = match tls.as_ref() { - Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls) - .map_err(|err| MetricsError::InvalidConfig { - message: err.to_string(), - })?, - None => base_tls_config, - }; - - opentelemetry_otlp::MetricExporter::builder() - .with_tonic() - .with_endpoint(endpoint) - .with_temporality(temporality) - .with_metadata(MetadataMap::from_headers(header_map)) - .with_tls_config(tls_config) - .build() - .map_err(|source| MetricsError::ExporterBuild { source }) - } - OtelExporter::OtlpHttp { - endpoint, - headers, - protocol, - tls, - } => { - debug!("Using OTLP Http exporter for metrics: {endpoint}"); - - let protocol = match protocol { - OtelHttpProtocol::Binary => Protocol::HttpBinary, - OtelHttpProtocol::Json => Protocol::HttpJson, - }; - - let mut exporter_builder = opentelemetry_otlp::MetricExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_temporality(temporality) - .with_protocol(protocol) - .with_headers(headers); - - if factory.network_policy().is_managed() { - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, - ) - .map_err(|err| MetricsError::InvalidConfig { - message: err.to_string(), - })?; - exporter_builder = exporter_builder.with_http_client(client); - } else if let Some(tls) = tls.as_ref() { - let client = - crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT) - .map_err(|err| MetricsError::InvalidConfig { - message: err.to_string(), - })?; - exporter_builder = exporter_builder.with_http_client(client); - } - - exporter_builder - .build() - .map_err(|source| MetricsError::ExporterBuild { source }) - } - } -} diff --git a/codex-rs/otel/src/metrics/client_tests.rs b/codex-rs/otel/src/metrics/client_tests.rs deleted file mode 100644 index 5363a3f5..00000000 --- a/codex-rs/otel/src/metrics/client_tests.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Consent follows the actual counter destination across exporter replacements. - -use super::*; -use opentelemetry_sdk::metrics::data::AggregatedMetrics; -use opentelemetry_sdk::metrics::data::MetricData; -use opentelemetry_sdk::metrics::data::ScopeMetrics; -use opentelemetry_sdk::metrics::data::SumDataPoint; -use pretty_assertions::assert_eq; - -#[test] -fn counter_consent_uses_the_active_exporter() -> Result<()> { - let mut builtin = MetricsClient::new( - MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(), - )?; - // Use the existing in-memory exporter to observe the built-in consent policy without - // contacting Statsig (the real Statsig exporter is disabled in debug builds). - Arc::get_mut(&mut builtin.inner) - .expect("unique provider") - .requires_analytics_consent = true; - let custom = MetricsClient::new( - MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(), - )?; - let active = Arc::new(RwLock::new(Arc::clone(&builtin.inner))); - let metrics = MetricsClient { - inner: Arc::clone(&builtin.inner), - active: Some(Arc::clone(&active)), - }; - - // A config reload alone does not replace the installed built-in exporter. - for analytics_enabled in [false, true] { - metrics.counter_with_analytics_consent( - "test.observations", - /*inc*/ 1, - &[], - analytics_enabled, - )?; - } - *active.write().unwrap() = Arc::clone(&custom.inner); - metrics.counter_with_analytics_consent( - "test.observations", - /*inc*/ 1, - &[], - /*analytics_enabled*/ false, - )?; - - let mut counts = Vec::new(); - for destination in [&builtin, &custom] { - let snapshot = destination.snapshot()?; - for metric in snapshot.scope_metrics().flat_map(ScopeMetrics::metrics) { - if let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() { - counts.extend(sum.data_points().map(SumDataPoint::value)); - } - } - } - assert_eq!(counts, vec![1, 1]); - Ok(()) -} diff --git a/codex-rs/otel/src/metrics/config.rs b/codex-rs/otel/src/metrics/config.rs index df2203a2..c47a411a 100644 --- a/codex-rs/otel/src/metrics/config.rs +++ b/codex-rs/otel/src/metrics/config.rs @@ -1,95 +1,24 @@ -use crate::config::OtelExporter; use crate::metrics::Result; -use crate::metrics::names::API_CALL_COUNT_METRIC; -use crate::metrics::names::API_CALL_DURATION_METRIC; -use crate::metrics::names::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC; -use crate::metrics::names::TOOL_CALL_COUNT_METRIC; -use crate::metrics::names::TOOL_CALL_DURATION_METRIC; -use crate::metrics::names::TURN_COST_MICROUSD_METRIC; -use crate::metrics::names::TURN_TOKEN_USAGE_METRIC; use crate::metrics::validation::validate_tag_key; use crate::metrics::validation::validate_tag_value; use opentelemetry_sdk::metrics::InMemoryMetricExporter; use std::collections::BTreeMap; use std::time::Duration; -const CONVERSATION_TURN_COUNT_METRIC: &str = "codex.conversation.turn.count"; - -// Metrics intentionally not sent through Codex's built-in Statsig route. -// Keep this as an exact-name list so custom OTLP exporters still receive them. -const STATSIG_DISABLED_METRICS: &[&str] = &[ - API_CALL_COUNT_METRIC, - API_CALL_DURATION_METRIC, - CONVERSATION_TURN_COUNT_METRIC, - // Caller-side executor volume belongs in configured observability collectors. - EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC, - RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC, - RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC, - RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC, - TOOL_CALL_COUNT_METRIC, - TOOL_CALL_DURATION_METRIC, - TURN_COST_MICROUSD_METRIC, - TURN_TOKEN_USAGE_METRIC, -]; - -#[derive(Clone, Debug)] -pub enum MetricsExporter { - Otlp(OtelExporter), - InMemory(InMemoryMetricExporter), -} - +/// Configuration for a local, in-process metrics client. There is no network exporter. #[derive(Clone, Debug)] pub struct MetricsConfig { - pub(crate) http_client_factory: codex_http_client::HttpClientFactory, pub(crate) environment: String, pub(crate) service_name: String, pub(crate) service_version: String, - pub(crate) exporter: MetricsExporter, + pub(crate) exporter: InMemoryMetricExporter, pub(crate) export_interval: Option, pub(crate) runtime_reader: bool, - pub(crate) statsig_disabled_metrics: &'static [&'static str], pub(crate) default_tags: BTreeMap, } impl MetricsConfig { - pub fn with_http_client_factory( - mut self, - factory: codex_http_client::HttpClientFactory, - ) -> Self { - self.http_client_factory = factory; - self - } - - pub fn otlp( - environment: impl Into, - service_name: impl Into, - service_version: impl Into, - exporter: OtelExporter, - ) -> Self { - let statsig_disabled_metrics = if matches!(exporter, OtelExporter::Statsig) { - STATSIG_DISABLED_METRICS - } else { - &[] - }; - Self { - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: environment.into(), - service_name: service_name.into(), - service_version: service_version.into(), - exporter: MetricsExporter::Otlp(exporter), - export_interval: None, - runtime_reader: false, - statsig_disabled_metrics, - default_tags: BTreeMap::new(), - } - } - - /// Create an in-memory config (used in tests). + /// Create an in-memory config. pub fn in_memory( environment: impl Into, service_name: impl Into, @@ -97,16 +26,12 @@ impl MetricsConfig { exporter: InMemoryMetricExporter, ) -> Self { Self { - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), environment: environment.into(), service_name: service_name.into(), service_version: service_version.into(), - exporter: MetricsExporter::InMemory(exporter), + exporter, export_interval: None, runtime_reader: false, - statsig_disabled_metrics: &[], default_tags: BTreeMap::new(), } } @@ -123,7 +48,7 @@ impl MetricsConfig { self } - /// Add a default tag that will be sent with every metric. + /// Add a default tag that will be recorded with every metric. pub fn with_tag(mut self, key: impl Into, value: impl Into) -> Result { let key = key.into(); let value = value.into(); diff --git a/codex-rs/otel/src/metrics/error.rs b/codex-rs/otel/src/metrics/error.rs index 7312992b..93096f7e 100644 --- a/codex-rs/otel/src/metrics/error.rs +++ b/codex-rs/otel/src/metrics/error.rs @@ -17,21 +17,12 @@ pub enum MetricsError { #[error("{label} contains invalid characters: {value}")] InvalidTagComponent { label: String, value: String }, - #[error("metrics exporter is disabled")] + #[error("metrics are not installed")] ExporterDisabled, #[error("counter increment must be non-negative for {name}: {inc}")] NegativeCounterIncrement { name: String, inc: i64 }, - #[error("failed to build OTLP metrics exporter")] - ExporterBuild { - #[source] - source: opentelemetry_otlp::ExporterBuildError, - }, - - #[error("invalid OTLP metrics configuration: {message}")] - InvalidConfig { message: String }, - #[error("failed to flush or shutdown metrics provider")] ProviderShutdown { #[source] diff --git a/codex-rs/otel/src/metrics/mod.rs b/codex-rs/otel/src/metrics/mod.rs index c4f9d315..99ca7d99 100644 --- a/codex-rs/otel/src/metrics/mod.rs +++ b/codex-rs/otel/src/metrics/mod.rs @@ -9,11 +9,9 @@ pub(crate) mod tags; pub(crate) mod timer; pub(crate) mod validation; -use crate::config::StatsigMetricsSettings; pub use crate::metrics::buffered::record_global_operation; pub use crate::metrics::client::MetricsClient; pub use crate::metrics::config::MetricsConfig; -pub use crate::metrics::config::MetricsExporter; pub use crate::metrics::error::MetricsError; pub use crate::metrics::error::Result; pub use crate::metrics::process::record_process_start_once; @@ -26,7 +24,6 @@ pub use tags::SessionMetricTagValues; pub use tags::bounded_originator_tag_value; static GLOBAL_METRICS: OnceLock = OnceLock::new(); -static GLOBAL_STATSIG_METRICS_SETTINGS: OnceLock = OnceLock::new(); pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient { let active = GLOBAL_METRICS @@ -45,17 +42,3 @@ pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient { pub fn global() -> Option { GLOBAL_METRICS.get().cloned() } - -pub(crate) fn install_global_statsig_settings(settings: StatsigMetricsSettings) { - let _ = GLOBAL_STATSIG_METRICS_SETTINGS.set(settings); -} - -pub(crate) fn global_statsig_settings() -> Option { - if GLOBAL_METRICS - .get() - .is_some_and(|metrics| metrics.active_inner().network_policy.is_managed()) - { - return None; - } - GLOBAL_STATSIG_METRICS_SETTINGS.get().cloned() -} diff --git a/codex-rs/otel/src/network_policy.rs b/codex-rs/otel/src/network_policy.rs deleted file mode 100644 index 9b9455a1..00000000 --- a/codex-rs/otel/src/network_policy.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! OTLP SDK transports remain disabled under application destination restrictions. -//! Export futures are revocable, including HTTP exporters driven from SDK worker threads. - -use bytes::Bytes; -use codex_http_client::NetworkPolicy; -use opentelemetry_http::HttpError; -use opentelemetry_sdk::Resource; -use opentelemetry_sdk::error::OTelSdkError; -use opentelemetry_sdk::error::OTelSdkResult; -use opentelemetry_sdk::logs::LogBatch; -use opentelemetry_sdk::logs::LogExporter; -use opentelemetry_sdk::metrics::Temporality; -use opentelemetry_sdk::metrics::data::ResourceMetrics; -use opentelemetry_sdk::metrics::exporter::PushMetricExporter; -use opentelemetry_sdk::trace::SpanData; -use opentelemetry_sdk::trace::SpanExporter; -use std::future::Future; -use std::pin::Pin; -use std::time::Duration; - -#[derive(Debug)] -pub(crate) struct PolicyExporter { - pub(crate) exporter: E, - pub(crate) policy: NetworkPolicy, -} - -fn denied(error: codex_http_client::NetworkPolicyDenied) -> OTelSdkError { - OTelSdkError::InternalFailure(error.to_string()) -} - -impl SpanExporter for PolicyExporter { - async fn export(&self, batch: Vec) -> OTelSdkResult { - let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?; - let export = self.exporter.export(batch); - permit.run(export).await.map_err(denied)? - } - fn shutdown_with_timeout(&mut self, timeout: Duration) -> OTelSdkResult { - self.exporter.shutdown_with_timeout(timeout) - } - fn force_flush(&mut self) -> OTelSdkResult { - self.exporter.force_flush() - } - fn set_resource(&mut self, resource: &Resource) { - self.exporter.set_resource(resource); - } -} - -impl LogExporter for PolicyExporter { - async fn export(&self, batch: LogBatch<'_>) -> OTelSdkResult { - let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?; - let export = self.exporter.export(batch); - permit.run(export).await.map_err(denied)? - } - fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult { - self.exporter.shutdown_with_timeout(timeout) - } - fn set_resource(&mut self, resource: &Resource) { - self.exporter.set_resource(resource); - } -} - -impl PushMetricExporter for PolicyExporter { - async fn export(&self, metrics: &ResourceMetrics) -> OTelSdkResult { - let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?; - let export = self.exporter.export(metrics); - permit.run(export).await.map_err(denied)? - } - fn force_flush(&self) -> OTelSdkResult { - self.exporter.force_flush() - } - fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult { - self.exporter.shutdown_with_timeout(timeout) - } - fn temporality(&self) -> Temporality { - self.exporter.temporality() - } -} - -/// Keeps blocking SDK worker threads from performing uncancellable HTTP I/O. -#[derive(Debug)] -pub(crate) struct RuntimeHttpClient { - pub(crate) client: codex_http_client::HttpClient, - pub(crate) timeout: Duration, - pub(crate) runtime: tokio::runtime::Handle, -} - -impl opentelemetry_http::HttpClient for RuntimeHttpClient { - fn send_bytes<'client, 'request>( - &'client self, - request: http::Request, - ) -> Pin, HttpError>> + Send + 'request>> - where - 'client: 'request, - Self: 'request, - { - Box::pin(async move { - let client = self.client.clone(); - let timeout = self.timeout; - let mut requests = tokio::task::JoinSet::new(); - requests.spawn_on( - async move { - let (parts, body) = request.into_parts(); - let response = client - .request(parts.method, parts.uri.to_string()) - .version(parts.version) - .headers(parts.headers) - .body(body) - .timeout(timeout) - .send() - .await? - .error_for_status()?; - let mut builder = http::Response::builder().status(response.status()); - if let Some(headers) = builder.headers_mut() { - *headers = response.headers().clone(); - } - Ok::<_, HttpError>(builder.body(response.bytes().await?)?) - }, - &self.runtime, - ); - // Dropping the SDK export future drops this set and aborts the HTTP request. - requests - .join_next() - .await - .ok_or("telemetry request task disappeared")?? - }) - } -} diff --git a/codex-rs/otel/src/otlp.rs b/codex-rs/otel/src/otlp.rs deleted file mode 100644 index a20ad5d6..00000000 --- a/codex-rs/otel/src/otlp.rs +++ /dev/null @@ -1,330 +0,0 @@ -use crate::config::OtelTlsConfig; -use codex_utils_absolute_path::AbsolutePathBuf; -use http::Uri; -use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TIMEOUT; -use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT; -use opentelemetry_otlp::tonic_types::transport::Certificate as TonicCertificate; -use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig; -use opentelemetry_otlp::tonic_types::transport::Identity as TonicIdentity; -use reqwest::Certificate as ReqwestCertificate; -use reqwest::Identity as ReqwestIdentity; -use reqwest::header::HeaderMap; -use reqwest::header::HeaderName; -use reqwest::header::HeaderValue; -use std::env; -use std::error::Error; -use std::fs; -use std::io; -use std::io::ErrorKind; -use std::path::PathBuf; -use std::time::Duration; - -pub(crate) fn build_header_map(headers: &std::collections::HashMap) -> HeaderMap { - let mut header_map = HeaderMap::new(); - for (key, value) in headers { - if let Ok(name) = HeaderName::from_bytes(key.as_bytes()) - && let Ok(val) = HeaderValue::from_str(value) - { - header_map.insert(name, val); - } - } - header_map -} - -pub(crate) fn build_grpc_tls_config( - endpoint: &str, - tls_config: ClientTlsConfig, - tls: &OtelTlsConfig, -) -> Result> { - let uri: Uri = endpoint.parse()?; - let host = uri.host().ok_or_else(|| { - config_error(format!( - "OTLP gRPC endpoint {endpoint} does not include a host" - )) - })?; - - let mut config = tls_config.domain_name(host.to_owned()); - - if let Some(path) = tls.ca_certificate.as_ref() { - let (pem, _) = read_bytes(path)?; - config = config.ca_certificate(TonicCertificate::from_pem(pem)); - } - - match (&tls.client_certificate, &tls.client_private_key) { - (Some(cert_path), Some(key_path)) => { - let (cert_pem, _) = read_bytes(cert_path)?; - let (key_pem, _) = read_bytes(key_path)?; - config = config.identity(TonicIdentity::from_pem(cert_pem, key_pem)); - } - (Some(_), None) | (None, Some(_)) => { - return Err(config_error( - "client_certificate and client_private_key must both be provided for mTLS", - )); - } - (None, None) => {} - } - - Ok(config) -} - -/// Build a blocking HTTP client with TLS configuration for OTLP HTTP exporters. -/// -/// We use `reqwest::blocking::Client` because OTEL exporters run on dedicated -/// OS threads that are not necessarily backed by tokio. -pub(crate) fn build_http_client( - tls: &OtelTlsConfig, - timeout_var: &str, -) -> Result> { - if current_tokio_runtime_is_multi_thread() { - tokio::task::block_in_place(|| build_http_client_inner(tls, timeout_var)) - } else if tokio::runtime::Handle::try_current().is_ok() { - let tls = tls.clone(); - let timeout_var = timeout_var.to_string(); - std::thread::spawn(move || { - build_http_client_inner(&tls, &timeout_var).map_err(|err| err.to_string()) - }) - .join() - .map_err(|_| config_error("failed to join OTLP blocking HTTP client builder thread"))? - .map_err(config_error) - } else { - build_http_client_inner(tls, timeout_var) - } -} - -pub(crate) fn current_tokio_runtime_is_multi_thread() -> bool { - match tokio::runtime::Handle::try_current() { - Ok(handle) => handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread, - Err(_) => false, - } -} - -fn build_http_client_inner( - tls: &OtelTlsConfig, - timeout_var: &str, -) -> Result> { - let mut builder = - reqwest::blocking::Client::builder().timeout(resolve_otlp_timeout(timeout_var)); - - if let Some(path) = tls.ca_certificate.as_ref() { - let (pem, location) = read_bytes(path)?; - let certificate = ReqwestCertificate::from_pem(pem.as_slice()).map_err(|error| { - config_error(format!( - "failed to parse certificate {}: {error}", - location.display() - )) - })?; - builder = builder - .tls_built_in_root_certs(false) - .add_root_certificate(certificate); - } - - match (&tls.client_certificate, &tls.client_private_key) { - (Some(cert_path), Some(key_path)) => { - let (mut cert_pem, cert_location) = read_bytes(cert_path)?; - let (key_pem, key_location) = read_bytes(key_path)?; - cert_pem.extend_from_slice(key_pem.as_slice()); - let identity = ReqwestIdentity::from_pem(cert_pem.as_slice()).map_err(|error| { - config_error(format!( - "failed to parse client identity using {} and {}: {error}", - cert_location.display(), - key_location.display() - )) - })?; - builder = builder.use_rustls_tls().identity(identity).https_only(true); - } - (Some(_), None) | (None, Some(_)) => { - return Err(config_error( - "client_certificate and client_private_key must both be provided for mTLS", - )); - } - (None, None) => {} - } - - builder - .build() - .map_err(|error| Box::new(error) as Box) -} - -pub(crate) fn build_async_http_client( - factory: &codex_http_client::HttpClientFactory, - tls: Option<&OtelTlsConfig>, - timeout_var: &str, -) -> Result> { - let mut config = codex_http_client::HttpClientTlsConfig::default(); - - if let Some(tls) = tls { - if let Some(path) = tls.ca_certificate.as_ref() { - let (pem, location) = read_bytes(path)?; - config = config - .with_root_certificate_pem(pem.as_slice()) - .map_err(|error| { - config_error(format!( - "failed to parse certificate {}: {error}", - location.display() - )) - })?; - } - - match (&tls.client_certificate, &tls.client_private_key) { - (Some(cert_path), Some(key_path)) => { - let (mut cert_pem, cert_location) = read_bytes(cert_path)?; - let (key_pem, key_location) = read_bytes(key_path)?; - cert_pem.extend_from_slice(key_pem.as_slice()); - config = config - .with_client_identity_pem(cert_pem.as_slice()) - .map_err(|error| { - config_error(format!( - "failed to parse client identity using {} and {}: {error}", - cert_location.display(), - key_location.display() - )) - })?; - } - (Some(_), None) | (None, Some(_)) => { - return Err(config_error( - "client_certificate and client_private_key must both be provided for mTLS", - )); - } - (None, None) => {} - } - } - - Ok(crate::network_policy::RuntimeHttpClient { - client: codex_http_client::HttpClientBuilder::new() - .without_request_logging() - .build_with_tls(factory, codex_http_client::ClientRouteClass::Other, config), - timeout: resolve_otlp_timeout(timeout_var), - runtime: tokio::runtime::Handle::try_current()?, - }) -} - -pub(crate) fn resolve_otlp_timeout(signal_var: &str) -> Duration { - if let Some(timeout) = read_timeout_env(signal_var) { - return timeout; - } - if let Some(timeout) = read_timeout_env(OTEL_EXPORTER_OTLP_TIMEOUT) { - return timeout; - } - OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT -} - -fn read_timeout_env(var: &str) -> Option { - let value = env::var(var).ok()?; - let parsed = value.parse::().ok()?; - if parsed < 0 { - return None; - } - Some(Duration::from_millis(parsed as u64)) -} - -fn read_bytes(path: &AbsolutePathBuf) -> Result<(Vec, PathBuf), Box> { - match fs::read(path) { - Ok(bytes) => Ok((bytes, path.to_path_buf())), - Err(error) => Err(Box::new(io::Error::new( - error.kind(), - format!("failed to read {}: {error}", path.display()), - ))), - } -} - -fn config_error(message: impl Into) -> Box { - Box::new(io::Error::new(ErrorKind::InvalidData, message.into())) -} - -#[cfg(test)] -mod tests { - use super::*; - use codex_http_client::HttpClientFactory; - use codex_http_client::OutboundProxyPolicy; - use pretty_assertions::assert_eq; - use rcgen::CertifiedKey; - use rcgen::generate_simple_self_signed; - use std::fs; - use tempfile::TempDir; - use tokio::runtime::Builder; - - #[test] - fn current_tokio_runtime_is_multi_thread_detects_runtime_flavor() { - assert!(!current_tokio_runtime_is_multi_thread()); - - let current_thread_runtime = Builder::new_current_thread() - .enable_all() - .build() - .expect("current-thread runtime"); - assert_eq!( - current_thread_runtime.block_on(async { current_tokio_runtime_is_multi_thread() }), - false - ); - - let multi_thread_runtime = Builder::new_multi_thread() - .worker_threads(2) - .enable_all() - .build() - .expect("multi-thread runtime"); - assert_eq!( - multi_thread_runtime.block_on(async { current_tokio_runtime_is_multi_thread() }), - true - ); - } - - #[test] - fn build_http_client_works_in_current_thread_runtime() { - let runtime = Builder::new_current_thread() - .enable_all() - .build() - .expect("current-thread runtime"); - - let client = runtime.block_on(async { - build_http_client(&OtelTlsConfig::default(), OTEL_EXPORTER_OTLP_TIMEOUT) - }); - - assert!(client.is_ok()); - } - - #[test] - fn build_http_client_accepts_pem_client_identity() { - let (_temp_dir, tls) = write_test_mtls_config(); - - build_http_client(&tls, OTEL_EXPORTER_OTLP_TIMEOUT) - .expect("blocking HTTP client should accept PEM client identity"); - } - - #[tokio::test] - async fn build_async_http_client_accepts_pem_client_identity() { - let (_temp_dir, tls) = write_test_mtls_config(); - - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault); - build_async_http_client(&factory, Some(&tls), OTEL_EXPORTER_OTLP_TIMEOUT) - .expect("async HTTP client should accept PEM client identity"); - } - - fn write_test_mtls_config() -> (TempDir, OtelTlsConfig) { - let temp_dir = tempfile::tempdir().expect("temporary TLS fixture directory"); - let CertifiedKey { cert, signing_key } = - generate_simple_self_signed(vec!["localhost".to_string()]) - .expect("test certificate should generate"); - let certificate_path = temp_dir.path().join("client.pem"); - let private_key_path = temp_dir.path().join("client-key.pem"); - fs::write(&certificate_path, cert.pem()).expect("client certificate should write"); - fs::write(&private_key_path, signing_key.serialize_pem()) - .expect("client private key should write"); - - ( - temp_dir, - OtelTlsConfig { - ca_certificate: Some( - AbsolutePathBuf::from_absolute_path(&certificate_path) - .expect("CA certificate path should be absolute"), - ), - client_certificate: Some( - AbsolutePathBuf::from_absolute_path(&certificate_path) - .expect("client certificate path should be absolute"), - ), - client_private_key: Some( - AbsolutePathBuf::from_absolute_path(&private_key_path) - .expect("client private key path should be absolute"), - ), - }, - ) - } -} diff --git a/codex-rs/otel/src/provider.rs b/codex-rs/otel/src/provider.rs deleted file mode 100644 index d04d107a..00000000 --- a/codex-rs/otel/src/provider.rs +++ /dev/null @@ -1,884 +0,0 @@ -use crate::config::OtelExporter; -use crate::config::OtelHttpProtocol; -use crate::config::OtelSettings; -use crate::config::StatsigMetricsSettings; -use crate::metrics::MetricsClient; -use crate::metrics::MetricsConfig; -use crate::targets::is_log_export_target; -use crate::targets::is_trace_safe_target; -use gethostname::gethostname; -use opentelemetry::Context; -use opentelemetry::KeyValue; -use opentelemetry::global; -use opentelemetry::trace::Span as _; -use opentelemetry::trace::SpanBuilder; -use opentelemetry::trace::TracerProvider as _; -use opentelemetry::trace::noop::NoopTracerProvider; -use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; -use opentelemetry_otlp::LogExporter; -use opentelemetry_otlp::OTEL_EXPORTER_OTLP_LOGS_TIMEOUT; -use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TRACES_TIMEOUT; -use opentelemetry_otlp::Protocol; -use opentelemetry_otlp::SpanExporter; -use opentelemetry_otlp::WithExportConfig; -use opentelemetry_otlp::WithHttpConfig; -use opentelemetry_otlp::WithTonicConfig; -use opentelemetry_otlp::tonic_types::metadata::MetadataMap; -use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig; -use opentelemetry_sdk::Resource; -use opentelemetry_sdk::error::OTelSdkResult; -use opentelemetry_sdk::logs::SdkLoggerProvider; -use opentelemetry_sdk::propagation::TraceContextPropagator; -use opentelemetry_sdk::runtime; -use opentelemetry_sdk::trace::BatchSpanProcessor; -use opentelemetry_sdk::trace::SdkTracerProvider; -use opentelemetry_sdk::trace::Span; -use opentelemetry_sdk::trace::SpanData; -use opentelemetry_sdk::trace::SpanProcessor; -use opentelemetry_sdk::trace::Tracer; -use opentelemetry_sdk::trace::TracerProviderBuilder; -use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor as TokioBatchSpanProcessor; -use opentelemetry_semantic_conventions as semconv; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::error::Error; -use std::io; -use std::mem::ManuallyDrop; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::sync::mpsc; -use std::time::Duration; -use tracing::debug; -use tracing_subscriber::Layer; -use tracing_subscriber::registry::LookupSpan; - -const ENV_ATTRIBUTE: &str = "env"; -const HOST_NAME_ATTRIBUTE: &str = "host.name"; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum ResourceKind { - Logs, - Traces, -} - -pub struct OtelProvider { - pub logger: Option, - pub tracer_provider: Option, - pub tracer: Option, - pub metrics: Option, - shutdown_started: AtomicBool, - shutdown_worker: Option>, -} - -struct ShutdownWorker { - provider: ManuallyDrop, - completed_tx: tokio::sync::oneshot::Sender<()>, -} - -struct ShutdownWorkerStartup { - worker_rx: mpsc::Receiver, - ready_tx: mpsc::SyncSender<()>, -} - -#[derive(Debug)] -struct GlobalTracer { - service_name: &'static str, -} - -impl opentelemetry::trace::Tracer for GlobalTracer { - type Span = global::BoxedSpan; - - fn build_with_context(&self, builder: SpanBuilder, parent: &Context) -> Self::Span { - global::tracer(self.service_name).build_with_context(builder, parent) - } -} - -impl OtelProvider { - /// Flushes and shuts down configured exporters at most once. - pub fn shutdown(&self) { - if self.shutdown_started.swap(/*val*/ true, Ordering::AcqRel) { - return; - } - - if let Some(tracer_provider) = &self.tracer_provider { - let _ = tracer_provider.shutdown(); - } - if let Some(metrics) = &self.metrics { - let _ = metrics.shutdown(); - } - if let Some(logger) = &self.logger { - let _ = logger.shutdown(); - } - } - - /// Starts the detached shutdown worker before shutdown-time resource pressure. - fn prepare_shutdown_worker(&mut self) -> io::Result<()> { - self.prepare_shutdown_worker_with_spawner(|startup| { - std::thread::Builder::new() - .name("codex-otel-shutdown".to_string()) - .spawn(move || { - if startup.ready_tx.send(()).is_err() { - return; - } - let Ok(worker) = startup.worker_rx.recv() else { - return; - }; - let provider = ManuallyDrop::into_inner(worker.provider); - provider.shutdown(); - drop(provider); - let _ = worker.completed_tx.send(()); - }) - }) - } - - fn prepare_shutdown_worker_with_spawner(&mut self, spawn: F) -> io::Result<()> - where - F: FnOnce(ShutdownWorkerStartup) -> io::Result>, - { - if self.shutdown_worker.is_some() { - return Ok(()); - } - - let (worker_tx, worker_rx) = mpsc::sync_channel(/*bound*/ 1); - let (ready_tx, ready_rx) = mpsc::sync_channel(/*bound*/ 1); - let startup = ShutdownWorkerStartup { - worker_rx, - ready_tx, - }; - let _shutdown_worker = spawn(startup)?; - ready_rx.recv().map_err(|_| { - io::Error::new( - io::ErrorKind::BrokenPipe, - "telemetry shutdown worker stopped before initializing", - ) - })?; - self.shutdown_worker = Some(worker_tx); - Ok(()) - } - - /// Shuts down exporters on a prepared detached thread within a time budget. - pub async fn shutdown_with_timeout(mut self, timeout: Duration) -> io::Result<()> { - let Some(worker_tx) = self.shutdown_worker.take() else { - // Best-effort shutdown must not run a potentially blocking destructor - // when its worker could not be prepared. - let _provider = ManuallyDrop::new(self); - return Err(io::Error::new( - io::ErrorKind::NotConnected, - "telemetry shutdown worker was not initialized", - )); - }; - - let (completed_tx, completed_rx) = tokio::sync::oneshot::channel(); - let worker = ShutdownWorker { - provider: ManuallyDrop::new(self), - completed_tx, - }; - worker_tx.send(worker).map_err(|_| { - io::Error::new( - io::ErrorKind::BrokenPipe, - "telemetry shutdown worker stopped before receiving the provider", - ) - })?; - - match tokio::time::timeout(timeout, completed_rx).await { - Ok(Ok(())) => Ok(()), - Ok(Err(_)) => Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "telemetry shutdown worker stopped before completing", - )), - Err(_) => Err(io::Error::new( - io::ErrorKind::TimedOut, - "telemetry shutdown exceeded its time budget", - )), - } - } - - pub fn try_new(settings: &OtelSettings) -> Result, Box> { - let log_enabled = !matches!(settings.exporter, OtelExporter::None); - let trace_enabled = !matches!(settings.trace_exporter, OtelExporter::None); - let metric_exporter = crate::config::resolve_exporter(&settings.metrics_exporter); - let metrics_enabled = !matches!(metric_exporter, OtelExporter::None); - - if !log_enabled && !trace_enabled && !metrics_enabled { - // Tracestate propagation is process-global; clear it when these - // settings do not install an active provider. - crate::trace_context::set_tracestate_entries(BTreeMap::new())?; - crate::metrics::buffered::GLOBAL.disable(); - install_global_tracer_provider(/*tracer_provider*/ None); - debug!("No OTEL exporter enabled in settings."); - return Ok(None); - } - - // Provider setup installs process-global OTEL state that cannot be - // rolled back. Validate trace metadata before any setup path can - // mutate those globals, and keep span attribute checks aligned with - // config loading when traces are exported. - if trace_enabled { - crate::config::validate_span_attributes(&settings.span_attributes)?; - } - crate::trace_context::validate_tracestate_entries(&settings.tracestate)?; - - let metrics = if matches!(metric_exporter, OtelExporter::None) { - None - } else { - let mut config = MetricsConfig::otlp( - settings.environment.clone(), - settings.service_name.clone(), - settings.service_version.clone(), - settings.metrics_exporter.clone(), - ) - .with_http_client_factory(settings.http_client_factory.clone()); - if settings.runtime_metrics { - config = config.with_runtime_reader(); - } - Some(MetricsClient::new(config)?) - }; - - let log_resource = make_resource(settings, ResourceKind::Logs); - let trace_resource = make_resource(settings, ResourceKind::Traces); - let logger = log_enabled - .then(|| { - build_logger( - &log_resource, - &settings.exporter, - &settings.http_client_factory, - ) - }) - .transpose()?; - - let tracer_provider = trace_enabled - .then(|| { - build_tracer_provider( - &trace_resource, - &settings.trace_exporter, - settings.span_attributes.clone(), - &settings.http_client_factory, - ) - }) - .transpose()?; - - let tracer = tracer_provider - .as_ref() - .map(|provider| provider.tracer(settings.service_name.clone())); - - let mut provider = Self { - logger, - tracer_provider, - tracer, - metrics, - shutdown_started: AtomicBool::default(), - shutdown_worker: None, - }; - provider.prepare_shutdown_worker()?; - - crate::trace_context::set_tracestate_entries(settings.tracestate.clone())?; - install_global_tracer_provider(provider.tracer_provider.clone()); - if let Some(metrics) = provider.metrics.as_mut() { - *metrics = crate::metrics::install_global(metrics.clone()); - if matches!(settings.metrics_exporter, OtelExporter::Statsig) { - crate::metrics::install_global_statsig_settings(StatsigMetricsSettings { - environment: settings.environment.clone(), - }); - } - } else { - crate::metrics::buffered::GLOBAL.disable(); - } - Ok(Some(provider)) - } - - pub fn logger_layer(&self) -> Option + Send + Sync> - where - S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync, - { - self.logger_export_layer().map(|layer| { - layer.with_filter(tracing_subscriber::filter::filter_fn( - OtelProvider::log_export_filter, - )) - }) - } - - /// Returns a log-export bridge that must be installed beneath the log export filter. - pub fn logger_export_layer(&self) -> Option + Send + Sync> - where - S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync, - { - self.logger.as_ref().map(OpenTelemetryTracingBridge::new) - } - - pub fn tracing_layer(&self) -> Option + Send + Sync> - where - S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync, - { - self.tracer.as_ref().map(|tracer| { - tracing_opentelemetry::layer() - .with_tracer(tracer.clone()) - .with_filter(tracing_subscriber::filter::filter_fn( - OtelProvider::trace_export_filter, - )) - }) - } - - /// Returns a permanent trace layer that follows the process-global tracer provider. - pub fn reloadable_tracing_layer(service_name: &'static str) -> impl Layer + Send + Sync - where - S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync, - { - tracing_opentelemetry::layer() - .with_tracer(GlobalTracer { service_name }) - .with_filter(tracing_subscriber::filter::filter_fn( - Self::trace_export_filter, - )) - } - - pub fn codex_export_filter(meta: &tracing::Metadata<'_>) -> bool { - Self::log_export_filter(meta) - } - - pub fn log_export_filter(meta: &tracing::Metadata<'_>) -> bool { - is_log_export_target(meta.target()) - } - - pub fn trace_export_filter(meta: &tracing::Metadata<'_>) -> bool { - let target = meta.target(); - if meta.is_span() { - // The exporter uses h2 and Tokio. Their root spans escape the - // SDK's suppression and would generate further OTLP exports. - !matches!(target.split("::").next(), Some("h2" | "tokio" | "runtime")) - } else { - is_trace_safe_target(target) - } - } - - pub fn metrics(&self) -> Option<&MetricsClient> { - self.metrics.as_ref() - } -} - -fn install_global_tracer_provider(tracer_provider: Option) { - if let Some(tracer_provider) = tracer_provider { - global::set_tracer_provider(tracer_provider); - global::set_text_map_propagator(TraceContextPropagator::new()); - } else { - global::set_tracer_provider(NoopTracerProvider::new()); - } -} - -impl Drop for OtelProvider { - fn drop(&mut self) { - self.shutdown(); - } -} - -fn make_resource(settings: &OtelSettings, kind: ResourceKind) -> Resource { - Resource::builder() - .with_service_name(settings.service_name.clone()) - .with_attributes(resource_attributes( - settings, - detected_host_name().as_deref(), - kind, - )) - .build() -} - -fn resource_attributes( - settings: &OtelSettings, - host_name: Option<&str>, - kind: ResourceKind, -) -> Vec { - let mut attributes = vec![ - KeyValue::new( - semconv::attribute::SERVICE_VERSION, - settings.service_version.clone(), - ), - KeyValue::new(ENV_ATTRIBUTE, settings.environment.clone()), - ]; - if kind == ResourceKind::Logs - && let Some(host_name) = host_name.and_then(normalize_host_name) - { - attributes.push(KeyValue::new(HOST_NAME_ATTRIBUTE, host_name)); - } - attributes -} - -fn detected_host_name() -> Option { - let host_name = gethostname(); - normalize_host_name(host_name.to_string_lossy().as_ref()) -} - -fn normalize_host_name(host_name: &str) -> Option { - let host_name = host_name.trim(); - (!host_name.is_empty()).then(|| host_name.to_owned()) -} - -fn tracer_provider_builder( - resource: &Resource, - span_attributes: HashMap, -) -> TracerProviderBuilder { - let builder = SdkTracerProvider::builder().with_resource(resource.clone()); - if span_attributes.is_empty() { - builder - } else { - builder.with_span_processor(SpanAttributesProcessor { - attributes: span_attributes, - }) - } -} - -/// Applies configured attributes when spans start. -/// -/// Resource attributes describe the provider process. These attributes are -/// per-span metadata, so they need to be attached before each span is exported. -#[derive(Debug)] -struct SpanAttributesProcessor { - attributes: HashMap, -} - -impl SpanProcessor for SpanAttributesProcessor { - fn on_start(&self, span: &mut Span, _cx: &Context) { - for (key, value) in self.attributes.iter() { - span.set_attribute(KeyValue::new(key.clone(), value.clone())); - } - } - - fn on_end(&self, _span: SpanData) {} - - fn force_flush(&self) -> OTelSdkResult { - Ok(()) - } - - fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult { - Ok(()) - } -} - -fn build_logger( - resource: &Resource, - exporter: &OtelExporter, - factory: &codex_http_client::HttpClientFactory, -) -> Result> { - let mut builder = SdkLoggerProvider::builder().with_resource(resource.clone()); - - match crate::config::resolve_exporter(exporter) { - OtelExporter::None => return Ok(builder.build()), - OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"), - OtelExporter::OtlpGrpc { - endpoint, - headers, - tls, - } => { - debug!("Using OTLP Grpc exporter: {endpoint}"); - - let header_map = crate::otlp::build_header_map(&headers); - - let base_tls_config = ClientTlsConfig::new() - .with_enabled_roots() - .assume_http2(true); - - let tls_config = match tls.as_ref() { - Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls)?, - None => base_tls_config, - }; - - let exporter = LogExporter::builder() - .with_tonic() - .with_endpoint(endpoint) - .with_metadata(MetadataMap::from_headers(header_map)) - .with_tls_config(tls_config) - .build()?; - - builder = builder.with_batch_exporter(crate::network_policy::PolicyExporter { - exporter, - policy: factory.network_policy().clone(), - }); - } - OtelExporter::OtlpHttp { - endpoint, - headers, - protocol, - tls, - } => { - debug!("Using OTLP Http exporter: {endpoint}"); - - let protocol = match protocol { - OtelHttpProtocol::Binary => Protocol::HttpBinary, - OtelHttpProtocol::Json => Protocol::HttpJson, - }; - - let mut exporter_builder = LogExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_protocol(protocol) - .with_headers(headers); - - if factory.network_policy().is_managed() { - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_LOGS_TIMEOUT, - )?; - exporter_builder = exporter_builder.with_http_client(client); - } else if let Some(tls) = tls.as_ref() { - let client = crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_LOGS_TIMEOUT)?; - exporter_builder = exporter_builder.with_http_client(client); - } - - let exporter = exporter_builder.build()?; - - builder = builder.with_batch_exporter(crate::network_policy::PolicyExporter { - exporter, - policy: factory.network_policy().clone(), - }); - } - } - - Ok(builder.build()) -} - -fn build_tracer_provider( - resource: &Resource, - exporter: &OtelExporter, - span_attributes: HashMap, - factory: &codex_http_client::HttpClientFactory, -) -> Result> { - let span_exporter = match crate::config::resolve_exporter(exporter) { - OtelExporter::None => return Ok(tracer_provider_builder(resource, span_attributes).build()), - OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"), - OtelExporter::OtlpGrpc { - endpoint, - headers, - tls, - } => { - debug!("Using OTLP Grpc exporter for traces: {endpoint}"); - - let header_map = crate::otlp::build_header_map(&headers); - - let base_tls_config = ClientTlsConfig::new() - .with_enabled_roots() - .assume_http2(true); - - let tls_config = match tls.as_ref() { - Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls)?, - None => base_tls_config, - }; - - SpanExporter::builder() - .with_tonic() - .with_endpoint(endpoint) - .with_metadata(MetadataMap::from_headers(header_map)) - .with_tls_config(tls_config) - .build()? - } - OtelExporter::OtlpHttp { - endpoint, - headers, - protocol, - tls, - } => { - debug!("Using OTLP Http exporter for traces: {endpoint}"); - - if crate::otlp::current_tokio_runtime_is_multi_thread() { - let protocol = match protocol { - OtelHttpProtocol::Binary => Protocol::HttpBinary, - OtelHttpProtocol::Json => Protocol::HttpJson, - }; - - let mut exporter_builder = SpanExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_protocol(protocol) - .with_headers(headers); - - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, - )?; - exporter_builder = exporter_builder.with_http_client(client); - - let processor = TokioBatchSpanProcessor::builder( - crate::network_policy::PolicyExporter { - exporter: exporter_builder.build()?, - policy: factory.network_policy().clone(), - }, - runtime::Tokio, - ) - .build(); - - return Ok(tracer_provider_builder(resource, span_attributes) - .with_span_processor(processor) - .build()); - } - - let protocol = match protocol { - OtelHttpProtocol::Binary => Protocol::HttpBinary, - OtelHttpProtocol::Json => Protocol::HttpJson, - }; - - let mut exporter_builder = SpanExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_protocol(protocol) - .with_headers(headers); - - if factory.network_policy().is_managed() { - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, - )?; - exporter_builder = exporter_builder.with_http_client(client); - } else if let Some(tls) = tls.as_ref() { - let client = - crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)?; - exporter_builder = exporter_builder.with_http_client(client); - } - - exporter_builder.build()? - } - }; - - let processor = BatchSpanProcessor::builder(crate::network_policy::PolicyExporter { - exporter: span_exporter, - policy: factory.network_policy().clone(), - }) - .build(); - - Ok(tracer_provider_builder(resource, span_attributes) - .with_span_processor(processor) - .build()) -} - -#[cfg(test)] -#[path = "provider_shutdown_tests.rs"] -mod shutdown_tests; - -#[cfg(test)] -mod tests { - use super::*; - use crate::metrics::API_CALL_COUNT_METRIC; - use crate::metrics::API_CALL_DURATION_METRIC; - use crate::metrics::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC; - use crate::metrics::MetricsExporter; - use crate::metrics::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC; - use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC; - use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC; - use crate::metrics::TOOL_CALL_COUNT_METRIC; - use crate::metrics::TOOL_CALL_DURATION_METRIC; - use crate::metrics::TURN_COST_MICROUSD_METRIC; - use crate::metrics::TURN_TOKEN_USAGE_METRIC; - use codex_http_client::HttpClientFactory; - use codex_http_client::OutboundProxyPolicy; - use opentelemetry::trace::Tracer as _; - use opentelemetry_sdk::metrics::InMemoryMetricExporter; - use pretty_assertions::assert_eq; - use std::path::PathBuf; - - #[test] - fn resource_attributes_include_host_name_when_present() { - let attrs = resource_attributes( - &test_otel_settings(), - Some("opentelemetry-test"), - ResourceKind::Logs, - ); - - let host_name = attrs - .iter() - .find(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE) - .map(|kv| kv.value.as_str().to_string()); - - assert_eq!(host_name, Some("opentelemetry-test".to_string())); - } - - #[test] - fn resource_attributes_omit_host_name_when_missing_or_empty() { - let missing = resource_attributes( - &test_otel_settings(), - /*host_name*/ None, - ResourceKind::Logs, - ); - let empty = resource_attributes(&test_otel_settings(), Some(" "), ResourceKind::Logs); - let trace_attrs = resource_attributes( - &test_otel_settings(), - Some("opentelemetry-test"), - ResourceKind::Traces, - ); - - assert!( - !missing - .iter() - .any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE) - ); - assert!( - !empty - .iter() - .any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE) - ); - assert!( - !trace_attrs - .iter() - .any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE) - ); - } - - #[test] - fn log_export_target_excludes_trace_safe_events() { - assert!(is_log_export_target("codex_otel.log_only")); - assert!(is_log_export_target("codex_otel.network_proxy")); - assert!(!is_log_export_target("codex_otel.trace_safe")); - assert!(!is_log_export_target("codex_otel.trace_safe.debug")); - } - - #[test] - fn trace_export_target_only_includes_trace_safe_prefix() { - assert!(is_trace_safe_target("codex_otel.trace_safe")); - assert!(is_trace_safe_target("codex_otel.trace_safe.summary")); - assert!(!is_trace_safe_target("codex_otel.log_only")); - assert!(!is_trace_safe_target("codex_otel.network_proxy")); - } - - #[test] - fn disabled_trace_settings_replace_global_tracer_with_noop() -> Result<(), Box> { - global::set_tracer_provider(SdkTracerProvider::builder().build()); - let before = global::tracer("codex-otel-test").start("before-disable"); - assert!( - before.is_recording(), - "the test provider should record before tracing is disabled" - ); - - let provider = OtelProvider::try_new(&test_otel_settings())?; - assert!(provider.is_none()); - - let after = global::tracer("codex-otel-test").start("after-disable"); - assert!( - !after.is_recording(), - "new spans should not record after tracing is disabled" - ); - Ok(()) - } - - #[test] - fn cached_global_metrics_follow_reinstalled_provider() -> Result<(), Box> { - let initial = - crate::metrics::install_global(MetricsClient::new(MetricsConfig::in_memory( - "test", - "codex-test", - env!("CARGO_PKG_VERSION"), - InMemoryMetricExporter::default(), - ))?); - crate::metrics::install_global_statsig_settings(StatsigMetricsSettings { - environment: "test".to_string(), - }); - assert!(crate::metrics::global_statsig_settings().is_some()); - let controller = codex_http_client::NetworkPolicyController::default(); - let policy = controller.policy(); - controller.publish( - policy.revision(), - codex_http_client::DestinationPolicy::Unrestricted, - ); - let cached = crate::metrics::global().expect("initial global metrics client"); - - let exporter = InMemoryMetricExporter::default(); - let replacement = crate::metrics::install_global(MetricsClient::new( - MetricsConfig::in_memory( - "test", - "codex-test", - env!("CARGO_PKG_VERSION"), - exporter.clone(), - ) - .with_http_client_factory( - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) - .with_network_policy(policy), - ), - )?); - assert!(crate::metrics::global_statsig_settings().is_none()); - cached.counter("codex.after_transition", /*inc*/ 1, &[])?; - initial.shutdown()?; - replacement.shutdown()?; - - let exported_metrics = exporter.get_finished_metrics()?; - let mut names: Vec<_> = exported_metrics - .iter() - .flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics) - .flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics) - .map(opentelemetry_sdk::metrics::data::Metric::name) - .collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names, vec!["codex.after_transition"]); - - Ok(()) - } - - #[test] - fn statsig_disabled_metrics_are_not_exported() -> Result<(), Box> { - let exporter = InMemoryMetricExporter::default(); - let mut config = MetricsConfig::otlp( - "test", - "codex-cli", - env!("CARGO_PKG_VERSION"), - OtelExporter::Statsig, - ); - config.exporter = MetricsExporter::InMemory(exporter.clone()); - let metrics = MetricsClient::new(config)?; - - metrics.counter(API_CALL_COUNT_METRIC, /*inc*/ 1, &[])?; - metrics.record_duration(API_CALL_DURATION_METRIC, Duration::from_millis(100), &[])?; - metrics.counter_with_description( - EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC, - "Client-side exec-server RPC attempts.", - /*inc*/ 1, - &[("method", "fs/readFile")], - )?; - metrics.counter("codex.conversation.turn.count", /*inc*/ 1, &[])?; - metrics.record_duration( - RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC, - Duration::from_millis(100), - &[], - )?; - metrics.record_duration( - RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC, - Duration::from_millis(100), - &[], - )?; - metrics.record_duration( - RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC, - Duration::from_millis(100), - &[], - )?; - metrics.counter(TOOL_CALL_COUNT_METRIC, /*inc*/ 1, &[])?; - metrics.record_duration(TOOL_CALL_DURATION_METRIC, Duration::from_millis(25), &[])?; - metrics.counter(TURN_COST_MICROUSD_METRIC, /*inc*/ 1, &[])?; - metrics.histogram(TURN_TOKEN_USAGE_METRIC, /*value*/ 100, &[])?; - metrics.counter("codex.turns", /*inc*/ 1, &[])?; - metrics.shutdown()?; - - let exported_metrics = exporter.get_finished_metrics()?; - let mut names: Vec<_> = exported_metrics - .iter() - .flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics) - .flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics) - .map(opentelemetry_sdk::metrics::data::Metric::name) - .collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names, vec!["codex.turns"]); - - Ok(()) - } - - fn test_otel_settings() -> OtelSettings { - OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-test".to_string(), - service_version: "0.0.0".to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - } - } -} diff --git a/codex-rs/otel/src/provider_shutdown_tests.rs b/codex-rs/otel/src/provider_shutdown_tests.rs deleted file mode 100644 index 768aa0f4..00000000 --- a/codex-rs/otel/src/provider_shutdown_tests.rs +++ /dev/null @@ -1,469 +0,0 @@ -use super::Context; -use super::OTelSdkResult; -use super::OtelProvider; -use super::SdkTracerProvider; -use super::Span; -use super::SpanData; -use super::SpanProcessor; -use pretty_assertions::assert_eq; -use std::io::ErrorKind; -#[cfg(any(target_os = "linux", target_os = "macos"))] -use std::process::Command; -use std::sync::Arc; -use std::sync::Condvar; -use std::sync::Mutex; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use std::sync::mpsc; -use std::time::Duration; - -#[cfg(any(target_os = "linux", target_os = "macos"))] -const GUARD_PAGE_FAILURE_CHILD_TEST: &str = - "provider::shutdown_tests::bounded_shutdown_survives_worker_guard_page_failure_child"; - -#[cfg(target_os = "macos")] -static GUARD_PAGE_INJECTION_ENABLED: AtomicBool = AtomicBool::new(false); -#[cfg(target_os = "macos")] -static GUARD_PAGE_INJECTION_ARMED: AtomicBool = AtomicBool::new(false); -#[cfg(target_os = "macos")] -static GUARD_PAGE_INJECTION_OBSERVED: AtomicBool = AtomicBool::new(false); - -#[cfg(target_os = "macos")] -#[unsafe(export_name = "mprotect")] -unsafe extern "C" fn fault_injected_mprotect( - address: *mut libc::c_void, - length: usize, - protection: libc::c_int, -) -> libc::c_int { - let original_symbol = unsafe { libc::dlsym(libc::RTLD_NEXT, c"mprotect".as_ptr()) }; - let original_mprotect: unsafe extern "C" fn( - *mut libc::c_void, - usize, - libc::c_int, - ) -> libc::c_int = unsafe { std::mem::transmute(original_symbol) }; - - if GUARD_PAGE_INJECTION_ENABLED.load(Ordering::Relaxed) - && protection == libc::PROT_NONE - && length == unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize - { - let mut thread_name = [0; 64]; - let named_shutdown_worker = unsafe { - libc::pthread_getname_np( - libc::pthread_self(), - thread_name.as_mut_ptr(), - thread_name.len(), - ) - } == 0 - && unsafe { std::ffi::CStr::from_ptr(thread_name.as_ptr()) } - .to_bytes() - .starts_with(b"codex-otel-shut"); - - if named_shutdown_worker { - GUARD_PAGE_INJECTION_OBSERVED.store(/*val*/ true, Ordering::Relaxed); - if GUARD_PAGE_INJECTION_ARMED.load(Ordering::Relaxed) { - unsafe { *libc::__error() = libc::ENOMEM }; - return -1; - } - } - } - - unsafe { original_mprotect(address, length, protection) } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum ShutdownBehavior { - Complete, - WaitForRelease, -} - -#[derive(Debug, Default)] -struct ShutdownState { - force_flushes: AtomicUsize, - shutdowns: AtomicUsize, - released: Mutex, - release_notification: Condvar, - started: Mutex>>, - completed: Mutex>>, -} - -#[derive(Debug)] -struct ControlledSpanProcessor { - behavior: ShutdownBehavior, - state: Arc, -} - -impl SpanProcessor for ControlledSpanProcessor { - fn on_start(&self, _span: &mut Span, _context: &Context) {} - - fn on_end(&self, _span: SpanData) {} - - fn force_flush(&self) -> OTelSdkResult { - self.state - .force_flushes - .fetch_add(/*val*/ 1, Ordering::Relaxed); - Ok(()) - } - - fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult { - self.state.shutdowns.fetch_add(/*val*/ 1, Ordering::Relaxed); - if let Some(started) = self.state.started.lock().expect("started lock").take() { - let _ = started.send(()); - } - - if self.behavior == ShutdownBehavior::WaitForRelease { - drop( - self.state - .release_notification - .wait_while( - self.state.released.lock().expect("release lock"), - |released| !*released, - ) - .expect("release notification"), - ); - } - - if let Some(completed) = self.state.completed.lock().expect("completed lock").take() { - let _ = completed.send(()); - } - Ok(()) - } -} - -struct TestProvider { - provider: OtelProvider, - state: Arc, - started: mpsc::Receiver<()>, - completed: mpsc::Receiver<()>, -} - -fn test_provider(behavior: ShutdownBehavior) -> TestProvider { - let (started_tx, started) = mpsc::channel(); - let (completed_tx, completed) = mpsc::channel(); - let state = Arc::new(ShutdownState { - started: Mutex::new(Some(started_tx)), - completed: Mutex::new(Some(completed_tx)), - ..ShutdownState::default() - }); - let processor = ControlledSpanProcessor { - behavior, - state: Arc::clone(&state), - }; - let tracer_provider = SdkTracerProvider::builder() - .with_span_processor(processor) - .build(); - - TestProvider { - provider: OtelProvider { - logger: None, - tracer_provider: Some(tracer_provider), - tracer: None, - metrics: None, - shutdown_started: AtomicBool::default(), - shutdown_worker: None, - }, - state, - started, - completed, - } -} - -#[tokio::test(flavor = "current_thread")] -async fn bounded_shutdown_does_not_flush_when_worker_creation_fails() { - let TestProvider { - mut provider, - state, - started, - completed, - } = test_provider(ShutdownBehavior::Complete); - - let preparation = provider.prepare_shutdown_worker_with_spawner(|_startup| { - Err(std::io::Error::new( - ErrorKind::WouldBlock, - "shutdown worker could not be created", - )) - }); - - assert_eq!( - preparation.as_ref().map_err(std::io::Error::kind), - Err(ErrorKind::WouldBlock) - ); - - let result = provider - .shutdown_with_timeout(Duration::from_secs(/*secs*/ 1)) - .await; - assert_eq!( - result.as_ref().map_err(std::io::Error::kind), - Err(ErrorKind::NotConnected) - ); - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 0); - assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0); - assert_eq!(started.try_recv(), Err(mpsc::TryRecvError::Empty)); - assert_eq!(completed.try_recv(), Err(mpsc::TryRecvError::Empty)); -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -#[test] -fn bounded_shutdown_survives_worker_guard_page_failure() { - let unique_suffix = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("current time follows Unix epoch") - .as_nanos(); - let temporary_directory = std::env::temp_dir().join(format!( - "codex-otel-guard-page-{}-{unique_suffix}", - std::process::id() - )); - std::fs::create_dir(&temporary_directory).expect("create fault injector directory"); - - let observed_path = temporary_directory.join("guard_page_fault.observed"); - let mut subprocess = Command::new(std::env::current_exe().expect("current test binary")); - subprocess - .arg("--exact") - .arg(GUARD_PAGE_FAILURE_CHILD_TEST) - .arg("--ignored") - .arg("--nocapture") - .arg("--test-threads=1") - .env("CODEX_OTEL_GUARD_PAGE_FAILURE_CHILD", "1") - .env("CODEX_OTEL_GUARD_PAGE_FAILURE_OBSERVED", &observed_path); - - let output = subprocess - .output() - .expect("run guard-page failure subprocess"); - let injection_was_observed = observed_path.is_file(); - - let _ = std::fs::remove_dir_all(&temporary_directory); - assert!( - output.status.success(), - "bounded telemetry shutdown crashed when its worker guard page could not be allocated\n\ - status: {}\nstdout:\n{}\nstderr:\n{}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert!( - injection_was_observed, - "guard-page fault injection never became active on {}-{}", - std::env::consts::ARCH, - std::env::consts::OS - ); -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -#[test] -// The parent regression invokes this ignored test in a fresh subprocess with -// `--exact --ignored`, isolating fatal native-thread initialization failures. -#[ignore] -fn bounded_shutdown_survives_worker_guard_page_failure_child() { - if std::env::var_os("CODEX_OTEL_GUARD_PAGE_FAILURE_CHILD").is_none() { - return; - } - - let TestProvider { - mut provider, - state, - .. - } = test_provider(ShutdownBehavior::Complete); - - #[cfg(target_os = "macos")] - GUARD_PAGE_INJECTION_ENABLED.store(/*val*/ true, Ordering::Relaxed); - - provider - .prepare_shutdown_worker() - .expect("pre-initialize bounded shutdown worker"); - - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_time() - .build() - .expect("create current-thread runtime"); - - #[cfg(target_os = "macos")] - { - assert!( - GUARD_PAGE_INJECTION_OBSERVED.load(Ordering::Relaxed), - "Rust mprotect interposer did not observe shutdown-worker guard-page setup" - ); - GUARD_PAGE_INJECTION_ARMED.store(/*val*/ true, Ordering::Relaxed); - } - - #[cfg(target_os = "linux")] - { - use seccompiler::BpfProgram; - use seccompiler::SeccompAction; - use seccompiler::SeccompCmpArgLen; - use seccompiler::SeccompCmpOp; - use seccompiler::SeccompCondition; - use seccompiler::SeccompFilter; - use seccompiler::SeccompRule; - - let page_size = - usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).expect("valid page size"); - let mapped_page = unsafe { - libc::mmap( - std::ptr::null_mut(), - page_size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - /*fd*/ -1, - /*offset*/ 0, - ) - }; - assert_ne!( - mapped_page, - libc::MAP_FAILED, - "map a page to verify guard-page fault injection: {}", - std::io::Error::last_os_error() - ); - - let protection_is_none = SeccompCondition::new( - /*arg_index*/ 2, - SeccompCmpArgLen::Dword, - SeccompCmpOp::Eq, - libc::PROT_NONE as u64, - ) - .expect("create guard-page seccomp condition"); - let rule = - SeccompRule::new(vec![protection_is_none]).expect("create guard-page seccomp rule"); - let filter = SeccompFilter::new( - std::collections::BTreeMap::from([(libc::SYS_mprotect, vec![rule])]), - SeccompAction::Allow, - SeccompAction::Errno(libc::ENOMEM as u32), - std::env::consts::ARCH - .try_into() - .expect("supported seccomp architecture"), - ) - .expect("create guard-page seccomp filter"); - let program: BpfProgram = filter - .try_into() - .expect("compile guard-page seccomp filter"); - seccompiler::apply_filter(&program).expect("install guard-page seccomp filter"); - - let protection_result = unsafe { libc::mprotect(mapped_page, page_size, libc::PROT_NONE) }; - let protection_error = std::io::Error::last_os_error(); - assert_eq!(protection_result, -1); - assert_eq!(protection_error.raw_os_error(), Some(libc::ENOMEM)); - assert_eq!(unsafe { libc::munmap(mapped_page, page_size) }, 0); - } - - let observed_path = std::env::var_os("CODEX_OTEL_GUARD_PAGE_FAILURE_OBSERVED") - .expect("guard-page fault observation path"); - std::fs::write(observed_path, "observed").expect("record guard-page fault injection"); - - runtime - .block_on(provider.shutdown_with_timeout(Duration::from_secs(/*secs*/ 1))) - .expect("bounded telemetry shutdown should not create a new native thread"); - - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1); -} - -#[tokio::test(flavor = "current_thread")] -async fn bounded_shutdown_times_out_without_blocking_the_runtime() { - let TestProvider { - mut provider, - state, - started, - completed, - } = test_provider(ShutdownBehavior::WaitForRelease); - provider - .prepare_shutdown_worker() - .expect("pre-initialize bounded shutdown worker"); - - let result = provider - .shutdown_with_timeout(Duration::from_millis(/*millis*/ 50)) - .await; - - assert_eq!( - result.as_ref().map_err(std::io::Error::kind), - Err(ErrorKind::TimedOut) - ); - started - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown worker started"); - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1); - assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0); - - *state.released.lock().expect("release lock") = true; - state.release_notification.notify_one(); - completed - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown worker completed after release"); -} - -async fn assert_bounded_shutdown_completes() { - let TestProvider { - mut provider, - state, - started, - completed, - } = test_provider(ShutdownBehavior::Complete); - provider - .prepare_shutdown_worker() - .expect("pre-initialize bounded shutdown worker"); - - provider - .shutdown_with_timeout(Duration::from_secs(/*secs*/ 1)) - .await - .expect("healthy processor shuts down"); - - started - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown worker started"); - completed - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown worker completed"); - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1); - assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0); -} - -#[tokio::test(flavor = "current_thread")] -async fn bounded_shutdown_completes_on_current_thread_runtime() { - assert_bounded_shutdown_completes().await; -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn bounded_shutdown_completes_on_multi_thread_runtime() { - assert_bounded_shutdown_completes().await; -} - -#[test] -fn explicit_shutdown_and_drop_shut_down_exporters_once_without_force_flush() { - let TestProvider { - provider, - state, - started, - completed, - } = test_provider(ShutdownBehavior::Complete); - - provider.shutdown(); - provider.shutdown(); - drop(provider); - - started - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown started"); - completed - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown completed"); - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1); - assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0); -} - -#[test] -fn drop_shuts_down_exporters_without_force_flush() { - let TestProvider { - provider, - state, - started, - completed, - } = test_provider(ShutdownBehavior::Complete); - - drop(provider); - - started - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown started"); - completed - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("shutdown completed"); - assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1); - assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0); -} diff --git a/codex-rs/otel/src/skill_invocation.rs b/codex-rs/otel/src/skill_invocation.rs index 1bc3b2a9..8506f9fa 100644 --- a/codex-rs/otel/src/skill_invocation.rs +++ b/codex-rs/otel/src/skill_invocation.rs @@ -1,4 +1,4 @@ -//! Exports skill-use metadata without skill contents, filesystem paths, or tool payloads. +//! Logs skill-use metadata locally without skill contents, filesystem paths, or tool payloads. //! Detection belongs to the caller; an invocation does not imply successful task completion. use crate::SessionTelemetry; @@ -7,6 +7,7 @@ use crate::targets::OTEL_LOG_ONLY_TARGET; use codex_protocol::protocol::SkillScope; /// How Codex detected the skill's use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SkillInvocationType { Explicit, Implicit, diff --git a/codex-rs/otel/src/targets.rs b/codex-rs/otel/src/targets.rs index 765c7015..65f9173b 100644 --- a/codex-rs/otel/src/targets.rs +++ b/codex-rs/otel/src/targets.rs @@ -1,11 +1,16 @@ -pub(crate) const OTEL_TARGET_PREFIX: &str = "codex_otel"; pub(crate) const OTEL_LOG_ONLY_TARGET: &str = "codex_otel.log_only"; pub(crate) const OTEL_TRACE_SAFE_TARGET: &str = "codex_otel.trace_safe"; -pub(crate) fn is_log_export_target(target: &str) -> bool { - target.starts_with(OTEL_TARGET_PREFIX) && !is_trace_safe_target(target) -} - pub(crate) fn is_trace_safe_target(target: &str) -> bool { target.starts_with(OTEL_TRACE_SAFE_TARGET) } + +/// Filters spans and events that are safe to attach to local trace layers. +pub fn trace_export_filter(meta: &tracing::Metadata<'_>) -> bool { + let target = meta.target(); + if meta.is_span() { + !matches!(target.split("::").next(), Some("h2" | "tokio" | "runtime")) + } else { + is_trace_safe_target(target) + } +} diff --git a/codex-rs/otel/src/trace_context.rs b/codex-rs/otel/src/trace_context.rs index 8ce0f99a..ea7bdfcd 100644 --- a/codex-rs/otel/src/trace_context.rs +++ b/codex-rs/otel/src/trace_context.rs @@ -1,16 +1,11 @@ -use std::collections::BTreeMap; -use std::collections::BTreeSet; use std::collections::HashMap; use std::env; -use std::str::FromStr; use std::sync::OnceLock; -use std::sync::RwLock; use codex_protocol::protocol::W3cTraceContext; use opentelemetry::Context; use opentelemetry::propagation::TextMapPropagator; use opentelemetry::trace::TraceContextExt; -use opentelemetry::trace::TraceState; use opentelemetry_sdk::propagation::TraceContextPropagator; use tracing::Span; use tracing::debug; @@ -21,11 +16,6 @@ const TRACEPARENT_ENV_VAR: &str = "TRACEPARENT"; const TRACESTATE_ENV_VAR: &str = "TRACESTATE"; static TRACEPARENT_CONTEXT: OnceLock> = OnceLock::new(); -// Trace context propagation can happen outside the provider object, so configured -// tracestate lives beside the process-global tracer provider. -static TRACESTATE_ENTRIES: OnceLock>>> = - OnceLock::new(); - pub fn current_span_w3c_trace_context() -> Option { span_w3c_trace_context(&Span::current()) } @@ -38,60 +28,12 @@ pub fn span_w3c_trace_context(span: &Span) -> Option { let mut headers = HashMap::new(); TraceContextPropagator::new().inject_context(&context, &mut headers); - let tracestate = headers.remove("tracestate"); - let configured_tracestate_guard = tracestate_entries() - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner); - Some(W3cTraceContext { traceparent: headers.remove("traceparent"), - tracestate: merge_tracestate_entries(tracestate.as_deref(), &configured_tracestate_guard), + tracestate: headers.remove("tracestate"), }) } -/// Injects the W3C trace context for `span` into HTTP headers. -/// -/// Existing `traceparent` and `tracestate` values are replaced so callers can -/// safely reuse a request header map while keeping the supplied span as the -/// source of truth. -pub fn inject_span_w3c_trace_headers(span: &Span, headers: &mut http::HeaderMap) -> bool { - let Some(trace) = span_w3c_trace_context(span) else { - return false; - }; - match trace.traceparent { - Some(traceparent) => { - if let Ok(value) = http::HeaderValue::from_str(&traceparent) { - headers.insert("traceparent", value); - } - } - None => { - headers.remove("traceparent"); - } - } - match trace.tracestate { - Some(tracestate) => { - if let Ok(value) = http::HeaderValue::from_str(&tracestate) { - headers.insert("tracestate", value); - } - } - None => { - headers.remove("tracestate"); - } - } - true -} - -pub(crate) fn set_tracestate_entries( - entries: BTreeMap>, -) -> Result<(), Box> { - validate_tracestate_entries(&entries)?; - let mut guard = tracestate_entries() - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *guard = entries; - Ok(()) -} - pub fn current_span_trace_id() -> Option { let context = Span::current().context(); let span = context.span(); @@ -161,177 +103,6 @@ fn load_traceparent_context() -> Option { } } -fn tracestate_entries() -> &'static RwLock>> { - TRACESTATE_ENTRIES.get_or_init(|| RwLock::new(BTreeMap::new())) -} - -fn merge_tracestate_entries( - tracestate: Option<&str>, - configured_entries: &BTreeMap>, -) -> Option { - let mut trace_state = tracestate - .and_then(|tracestate| match TraceState::from_str(tracestate) { - Ok(trace_state) => Some(trace_state), - Err(err) => { - warn!("ignoring invalid tracestate while propagating trace context: {err}"); - None - } - }) - .unwrap_or_default(); - - // TraceState::insert places members at the front. Reverse iteration keeps - // deterministic map order while upserting fields inside configured members. - for (key, fields) in configured_entries.iter().rev() { - let value = merge_tracestate_member_fields(trace_state.get(key), fields); - trace_state = match trace_state.insert(key.clone(), value) { - Ok(trace_state) => trace_state, - Err(err) => { - warn!("ignoring configured tracestate while propagating trace context: {err}"); - break; - } - }; - } - - let tracestate = trace_state.header(); - (!tracestate.is_empty()).then_some(tracestate) -} - -/// Validates configured tracestate members before they are propagated in W3C trace context. -pub fn validate_tracestate_entries( - entries: &BTreeMap>, -) -> Result<(), Box> { - // Reject malformed entries before installing them so propagated trace - // context remains acceptable to other W3C Trace Context extractors. The - // SDK validates member keys and list structure, but configured member - // fields are joined into header values here and need stricter validation. - let entries = entries - .iter() - .map(|(key, fields)| encode_tracestate_member_fields(key, fields)) - .collect::, _>>()?; - TraceState::from_key_value( - entries - .iter() - .map(|(key, value)| (key.as_str(), value.as_str())), - ) - .map_err(|err| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!("invalid configured tracestate: {err}"), - ) - })?; - Ok(()) -} - -/// Validates one configured tracestate member and its encoded field value. -pub fn validate_tracestate_member( - member_key: &str, - fields: &BTreeMap, -) -> Result<(), Box> { - let (key, value) = encode_tracestate_member_fields(member_key, fields)?; - TraceState::from_key_value([(key.as_str(), value.as_str())]).map_err(|err| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!("invalid configured tracestate: {err}"), - ) - })?; - Ok(()) -} - -fn encode_tracestate_member_fields( - member_key: &str, - fields: &BTreeMap, -) -> Result<(String, String), Box> { - // Configured fields are encoded into one opaque tracestate member value. - // Validate both the field grammar and the final header value so malformed - // config cannot produce propagated trace context that downstream W3C - // extractors reject. - let mut encoded = Vec::with_capacity(fields.len()); - for (field_key, value) in fields { - if !is_configured_tracestate_field_key(field_key) { - return Err(invalid_tracestate_config(format!( - "invalid configured tracestate field key {member_key}.{field_key}" - ))); - } - if !is_configured_tracestate_field_value(value) { - return Err(invalid_tracestate_config(format!( - "invalid configured tracestate value for {member_key}.{field_key}" - ))); - } - encoded.push(format!("{field_key}:{value}")); - } - let value = encoded.join(";"); - if !is_header_safe_tracestate_member_value(&value) { - return Err(invalid_tracestate_config(format!( - "invalid configured tracestate value for {member_key}" - ))); - } - Ok((member_key.to_string(), value)) -} - -fn is_configured_tracestate_field_key(field_key: &str) -> bool { - !field_key.is_empty() - && field_key - .bytes() - .all(|byte| matches!(byte, b'!'..=b'~') && !matches!(byte, b':' | b';' | b',' | b'=')) -} - -fn is_configured_tracestate_field_value(value: &str) -> bool { - value - .bytes() - .all(|byte| is_tracestate_member_value_byte(byte) && byte != b';') -} - -fn is_header_safe_tracestate_member_value(value: &str) -> bool { - value.is_empty() - || (value.bytes().all(is_tracestate_member_value_byte) - && value.as_bytes().last().is_some_and(|byte| *byte != b' ')) -} - -fn is_tracestate_member_value_byte(byte: u8) -> bool { - matches!(byte, b' '..=b'~') && !matches!(byte, b',' | b'=') -} - -fn invalid_tracestate_config(message: String) -> Box { - Box::new(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - message, - )) -} - -fn merge_tracestate_member_fields( - existing: Option<&str>, - configured_fields: &BTreeMap, -) -> String { - // W3C TraceState treats member values as opaque strings. The config models - // values as semicolon-separated key:value fields so selected fields can be - // upserted without replacing unrelated fields in the same member. - let mut fields = Vec::new(); - let mut seen = BTreeSet::new(); - - if let Some(existing) = existing { - for field in existing.split(';').filter(|field| !field.is_empty()) { - if let Some((field_key, _)) = field.split_once(':') { - if let Some(value) = configured_fields.get(field_key) { - if seen.insert(field_key) { - fields.push(format!("{field_key}:{value}")); - } - continue; - } - seen.insert(field_key); - } - fields.push(field.to_string()); - } - } - - fields.extend( - configured_fields - .iter() - .filter(|(field_key, _)| !seen.contains(field_key.as_str())) - .map(|(field_key, value)| format!("{field_key}:{value}")), - ); - fields.join(";") -} - #[cfg(test)] mod tests { use super::context_from_trace_headers; diff --git a/codex-rs/otel/tests/suite/buffered_operations_tests.rs b/codex-rs/otel/tests/suite/buffered_operations_tests.rs index 63b3dd8e..a70bf1fc 100644 --- a/codex-rs/otel/tests/suite/buffered_operations_tests.rs +++ b/codex-rs/otel/tests/suite/buffered_operations_tests.rs @@ -1,20 +1,12 @@ -//! Exercises global operation buffering across shutdown and rejected configuration changes. +//! Exercises global operation buffering across shutdown and replacement installations. -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; use codex_otel::MetricsClient; use codex_otel::MetricsConfig; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; use codex_otel::install_global_metrics; use codex_otel::record_global_operation; use opentelemetry_sdk::metrics::data::AggregatedMetrics; use opentelemetry_sdk::metrics::data::MetricData; use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use std::collections::HashMap; use std::time::Duration; fn install() -> MetricsClient { @@ -76,51 +68,3 @@ fn shutdown_buffers_until_replacement_and_preserves_newer_installations() { assert_eq!(totals(&third), (1, 1, 7.0)); third.shutdown().unwrap(); } - -#[test] -fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown() { - let metrics = install(); - let mut settings = OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "test".to_string(), - service_version: "1".to_string(), - codex_home: ".".into(), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: "http://127.0.0.1:1/v1/traces".to_string(), - headers: Default::default(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::from([(String::new(), "invalid".to_string())]), - tracestate: BTreeMap::new(), - }; - assert_eq!( - OtelProvider::try_new(&settings).err().unwrap().to_string(), - "configured span attribute key must not be empty" - ); - observe(); - assert_eq!(totals(&metrics), (1, 1, 7.0)); - - metrics.shutdown().unwrap(); - observe(); - assert!(OtelProvider::try_new(&settings).is_err()); - let replacement = install(); - assert_eq!(totals(&replacement), (1, 1, 7.0)); - replacement.shutdown().unwrap(); - - settings.span_attributes.clear(); - for trace_exporter in [settings.trace_exporter.clone(), OtelExporter::None] { - let metrics = install(); - settings.trace_exporter = trace_exporter; - let _provider = OtelProvider::try_new(&settings).unwrap(); - metrics.shutdown().unwrap(); - observe(); - let replacement = install(); - assert_eq!(totals(&replacement), (0, 0, 0.0)); - replacement.shutdown().unwrap(); - } -} diff --git a/codex-rs/otel/tests/suite/mod.rs b/codex-rs/otel/tests/suite/mod.rs index 2422d083..907a4d42 100644 --- a/codex-rs/otel/tests/suite/mod.rs +++ b/codex-rs/otel/tests/suite/mod.rs @@ -1,8 +1,6 @@ #[path = "buffered_operations_tests.rs"] mod buffered_operations; mod manager_metrics; -mod otel_export_routing_policy; -mod otlp_http_loopback; mod runtime_summary; mod send; mod snapshot; diff --git a/codex-rs/otel/tests/suite/otel_export_routing_policy.rs b/codex-rs/otel/tests/suite/otel_export_routing_policy.rs deleted file mode 100644 index 3d6052cc..00000000 --- a/codex-rs/otel/tests/suite/otel_export_routing_policy.rs +++ /dev/null @@ -1,1314 +0,0 @@ -use crate::harness::attributes_to_map; -use crate::harness::build_metrics_with_defaults; -use crate::harness::find_metric; -use crate::harness::latest_metrics; -use codex_api::AgentIdentityTelemetry; -use codex_otel::AuthEnvTelemetryMetadata; -use codex_otel::OtelProvider; -use codex_otel::SSE_EVENT_COUNT_METRIC; -use codex_otel::SSE_EVENT_DURATION_METRIC; -use codex_otel::SessionTelemetry; -use codex_otel::TelemetryAuthMode; -use opentelemetry::KeyValue; -use opentelemetry::logs::AnyValue; -use opentelemetry::trace::TracerProvider as _; -use opentelemetry_sdk::logs::InMemoryLogExporter; -use opentelemetry_sdk::logs::SdkLogRecord; -use opentelemetry_sdk::logs::SdkLoggerProvider; -use opentelemetry_sdk::metrics::data::AggregatedMetrics; -use opentelemetry_sdk::metrics::data::MetricData; -use opentelemetry_sdk::trace::InMemorySpanExporter; -use opentelemetry_sdk::trace::SdkTracerProvider; -use pretty_assertions::assert_eq; -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::time::Duration; -use tracing_subscriber::Layer; -use tracing_subscriber::filter::filter_fn; -use tracing_subscriber::layer::SubscriberExt; - -use codex_protocol::AgentPath; -use codex_protocol::ThreadId; -use codex_protocol::ToolName; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::ToolResultLogConfig; -use codex_protocol::models::ImageReference; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::GuardianAssessmentEvent; -use codex_protocol::protocol::GuardianAssessmentOutcome; -use codex_protocol::protocol::GuardianAssessmentStatus; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::TokenUsage; -use codex_protocol::user_input::UserInput; -use eventsource_stream::Event as StreamEvent; - -fn log_attributes(record: &SdkLogRecord) -> BTreeMap { - record - .attributes_iter() - .map(|(key, value)| (key.as_str().to_string(), any_value_to_string(value))) - .collect() -} - -fn span_event_attributes(event: &opentelemetry::trace::Event) -> BTreeMap { - event - .attributes - .iter() - .map(|KeyValue { key, value, .. }| (key.as_str().to_string(), value.to_string())) - .collect() -} - -fn any_value_to_string(value: &AnyValue) -> String { - match value { - AnyValue::Int(value) => value.to_string(), - AnyValue::Double(value) => value.to_string(), - AnyValue::String(value) => value.as_str().to_string(), - AnyValue::Boolean(value) => value.to_string(), - AnyValue::Bytes(value) => String::from_utf8_lossy(value).into_owned(), - AnyValue::ListAny(value) => format!("{value:?}"), - AnyValue::Map(value) => format!("{value:?}"), - _ => format!("{value:?}"), - } -} - -fn find_log_by_event_name<'a>( - logs: &'a [opentelemetry_sdk::logs::in_memory_exporter::LogDataWithResource], - event_name: &str, -) -> &'a opentelemetry_sdk::logs::in_memory_exporter::LogDataWithResource { - logs.iter() - .find(|log| { - log_attributes(&log.record) - .get("event.name") - .is_some_and(|value| value == event_name) - }) - .expect("log event should exist") -} - -fn find_span_event_by_name_attr<'a>( - events: &'a [opentelemetry::trace::Event], - event_name: &str, -) -> &'a opentelemetry::trace::Event { - events - .iter() - .find(|event| { - span_event_attributes(event) - .get("event.name") - .is_some_and(|value| value == event_name) - }) - .expect("span event should exist") -} - -fn auth_env_metadata() -> AuthEnvTelemetryMetadata { - AuthEnvTelemetryMetadata { - openai_api_key_env_present: true, - codex_api_key_env_present: false, - codex_api_key_env_enabled: true, - provider_env_key_name: Some("configured".to_string()), - provider_env_key_present: Some(true), - refresh_token_url_override_present: true, - } -} - -#[test] -fn suppressing_sse_delta_logs_preserves_errors_completions_and_metrics() -> codex_otel::Result<()> { - for log_sse_deltas in [true, false] { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ); - let (metrics, metric_exporter) = build_metrics_with_defaults(&[])?; - let mut manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - /*account_id*/ None, - /*account_email*/ None, - /*auth_mode*/ None, - "test_originator".to_string(), - /*log_user_prompts*/ false, - "tty".to_string(), - SessionSource::Cli, - ) - .with_metrics_without_metadata_tags(metrics); - if !log_sse_deltas { - manager = manager.without_sse_delta_logs(); - } - let events = [ - ("response.output_text.delta", "{}", true), - ("response.reasoning_summary_text.delta", "{}", true), - ("response.custom_tool_call_input.delta", "{}", true), - ("response.output_text.done", "{}", true), - ("response.completed", "{}", true), - ("response.output_text.delta", "{", false), - ("response.failed", r#"{"error":"failed"}"#, false), - ]; - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - for (kind, data, _) in events { - manager.log_sse_event::<&str>( - &Ok(Some(Ok(StreamEvent { - event: kind.to_string(), - data: data.to_string(), - id: String::new(), - retry: None, - }))), - Duration::from_millis(10), - ); - } - manager.sse_event_completed( - &TokenUsage { - input_tokens: 7, - ..Default::default() - }, - /*ttft_ms*/ Some(10), - ); - }); - logger_provider.force_flush().expect("flush logs"); - let logs = log_exporter.get_emitted_logs().expect("exported logs"); - let exported_events = logs - .iter() - .map(|log| { - let attributes = log_attributes(&log.record); - ( - attributes["event.kind"].clone(), - attributes.contains_key("error.message"), - attributes.get("input_token_count").cloned(), - ) - }) - .collect::>(); - let mut expected_events = Vec::new(); - if log_sse_deltas { - expected_events.extend([ - ("response.output_text.delta".to_string(), false, None), - ( - "response.reasoning_summary_text.delta".to_string(), - false, - None, - ), - ( - "response.custom_tool_call_input.delta".to_string(), - false, - None, - ), - ]); - } - expected_events.extend([ - ("response.output_text.done".to_string(), false, None), - ("response.completed".to_string(), false, None), - ("response.output_text.delta".to_string(), true, None), - ("response.failed".to_string(), true, None), - ( - "response.completed".to_string(), - false, - Some("7".to_string()), - ), - ]); - assert_eq!(exported_events, expected_events); - - manager.shutdown_metrics()?; - let resource_metrics = latest_metrics(&metric_exporter); - let expected_counts = events - .iter() - .map(|(kind, _, success)| { - ( - BTreeMap::from([ - ("kind".to_string(), kind.to_string()), - ("success".to_string(), success.to_string()), - ]), - 1, - ) - }) - .collect::>(); - let counter = find_metric(&resource_metrics, SSE_EVENT_COUNT_METRIC).expect("SSE counter"); - let AggregatedMetrics::U64(MetricData::Sum(sum)) = counter.data() else { - panic!("expected SSE counter"); - }; - assert_eq!( - sum.data_points() - .map(|point| (attributes_to_map(point.attributes()), point.value())) - .collect::>(), - expected_counts, - ); - let duration = - find_metric(&resource_metrics, SSE_EVENT_DURATION_METRIC).expect("SSE duration"); - let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = duration.data() else { - panic!("expected SSE duration histogram"); - }; - assert_eq!( - histogram - .data_points() - .map(|point| ( - attributes_to_map(point.attributes()), - (point.count(), point.sum()) - )) - .collect::>(), - expected_counts - .into_keys() - .map(|tags| (tags, (1, 10.0))) - .collect(), - ); - } - Ok(()) -} - -#[test] -fn otel_export_routing_policy_routes_prompt_and_guardian_payloads() { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::ApiKey), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - SessionSource::Cli, - ); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - manager.user_prompt(&[ - UserInput::Text { - text: "super secret prompt".to_string(), - text_elements: Vec::new(), - }, - UserInput::Image { - image: ImageReference::Inline { - image_url: "https://example.com/image.png".to_string(), - }, - detail: None, - }, - UserInput::LocalImage { - path: PathBuf::from("/tmp/secret.png"), - detail: None, - }, - ]); - let mut assessment: GuardianAssessmentEvent = serde_json::from_value(serde_json::json!({ - "id": "review", - "turn_id": "turn", - "target_item_id": "tool-call", - "status": "in_progress", - "risk_level": "medium", - "user_authorization": "high", - "rationale": format!("{}🦀", "x".repeat(/*n*/ 65_535)), - "action": {"type": "mcp_tool_call", "server": "private-server", "tool_name": "tool"}, - })) - .expect("assessment"); - manager.guardian_assessment(&assessment, /*outcome*/ None); - for (status, outcome) in [ - ( - GuardianAssessmentStatus::Approved, - Some(GuardianAssessmentOutcome::Allow), - ), - ( - GuardianAssessmentStatus::Denied, - Some(GuardianAssessmentOutcome::Deny), - ), - (GuardianAssessmentStatus::Denied, None), - (GuardianAssessmentStatus::TimedOut, None), - (GuardianAssessmentStatus::Aborted, None), - ] { - assessment.status = status; - if outcome.is_none() { - assessment.rationale = None; - } - manager.guardian_assessment(&assessment, outcome); - } - }); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - assert!( - logs.iter() - .all(|log| { log.record.target().map(Cow::as_ref) == Some("codex_otel.log_only") }) - ); - - let prompt_log = find_log_by_event_name(&logs, "codex.user_prompt"); - let prompt_log_attrs = log_attributes(&prompt_log.record); - assert_eq!( - prompt_log_attrs.get("prompt").map(String::as_str), - Some("super secret prompt") - ); - assert_eq!( - prompt_log_attrs.get("user.email").map(String::as_str), - Some("engineer@example.com") - ); - - let assessments: Vec<_> = logs - .iter() - .map(|log| log_attributes(&log.record)) - .filter(|attrs| { - attrs.get("event.name").map(String::as_str) == Some("codex.guardian_assessment") - }) - .collect(); - assert_eq!( - assessments - .iter() - .map(|attrs| ( - attrs["status"].as_str(), - attrs.get("outcome").map(String::as_str), - attrs.get("rationale").map(String::len), - attrs.get("rationale_length").map(String::as_str), - attrs.get("rationale_truncated").map(String::as_str), - )) - .collect::>(), - vec![ - ( - "approved", - Some("allow"), - Some(65_535), - Some("65539"), - Some("true") - ), - ( - "denied", - Some("deny"), - Some(65_535), - Some("65539"), - Some("true") - ), - ("denied", None, None, None, None), - ("timed_out", None, None, None, None), - ("aborted", None, None, None, None), - ], - ); - assert!(!format!("{assessments:?}").contains("private-server")); - - let spans = span_exporter.get_finished_spans().expect("span export"); - assert_eq!(spans.len(), 1); - let span_events = &spans[0].events.events; - assert_eq!(span_events.len(), 1); - - let prompt_trace_event = find_span_event_by_name_attr(span_events, "codex.user_prompt"); - let prompt_trace_attrs = span_event_attributes(prompt_trace_event); - assert_eq!( - prompt_trace_attrs.get("prompt_length").map(String::as_str), - Some("19") - ); - assert_eq!( - prompt_trace_attrs - .get("text_input_count") - .map(String::as_str), - Some("1") - ); - assert_eq!( - prompt_trace_attrs - .get("image_input_count") - .map(String::as_str), - Some("1") - ); - assert_eq!( - prompt_trace_attrs - .get("local_image_input_count") - .map(String::as_str), - Some("1") - ); - assert!(!prompt_trace_attrs.contains_key("prompt")); - assert!(!prompt_trace_attrs.contains_key("user.email")); - assert!(!prompt_trace_attrs.contains_key("user.account_id")); -} - -#[test] -fn otel_export_routing_policy_routes_tool_result_log_and_trace_events() { - let output = "secret output\nsecond line\n".repeat(100); - let root_id = ThreadId::new(); - let child_id = ThreadId::new(); - let legacy_id = ThreadId::new(); - let unnamed_id = ThreadId::new(); - let make_manager = |thread_id, source| { - SessionTelemetry::new( - thread_id, - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::ApiKey), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - source, - ) - }; - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = make_manager(root_id, SessionSource::Cli).with_product_sku(Some("codex")); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - let manager = manager.with_tool_result_log_config(ToolResultLogConfig { - max_bytes: output.len(), - }); - manager.tool_result_with_tags( - &ToolName::namespaced("mcp__example", "shell"), - "call-1", - "secret arguments", - std::time::Duration::from_millis(42), - /*success*/ true, - &output, - &[], - &[ - ("mcp_server", "internal-mcp"), - ("mcp_server_origin", "stdio"), - ], - ); - let child = make_manager( - child_id, - SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id: root_id, - depth: 1, - agent_path: Some(AgentPath::try_from("/root/reviewer").expect("agent path")), - agent_nickname: Some("legacy nickname".to_string()), - agent_role: None, - }), - ) - .with_product_sku(Some("customer-specific-value")); - child.tool_result_with_tags( - &ToolName::plain("shell"), - "call-2", - "{}", - std::time::Duration::ZERO, - /*success*/ true, - &output, - &[], - &[], - ); - let legacy = make_manager( - legacy_id, - SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id: root_id, - depth: 1, - agent_path: None, - agent_nickname: Some("Mendel".to_string()), - agent_role: None, - }), - ); - let unnamed = make_manager(unnamed_id, SessionSource::SubAgent(SubAgentSource::Review)); - for (manager, name, error) in [ - (&manager, "root_failure", "failure"), - (&legacy, "legacy_failure", output.as_str()), - (&unnamed, "unnamed_failure", "failure"), - ] { - manager.tool_result_with_tags( - &ToolName::plain(name), - name, - "{}", - std::time::Duration::ZERO, - /*success*/ false, - error, - &[], - &[], - ); - } - }); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - assert!( - logs.iter() - .all(|log| { log.record.target().map(Cow::as_ref) == Some("codex_otel.log_only") }) - ); - - let tool_log = find_log_by_event_name(&logs, "codex.tool_result"); - let tool_log_attrs = log_attributes(&tool_log.record); - assert_eq!( - tool_log_attrs.get("tool_name").map(String::as_str), - Some("shell") - ); - assert_eq!( - tool_log_attrs.get("tool_namespace").map(String::as_str), - Some("mcp__example") - ); - assert_eq!( - tool_log_attrs.get("arguments").map(String::as_str), - Some("secret arguments") - ); - assert_eq!( - tool_log_attrs.get("output").map(String::as_str), - Some(output.as_str()) - ); - let tool_logs: Vec<_> = logs - .iter() - .map(|log| log_attributes(&log.record)) - .filter(|attrs| attrs.get("event.name").map(String::as_str) == Some("codex.tool_result")) - .collect(); - assert_eq!( - tool_logs - .iter() - .map(|attrs| attrs.get("product_sku").map(String::as_str)) - .collect::>(), - vec![Some("codex"), Some("other"), Some("codex"), None, None], - ); - assert_eq!( - tool_logs - .iter() - .map(|attrs| ( - attrs["conversation.id"].clone(), - attrs["agent_name"].clone(), - attrs["output_truncated"].clone(), - )) - .collect::>(), - vec![ - ( - root_id.to_string(), - "/root".to_string(), - "false".to_string() - ), - ( - child_id.to_string(), - "/root/reviewer".to_string(), - "true".to_string() - ), - ( - root_id.to_string(), - "/root".to_string(), - "false".to_string() - ), - ( - legacy_id.to_string(), - "Mendel".to_string(), - "true".to_string() - ), - ( - unnamed_id.to_string(), - unnamed_id.to_string(), - "false".to_string() - ), - ] - ); - assert!(tool_logs[1]["output"].ends_with("[... telemetry preview truncated ...]")); - let sequences: Vec = tool_logs - .iter() - .map(|attrs| attrs["tool_result_seq"].parse().expect("numeric sequence")) - .collect(); - assert!(sequences[0] > 0); - assert!(sequences.windows(2).all(|pair| pair[0] < pair[1])); - assert_eq!( - tool_log_attrs.get("mcp_server").map(String::as_str), - Some("internal-mcp") - ); - assert_eq!( - tool_log_attrs.get("mcp_server_origin").map(String::as_str), - Some("stdio") - ); - - let spans = span_exporter.get_finished_spans().expect("span export"); - assert_eq!(spans.len(), 1); - let span_events = &spans[0].events.events; - assert_eq!(span_events.len(), tool_logs.len()); - for (event, log) in span_events.iter().zip(&tool_logs) { - let attrs = span_event_attributes(event); - assert_eq!(attrs.get("tool_name"), log.get("tool_name")); - assert_eq!(attrs.get("tool_namespace"), log.get("tool_namespace")); - assert_eq!(attrs.get("tool_result_seq"), log.get("tool_result_seq")); - assert_eq!(attrs.get("product_sku"), log.get("product_sku")); - assert_eq!(attrs.get("output_truncated"), log.get("output_truncated")); - assert!(!attrs.contains_key("agent_name")); - } - - let tool_trace_event = find_span_event_by_name_attr(span_events, "codex.tool_result"); - let tool_trace_attrs = span_event_attributes(tool_trace_event); - assert_eq!( - tool_trace_attrs.get("arguments_length").map(String::as_str), - Some("16") - ); - assert_eq!( - tool_trace_attrs.get("output_length").map(String::as_str), - Some(output.len().to_string().as_str()) - ); - assert_eq!( - tool_trace_attrs - .get("output_line_count") - .map(String::as_str), - Some(output.lines().count().to_string().as_str()) - ); - assert!(!tool_trace_attrs.contains_key("arguments")); - assert!(!tool_trace_attrs.contains_key("output")); - assert!(!tool_trace_attrs.contains_key("mcp_server")); - assert!(!tool_trace_attrs.contains_key("mcp_server_origin")); -} - -#[test] -fn otel_export_routing_policy_routes_auth_recovery_log_and_trace_events() { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::Chatgpt), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - SessionSource::Cli, - ); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - manager.record_auth_recovery( - "managed", - "reload", - "recovery_succeeded", - Some("req-401"), - Some("ray-401"), - Some("missing_authorization_header"), - Some("token_expired"), - /*recovery_reason*/ None, - Some(true), - ); - }); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - let recovery_log = find_log_by_event_name(&logs, "codex.auth_recovery"); - let recovery_log_attrs = log_attributes(&recovery_log.record); - assert_eq!( - recovery_log_attrs.get("auth.mode").map(String::as_str), - Some("managed") - ); - assert_eq!( - recovery_log_attrs.get("auth.step").map(String::as_str), - Some("reload") - ); - assert_eq!( - recovery_log_attrs.get("auth.outcome").map(String::as_str), - Some("recovery_succeeded") - ); - assert_eq!( - recovery_log_attrs - .get("auth.request_id") - .map(String::as_str), - Some("req-401") - ); - assert_eq!( - recovery_log_attrs.get("auth.cf_ray").map(String::as_str), - Some("ray-401") - ); - assert_eq!( - recovery_log_attrs.get("auth.error").map(String::as_str), - Some("missing_authorization_header") - ); - assert_eq!( - recovery_log_attrs - .get("auth.error_code") - .map(String::as_str), - Some("token_expired") - ); - assert_eq!( - recovery_log_attrs - .get("auth.state_changed") - .map(String::as_str), - Some("true") - ); - - let spans = span_exporter.get_finished_spans().expect("span export"); - assert_eq!(spans.len(), 1); - let span_events = &spans[0].events.events; - assert_eq!(span_events.len(), 1); - - let recovery_trace_event = find_span_event_by_name_attr(span_events, "codex.auth_recovery"); - let recovery_trace_attrs = span_event_attributes(recovery_trace_event); - assert_eq!( - recovery_trace_attrs.get("auth.mode").map(String::as_str), - Some("managed") - ); - assert_eq!( - recovery_trace_attrs.get("auth.step").map(String::as_str), - Some("reload") - ); - assert_eq!( - recovery_trace_attrs.get("auth.outcome").map(String::as_str), - Some("recovery_succeeded") - ); - assert_eq!( - recovery_trace_attrs - .get("auth.request_id") - .map(String::as_str), - Some("req-401") - ); - assert_eq!( - recovery_trace_attrs.get("auth.cf_ray").map(String::as_str), - Some("ray-401") - ); - assert_eq!( - recovery_trace_attrs.get("auth.error").map(String::as_str), - Some("missing_authorization_header") - ); - assert_eq!( - recovery_trace_attrs - .get("auth.error_code") - .map(String::as_str), - Some("token_expired") - ); - assert_eq!( - recovery_trace_attrs - .get("auth.state_changed") - .map(String::as_str), - Some("true") - ); -} - -#[test] -fn otel_export_routing_policy_routes_api_request_auth_observability() { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::Chatgpt), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - SessionSource::Cli, - ) - .with_auth_env(auth_env_metadata()); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - manager.conversation_starts( - "openai", - /*reasoning_effort*/ None, - ReasoningSummary::Auto, - /*context_window*/ None, - /*auto_compact_token_limit*/ None, - AskForApproval::Never, - SandboxPolicy::DangerFullAccess, - Vec::new(), - /*legacy_multi_agent_disabled_sources*/ &[], - ); - let agent_identity_telemetry = AgentIdentityTelemetry { - agent_id: "agent-runtime-otel".to_string(), - task_id: "task-run-otel".to_string(), - }; - manager.record_api_request( - /*attempt*/ 1, - Some(401), - Some("http 401"), - std::time::Duration::from_millis(42), - /*auth_header_attached*/ true, - Some("authorization"), - /*retry_after_unauthorized*/ true, - Some("managed"), - Some("refresh_token"), - "/responses", - Some("req-401"), - Some("ray-401"), - Some("missing_authorization_header"), - Some("token_expired"), - Some(&agent_identity_telemetry), - ); - }); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - let conversation_log = find_log_by_event_name(&logs, "codex.conversation_starts"); - let conversation_log_attrs = log_attributes(&conversation_log.record); - assert_eq!( - conversation_log_attrs - .get("auth.env_openai_api_key_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - conversation_log_attrs - .get("auth.env_provider_key_name") - .map(String::as_str), - Some("configured") - ); - let request_log = find_log_by_event_name(&logs, "codex.api_request"); - let request_log_attrs = log_attributes(&request_log.record); - assert_eq!( - request_log_attrs - .get("auth.header_attached") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs - .get("auth.header_name") - .map(String::as_str), - Some("authorization") - ); - assert_eq!( - request_log_attrs - .get("auth.retry_after_unauthorized") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs - .get("auth.recovery_mode") - .map(String::as_str), - Some("managed") - ); - assert_eq!( - request_log_attrs - .get("auth.recovery_phase") - .map(String::as_str), - Some("refresh_token") - ); - assert_eq!( - request_log_attrs.get("endpoint").map(String::as_str), - Some("/responses") - ); - assert_eq!( - request_log_attrs.get("auth.error").map(String::as_str), - Some("missing_authorization_header") - ); - assert_eq!( - request_log_attrs - .get("auth.env_codex_api_key_enabled") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs - .get("auth.env_refresh_token_url_override_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-otel") - ); - assert_eq!( - request_log_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-otel") - ); - - let spans = span_exporter.get_finished_spans().expect("span export"); - let conversation_trace_event = - find_span_event_by_name_attr(&spans[0].events.events, "codex.conversation_starts"); - let conversation_trace_attrs = span_event_attributes(conversation_trace_event); - assert_eq!( - conversation_trace_attrs - .get("auth.env_provider_key_present") - .map(String::as_str), - Some("true") - ); - let request_trace_event = - find_span_event_by_name_attr(&spans[0].events.events, "codex.api_request"); - let request_trace_attrs = span_event_attributes(request_trace_event); - assert_eq!( - request_trace_attrs - .get("auth.header_attached") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_trace_attrs - .get("auth.header_name") - .map(String::as_str), - Some("authorization") - ); - assert_eq!( - request_trace_attrs - .get("auth.retry_after_unauthorized") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_trace_attrs.get("endpoint").map(String::as_str), - Some("/responses") - ); - assert_eq!( - request_trace_attrs - .get("auth.env_openai_api_key_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_trace_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-otel") - ); - assert_eq!( - request_trace_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-otel") - ); -} - -#[test] -fn otel_export_routing_policy_routes_websocket_connect_auth_observability() { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - let (metrics, metric_exporter) = build_metrics_with_defaults(&[]).unwrap(); - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::Chatgpt), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - SessionSource::Cli, - ) - .with_auth_env(auth_env_metadata()) - .with_product_sku(Some("codex")) - .with_metrics_without_metadata_tags(metrics); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - let agent_identity_telemetry = AgentIdentityTelemetry { - agent_id: "agent-runtime-ws".to_string(), - task_id: "task-run-ws".to_string(), - }; - manager.record_websocket_connect( - std::time::Duration::from_millis(17), - Some(401), - Some("http 401"), - /*auth_header_attached*/ true, - Some("authorization"), - /*retry_after_unauthorized*/ true, - Some("managed"), - Some("reload"), - "/responses", - /*reauth*/ true, - Some("req-ws-401"), - Some("ray-ws-401"), - Some("missing_authorization_header"), - Some("token_expired"), - Some(&agent_identity_telemetry), - ); - manager.shutdown_metrics().unwrap(); - }); - - let exported = latest_metrics(&metric_exporter); - let expected_labels = BTreeMap::from([ - ("product_sku".to_string(), "codex".to_string()), - ("reauth".to_string(), "true".to_string()), - ("success".to_string(), "false".to_string()), - ]); - let counter = find_metric(&exported, codex_otel::WEBSOCKET_CONNECT_COUNT_METRIC).unwrap(); - let AggregatedMetrics::U64(MetricData::Sum(sum)) = counter.data() else { - panic!("expected connect counter"); - }; - let point = sum.data_points().next().expect("failed handshake"); - assert_eq!(point.value(), 1); - assert_eq!(attributes_to_map(point.attributes()), expected_labels); - - let duration = find_metric(&exported, codex_otel::WEBSOCKET_CONNECT_DURATION_METRIC).unwrap(); - let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = duration.data() else { - panic!("expected connect duration histogram"); - }; - let point = histogram.data_points().next().expect("failed handshake"); - assert_eq!((point.count(), point.sum()), (1, 17.0)); - assert_eq!(attributes_to_map(point.attributes()), expected_labels); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - let connect_log = find_log_by_event_name(&logs, "codex.websocket_connect"); - let connect_log_attrs = log_attributes(&connect_log.record); - assert_eq!( - connect_log_attrs - .get("auth.header_attached") - .map(String::as_str), - Some("true") - ); - assert_eq!( - connect_log_attrs - .get("auth.header_name") - .map(String::as_str), - Some("authorization") - ); - assert_eq!( - connect_log_attrs.get("auth.error").map(String::as_str), - Some("missing_authorization_header") - ); - assert_eq!( - connect_log_attrs.get("endpoint").map(String::as_str), - Some("/responses") - ); - assert_eq!( - connect_log_attrs - .get("auth.connection_reused") - .map(String::as_str), - Some("false") - ); - assert_eq!( - connect_log_attrs - .get("auth.env_provider_key_name") - .map(String::as_str), - Some("configured") - ); - assert_eq!( - connect_log_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-ws") - ); - assert_eq!( - connect_log_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-ws") - ); - - let spans = span_exporter.get_finished_spans().expect("span export"); - let connect_trace_event = - find_span_event_by_name_attr(&spans[0].events.events, "codex.websocket_connect"); - let connect_trace_attrs = span_event_attributes(connect_trace_event); - assert_eq!( - connect_trace_attrs - .get("auth.recovery_phase") - .map(String::as_str), - Some("reload") - ); - assert_eq!( - connect_trace_attrs - .get("auth.env_refresh_token_url_override_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - connect_trace_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-ws") - ); - assert_eq!( - connect_trace_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-ws") - ); -} - -#[test] -fn otel_export_routing_policy_routes_websocket_request_transport_observability() { - let log_exporter = InMemoryLogExporter::default(); - let logger_provider = SdkLoggerProvider::builder() - .with_simple_exporter(log_exporter.clone()) - .build(); - let span_exporter = InMemorySpanExporter::default(); - let tracer_provider = SdkTracerProvider::builder() - .with_simple_exporter(span_exporter.clone()) - .build(); - let tracer = tracer_provider.tracer("sink-split-test"); - - let subscriber = tracing_subscriber::registry() - .with( - opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new( - &logger_provider, - ) - .with_filter(filter_fn(OtelProvider::log_export_filter)), - ) - .with( - tracing_opentelemetry::layer() - .with_tracer(tracer) - .with_filter(filter_fn(OtelProvider::trace_export_filter)), - ); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - let manager = SessionTelemetry::new( - ThreadId::new(), - "gpt-5.1", - "gpt-5.1", - Some("account-id".to_string()), - Some("engineer@example.com".to_string()), - Some(TelemetryAuthMode::Chatgpt), - "codex_exec".to_string(), - /*log_user_prompts*/ true, - "tty".to_string(), - SessionSource::Cli, - ) - .with_auth_env(auth_env_metadata()); - let root_span = tracing::info_span!("root"); - let _root_guard = root_span.enter(); - let agent_identity_telemetry = AgentIdentityTelemetry { - agent_id: "agent-runtime-ws-request".to_string(), - task_id: "task-run-ws-request".to_string(), - }; - manager.record_websocket_request( - std::time::Duration::from_millis(23), - Some("stream error"), - /*connection_reused*/ true, - Some(&agent_identity_telemetry), - ); - }); - - logger_provider.force_flush().expect("flush logs"); - tracer_provider.force_flush().expect("flush traces"); - - let logs = log_exporter.get_emitted_logs().expect("log export"); - let request_log = find_log_by_event_name(&logs, "codex.websocket_request"); - let request_log_attrs = log_attributes(&request_log.record); - assert_eq!( - request_log_attrs - .get("auth.connection_reused") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs.get("error.message").map(String::as_str), - Some("stream error") - ); - assert_eq!( - request_log_attrs - .get("auth.env_openai_api_key_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_log_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-ws-request") - ); - assert_eq!( - request_log_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-ws-request") - ); - - let spans = span_exporter.get_finished_spans().expect("span export"); - let request_trace_event = - find_span_event_by_name_attr(&spans[0].events.events, "codex.websocket_request"); - let request_trace_attrs = span_event_attributes(request_trace_event); - assert_eq!( - request_trace_attrs - .get("auth.connection_reused") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_trace_attrs - .get("auth.env_provider_key_present") - .map(String::as_str), - Some("true") - ); - assert_eq!( - request_trace_attrs.get("auth.agent_id").map(String::as_str), - Some("agent-runtime-ws-request") - ); - assert_eq!( - request_trace_attrs.get("auth.task_id").map(String::as_str), - Some("task-run-ws-request") - ); -} diff --git a/codex-rs/otel/tests/suite/otlp_http_loopback.rs b/codex-rs/otel/tests/suite/otlp_http_loopback.rs deleted file mode 100644 index 44b73bd8..00000000 --- a/codex-rs/otel/tests/suite/otlp_http_loopback.rs +++ /dev/null @@ -1,947 +0,0 @@ -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_otel::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC; -use codex_otel::MetricsClient; -use codex_otel::MetricsConfig; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; -use codex_otel::Result; -use codex_otel::current_span_w3c_trace_context; -use codex_otel::set_parent_from_w3c_trace_context; -use codex_protocol::protocol::W3cTraceContext; -use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::io::Read as _; -use std::io::Write as _; -use std::net::TcpListener; -use std::net::TcpStream; -use std::path::PathBuf; -use std::sync::Mutex; -use std::sync::mpsc; -use std::thread; -use std::time::Duration; -use std::time::Instant; -use tracing_subscriber::layer::SubscriberExt; - -static TRACE_CONTEXT_CONFIG_LOCK: Mutex<()> = Mutex::new(()); - -struct CapturedRequest { - path: String, - content_type: Option, - body: Vec, -} - -fn read_http_request( - stream: &mut TcpStream, -) -> std::io::Result<(String, HashMap, Vec)> { - stream.set_read_timeout(Some(Duration::from_secs(2)))?; - let deadline = Instant::now() + Duration::from_secs(2); - - let mut read_next = |buf: &mut [u8]| -> std::io::Result { - loop { - match stream.read(buf) { - Ok(n) => return Ok(n), - Err(err) - if err.kind() == std::io::ErrorKind::WouldBlock - || err.kind() == std::io::ErrorKind::Interrupted => - { - if Instant::now() >= deadline { - return Err(std::io::Error::new( - std::io::ErrorKind::TimedOut, - "timed out waiting for request data", - )); - } - thread::sleep(Duration::from_millis(5)); - } - Err(err) => return Err(err), - } - } - }; - - let mut buf = Vec::new(); - let mut scratch = [0u8; 8192]; - let header_end = loop { - let n = read_next(&mut scratch)?; - if n == 0 { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "EOF before headers", - )); - } - buf.extend_from_slice(&scratch[..n]); - if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { - break end; - } - if buf.len() > 1024 * 1024 { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "headers too large", - )); - } - }; - - let headers_bytes = &buf[..header_end]; - let mut body_bytes = buf[header_end + 4..].to_vec(); - - let headers_str = std::str::from_utf8(headers_bytes).map_err(|err| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("headers not utf-8: {err}"), - ) - })?; - let mut lines = headers_str.split("\r\n"); - let start = lines.next().ok_or_else(|| { - std::io::Error::new(std::io::ErrorKind::InvalidData, "missing request line") - })?; - let mut parts = start.split_whitespace(); - let _method = parts.next().unwrap_or_default(); - let path = parts - .next() - .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "missing path"))? - .to_string(); - - let mut headers = HashMap::new(); - for line in lines { - let Some((k, v)) = line.split_once(':') else { - continue; - }; - headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string()); - } - - if let Some(len) = headers - .get("content-length") - .and_then(|v| v.parse::().ok()) - { - while body_bytes.len() < len { - let n = read_next(&mut scratch)?; - if n == 0 { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "EOF before body complete", - )); - } - body_bytes.extend_from_slice(&scratch[..n]); - if body_bytes.len() > len + 1024 * 1024 { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "body too large", - )); - } - } - body_bytes.truncate(len); - } - - Ok((path, headers, body_bytes)) -} - -fn write_http_response(stream: &mut TcpStream, status: &str) -> std::io::Result<()> { - let response = format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); - stream.write_all(response.as_bytes())?; - stream.flush() -} - -#[test] -fn otlp_http_exporter_honors_cumulative_temporality_env() -> Result<()> { - // Isolate the environment setting from other tests, including under Bazel/libtest. - const CHILD_ENV: &str = "CODEX_OTEL_TEMPORALITY_TEST_CHILD"; - if std::env::var_os(CHILD_ENV).is_none() { - let current_thread = thread::current(); - let output = std::process::Command::new(std::env::current_exe().expect("test executable")) - .args([ - "--exact", - current_thread.name().expect("test name"), - "--nocapture", - ]) - .env(CHILD_ENV, "1") - .env( - "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE", - "cumulative", - ) - .env("OTEL_METRIC_EXPORT_INTERVAL", "60000") - .output() - .expect("run test with cumulative temporality configured"); - assert!( - output.status.success(), - "{}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr), - ); - return Ok(()); - } - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - listener.set_nonblocking(true).expect("set_nonblocking"); - - let (tx, rx) = mpsc::channel::>(); - let server = thread::spawn(move || { - let mut captured = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(3); - - while Instant::now() < deadline { - match listener.accept() { - Ok((mut stream, _)) => { - let result = read_http_request(&mut stream); - let _ = write_http_response(&mut stream, "202 Accepted"); - if let Ok((path, headers, body)) = result { - captured.push(CapturedRequest { - path, - content_type: headers.get("content-type").cloned(), - body, - }); - } - } - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - - let _ = tx.send(captured); - }); - - let metrics = MetricsClient::new(MetricsConfig::otlp( - "test", - "codex-cli", - env!("CARGO_PKG_VERSION"), - OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/metrics"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - ))?; - - metrics.counter("codex.turns", /*inc*/ 1, &[("source", "test")])?; - metrics.counter("codex.api_request", /*inc*/ 1, &[("status", "200")])?; - metrics.counter_with_description( - EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC, - "Client-side exec-server RPC attempts.", - /*inc*/ 1, - &[("method", "fs/readFile")], - )?; - metrics.record_duration( - "codex.api_request.duration_ms", - Duration::from_millis(100), - &[("status", "200")], - )?; - metrics.counter("codex.conversation.turn.count", /*inc*/ 1, &[])?; - metrics.record_duration( - "codex.responses_api_engine_iapi_ttft.duration_ms", - Duration::from_millis(100), - &[], - )?; - metrics.record_duration( - "codex.responses_api_engine_service_tbt.duration_ms", - Duration::from_millis(100), - &[], - )?; - metrics.record_duration( - "codex.responses_api_engine_service_ttft.duration_ms", - Duration::from_millis(100), - &[], - )?; - metrics.counter("codex.tool.call", /*inc*/ 1, &[("tool", "test")])?; - metrics.record_duration( - "codex.tool.call.duration_ms", - Duration::from_millis(42), - &[("tool", "test")], - )?; - metrics.histogram( - "codex.turn.token_usage", - /*value*/ 100, - &[("token_type", "total")], - )?; - metrics.gauge_with_description( - "codex.active", - "Number of active Codex operations.", - /*value*/ 1, - &[("component", "test")], - )?; - metrics.shutdown()?; - - server.join().expect("server join"); - let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); - - let request = captured - .iter() - .find(|req| req.path == "/v1/metrics") - .expect("/v1/metrics request should be captured"); - let content_type = request - .content_type - .as_deref() - .unwrap_or(""); - assert!( - content_type.starts_with("application/json"), - "unexpected content-type: {content_type}" - ); - - let payload: serde_json::Value = serde_json::from_slice(&request.body).expect("OTLP JSON"); - let counter = payload["resourceMetrics"][0]["scopeMetrics"][0]["metrics"] - .as_array() - .expect("exported metrics") - .iter() - .find(|metric| metric["name"] == "codex.turns") - .expect("exported counter"); - assert_eq!( - counter["sum"]["aggregationTemporality"], - serde_json::json!(2) - ); - - let body = String::from_utf8_lossy(&request.body); - assert!( - body.contains("codex.turns"), - "expected metric name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("codex.active"), - "expected gauge not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.api_request\""), - "expected API-request counter not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains(EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC), - "custom OTLP must retain the exec-server client counter excluded from built-in Statsig" - ); - assert!( - body.contains("\"codex.api_request.duration_ms\""), - "expected API-request duration not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.conversation.turn.count\""), - "expected conversation turn count not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.responses_api_engine_iapi_ttft.duration_ms\""), - "expected engine IAPI TTFT duration not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.responses_api_engine_service_tbt.duration_ms\""), - "expected engine service TBT duration not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.responses_api_engine_service_ttft.duration_ms\""), - "expected engine service TTFT duration not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.tool.call\""), - "expected tool-call counter not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.turn.token_usage\""), - "expected turn-token histogram not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("\"codex.tool.call.duration_ms\""), - "expected tool-call duration not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("component") && body.contains("test"), - "expected gauge tag not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - - Ok(()) -} - -#[test] -fn otlp_http_exporter_sends_logs_to_collector() --> std::result::Result<(), Box> { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - listener.set_nonblocking(true).expect("set_nonblocking"); - - let (tx, rx) = mpsc::channel::>(); - let server = thread::spawn(move || { - let mut captured = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(3); - - while Instant::now() < deadline { - match listener.accept() { - Ok((mut stream, _)) => { - let result = read_http_request(&mut stream); - let _ = write_http_response(&mut stream, "202 Accepted"); - if let Ok((path, headers, body)) = result { - captured.push(CapturedRequest { - path, - content_type: headers.get("content-type").cloned(), - body, - }); - } - } - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - - let _ = tx.send(captured); - }); - - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/logs"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - })? - .expect("otel provider"); - let logger_layer = otel.logger_layer().expect("logger layer"); - let subscriber = tracing_subscriber::registry().with(logger_layer); - - tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - tracing::event!( - target: "codex_otel.log_only", - tracing::Level::INFO, - event.name = "codex.test.log_exported", - "test OTEL log export" - ); - }); - otel.shutdown(); - - server.join().expect("server join"); - let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); - - let request = captured - .iter() - .find(|req| req.path == "/v1/logs") - .expect("/v1/logs request should be captured"); - let content_type = request - .content_type - .as_deref() - .unwrap_or(""); - assert!( - content_type.starts_with("application/json"), - "unexpected content-type: {content_type}" - ); - - let body = String::from_utf8_lossy(&request.body); - assert!( - body.contains("codex.test.log_exported"), - "expected exported log event not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - Ok(()) -} - -#[test] -fn otel_provider_rejects_header_unsafe_configured_tracestate() { - let result = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: "http://127.0.0.1:1/v1/traces".to_string(), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::from([( - "example".to_string(), - BTreeMap::from([("alpha".to_string(), "one\ntwo".to_string())]), - )]), - }); - - let err = result - .err() - .expect("header-unsafe configured tracestate should be rejected"); - assert!(err.to_string().contains("configured tracestate value")); -} - -#[test] -fn otlp_http_exporter_sends_traces_to_collector() --> std::result::Result<(), Box> { - let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - listener.set_nonblocking(true).expect("set_nonblocking"); - - let (tx, rx) = mpsc::channel::>(); - let server = thread::spawn(move || { - let mut captured = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(3); - - while Instant::now() < deadline { - match listener.accept() { - Ok((mut stream, _)) => { - let result = read_http_request(&mut stream); - let _ = write_http_response(&mut stream, "202 Accepted"); - if let Ok((path, headers, body)) = result { - captured.push(CapturedRequest { - path, - content_type: headers.get("content-type").cloned(), - body, - }); - } - } - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - - let _ = tx.send(captured); - }); - - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/traces"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::from([( - "test.configured_attribute".to_string(), - "configured-value".to_string(), - )]), - tracestate: BTreeMap::from([( - "example".to_string(), - BTreeMap::from([ - ("alpha".to_string(), "one".to_string()), - ("beta".to_string(), "two".to_string()), - ]), - )]), - })? - .expect("otel provider"); - let tracing_layer = otel.tracing_layer().expect("tracing layer"); - let subscriber = tracing_subscriber::registry().with(tracing_layer); - - let propagated_trace = tracing::subscriber::with_default(subscriber, || { - let span = tracing::info_span!( - "trace-loopback", - otel.name = "trace-loopback", - otel.kind = "server", - rpc.system = "jsonrpc", - rpc.method = "trace-loopback", - ); - assert!(set_parent_from_w3c_trace_context( - &span, - &W3cTraceContext { - traceparent: Some( - "00-00000000000000000000000000000001-0000000000000002-01".to_string(), - ), - tracestate: Some("example=alpha:zero;keep:yes,other=value".to_string()), - }, - )); - let _guard = span.enter(); - let propagated_trace = - current_span_w3c_trace_context().expect("current span should have trace context"); - tracing::event!( - target: "codex_otel.trace_safe", - tracing::Level::INFO, - event.name = "codex.test.trace_event", - "test OTEL trace event" - ); - tracing::info!("trace loopback event"); - propagated_trace - }); - otel.shutdown(); - - assert_eq!( - propagated_trace.tracestate.as_deref(), - Some("example=alpha:one;keep:yes;beta:two,other=value") - ); - - server.join().expect("server join"); - let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); - - let request = captured - .iter() - .find(|req| req.path == "/v1/traces") - .expect("/v1/traces request should be captured"); - let content_type = request - .content_type - .as_deref() - .unwrap_or(""); - assert!( - content_type.starts_with("application/json"), - "unexpected content-type: {content_type}" - ); - - let body = String::from_utf8_lossy(&request.body); - assert!( - body.contains("trace-loopback"), - "expected span name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("codex-cli"), - "expected service name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("test.configured_attribute") && body.contains("configured-value"), - "expected configured span attribute not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("codex.test.trace_event"), - "expected trace event not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn otlp_http_exporter_sends_traces_to_collector_with_bounded_shutdown_in_tokio_runtime() --> std::result::Result<(), Box> { - let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - listener.set_nonblocking(true).expect("set_nonblocking"); - - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/traces"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - })? - .expect("otel provider"); - let (tx, rx) = mpsc::channel::>(); - let (stop_tx, stop_rx) = mpsc::channel(); - let server = thread::spawn(move || { - let mut captured = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(3); - - while Instant::now() < deadline { - match stop_rx.try_recv() { - Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break, - Err(mpsc::TryRecvError::Empty) => {} - } - - match listener.accept() { - Ok((mut stream, _)) => { - let result = read_http_request(&mut stream); - let _ = write_http_response(&mut stream, "202 Accepted"); - if let Ok((path, headers, body)) = result { - captured.push(CapturedRequest { - path, - content_type: headers.get("content-type").cloned(), - body, - }); - } - } - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - - let _ = tx.send(captured); - }); - let tracing_layer = otel.tracing_layer().expect("tracing layer"); - let subscriber = tracing_subscriber::registry().with(tracing_layer); - - tracing::subscriber::with_default(subscriber, || { - let span = tracing::info_span!( - "trace-loopback-tokio", - otel.name = "trace-loopback-tokio", - otel.kind = "server", - rpc.system = "jsonrpc", - rpc.method = "trace-loopback-tokio", - ); - let _guard = span.enter(); - tracing::info!("trace loopback event from tokio runtime"); - }); - let shutdown_result = tokio::task::block_in_place(|| { - tokio::runtime::Handle::current() - .block_on(otel.shutdown_with_timeout(Duration::from_secs(/*secs*/ 2))) - }); - - let _ = stop_tx.send(()); - server.join().expect("server join"); - shutdown_result?; - let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); - - let request = captured - .iter() - .find(|req| req.path == "/v1/traces") - .expect("/v1/traces request should be captured"); - let content_type = request - .content_type - .as_deref() - .unwrap_or(""); - assert!( - content_type.starts_with("application/json"), - "unexpected content-type: {content_type}" - ); - - let body = String::from_utf8_lossy(&request.body); - assert!( - body.contains("trace-loopback-tokio"), - "expected span name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("codex-cli"), - "expected service name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - - Ok(()) -} - -#[test] -fn otlp_http_exporter_times_out_when_collector_stalls_during_bounded_shutdown() { - let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - let (request_started_tx, request_started_rx) = mpsc::channel(); - let (release_tx, release_rx) = mpsc::channel(); - - let server = thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept trace request"); - let (path, _, _) = read_http_request(&mut stream).expect("read trace request"); - request_started_tx.send(path).expect("request started"); - release_rx - .recv_timeout(Duration::from_secs(/*secs*/ 2)) - .expect("collector released"); - write_http_response(&mut stream, "202 Accepted").expect("write trace response"); - }); - - let runtime = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .expect("build tokio runtime"); - let (result, elapsed) = runtime.block_on(async move { - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/traces"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .expect("build otel provider") - .expect("otel provider"); - let tracing_layer = otel.tracing_layer().expect("tracing layer"); - let subscriber = tracing_subscriber::registry().with(tracing_layer); - - tracing::subscriber::with_default(subscriber, || { - let span = tracing::info_span!("trace-loopback-stalled"); - let _guard = span.enter(); - tracing::info!("trace loopback event for stalled collector"); - }); - - let started = Instant::now(); - let result = otel - .shutdown_with_timeout(Duration::from_millis(/*millis*/ 50)) - .await; - (result, started.elapsed()) - }); - - let path = request_started_rx - .recv_timeout(Duration::from_secs(/*secs*/ 1)) - .expect("trace request reached collector"); - release_tx.send(()).expect("release collector"); - server.join().expect("server join"); - runtime.shutdown_timeout(Duration::from_secs(/*secs*/ 1)); - - assert_eq!(path, "/v1/traces"); - assert_eq!( - result.as_ref().map_err(std::io::Error::kind), - Err(std::io::ErrorKind::TimedOut) - ); - assert!( - elapsed < Duration::from_secs(/*secs*/ 1), - "bounded shutdown blocked for {elapsed:?}" - ); -} - -#[test] -fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime() --> std::result::Result<(), Box> { - let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("local_addr"); - listener.set_nonblocking(true).expect("set_nonblocking"); - - let (tx, rx) = mpsc::channel::>(); - let server = thread::spawn(move || { - let mut captured = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(3); - - while Instant::now() < deadline { - match listener.accept() { - Ok((mut stream, _)) => { - let result = read_http_request(&mut stream); - let _ = write_http_response(&mut stream, "202 Accepted"); - if let Ok((path, headers, body)) = result { - captured.push(CapturedRequest { - path, - content_type: headers.get("content-type").cloned(), - body, - }); - } - } - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - - let _ = tx.send(captured); - }); - - let (runtime_result_tx, runtime_result_rx) = mpsc::channel::>(); - let runtime_thread = thread::spawn(move || { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("current-thread runtime"); - - let result = runtime.block_on(async move { - let otel = OtelProvider::try_new(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/traces"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .map_err(|err| err.to_string())? - .expect("otel provider"); - let tracing_layer = otel.tracing_layer().expect("tracing layer"); - let subscriber = tracing_subscriber::registry().with(tracing_layer); - - tracing::subscriber::with_default(subscriber, || { - let span = tracing::info_span!( - "trace-loopback-current-thread", - otel.name = "trace-loopback-current-thread", - otel.kind = "server", - rpc.system = "jsonrpc", - rpc.method = "trace-loopback-current-thread", - ); - let _guard = span.enter(); - tracing::info!("trace loopback event from current-thread tokio runtime"); - }); - otel.shutdown(); - Ok::<(), String>(()) - }); - let _ = runtime_result_tx.send(result); - }); - - runtime_result_rx - .recv_timeout(Duration::from_secs(5)) - .expect("current-thread runtime should complete") - .map_err(std::io::Error::other)?; - runtime_thread.join().expect("runtime thread"); - - server.join().expect("server join"); - let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); - - let request = captured - .iter() - .find(|req| req.path == "/v1/traces") - .expect("/v1/traces request should be captured"); - let content_type = request - .content_type - .as_deref() - .unwrap_or(""); - assert!( - content_type.starts_with("application/json"), - "unexpected content-type: {content_type}" - ); - - let body = String::from_utf8_lossy(&request.body); - assert!( - body.contains("trace-loopback-current-thread"), - "expected span name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - assert!( - body.contains("codex-cli"), - "expected service name not found; body prefix: {}", - &body.chars().take(2000).collect::() - ); - - Ok(()) -} diff --git a/codex-rs/protocol/src/error.rs b/codex-rs/protocol/src/error.rs index bc47eedb..d3137a00 100644 --- a/codex-rs/protocol/src/error.rs +++ b/codex-rs/protocol/src/error.rs @@ -100,7 +100,7 @@ pub struct ResponseIncompleteError { #[strum_discriminants(derive(serde::Serialize, strum_macros::IntoStaticStr))] #[strum_discriminants(strum(serialize_all = "snake_case"))] #[strum_discriminants(serde(rename_all = "snake_case"))] -#[strum_discriminants(doc = "The payload-free semantic category used for analytics.")] +#[strum_discriminants(doc = "The payload-free semantic category of the error.")] pub enum CodexErrorDetails { #[error("turn aborted. Something went wrong? Hit `/feedback` to report the issue.")] TurnAborted, diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 03f5f187..9d3ee9d8 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -271,7 +271,7 @@ pub fn is_safe_plugin_relative_path(path: &str) -> bool { }) } -/// Immutable model labels carried within command lifecycle events for analytics. +/// Immutable model labels carried within command lifecycle events. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ModelInvocationContext { pub model_slug: String, @@ -280,7 +280,7 @@ pub struct ModelInvocationContext { #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)] pub struct CommandExecutionItem { - /// Observed process backend for live analytics; None means unknown or not launched. + /// Observed process backend; None means unknown or not launched. #[serde(skip)] #[schemars(skip)] #[ts(skip)] diff --git a/codex-rs/protocol/src/legacy_events.rs b/codex-rs/protocol/src/legacy_events.rs index 3dc17759..169d66c2 100644 --- a/codex-rs/protocol/src/legacy_events.rs +++ b/codex-rs/protocol/src/legacy_events.rs @@ -287,7 +287,7 @@ 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 { - // V2 records these tool items privately for analytics, not legacy UI events. + // V2 records these tool items privately, not as legacy UI events. CollabAgentTool::SendMessage | CollabAgentTool::FollowupTask | CollabAgentTool::InterruptAgent diff --git a/codex-rs/protocol/src/models/executed_tool_calls.rs b/codex-rs/protocol/src/models/executed_tool_calls.rs index 95151c26..211d5c9a 100644 --- a/codex-rs/protocol/src/models/executed_tool_calls.rs +++ b/codex-rs/protocol/src/models/executed_tool_calls.rs @@ -409,7 +409,7 @@ pub struct ExecutedToolCall { pub name: String, #[ts(type = "unknown")] arguments: ExecutedToolCallArguments, - /// Host-generated analytics only: ignore input JSON rather than accepting caller-supplied + /// Host-generated only: ignore input JSON rather than accepting caller-supplied /// evidence, and keep this out of public schemas and generated clients. #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")] #[schemars(skip)] diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index e11fb4bd..cc88f17f 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -3502,7 +3502,7 @@ pub struct SessionMeta { pub cli_version: String, #[serde(default)] pub source: SessionSource, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_source: Option, /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. @@ -4347,7 +4347,7 @@ pub struct SessionConfiguredEvent { pub forked_from_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub parent_thread_id: Option, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_source: Option, diff --git a/codex-rs/rollout/src/compression.rs b/codex-rs/rollout/src/compression.rs index 603fe338..1334b8c7 100644 --- a/codex-rs/rollout/src/compression.rs +++ b/codex-rs/rollout/src/compression.rs @@ -27,7 +27,7 @@ const COMPRESSED_SUFFIX: &str = ".zst"; const MAX_NOT_FOUND_RETRIES: usize = 3; const OPEN_ROLLOUT_LINE_READER_RETRY_DELAY: Duration = Duration::from_millis(50); -/// The entry point that requested a compression pass, not a Statsig cohort. +/// The entry point that requested a compression pass. #[derive(Clone, Copy, Debug)] pub enum RolloutCompressionTrigger { Startup, diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index ef03ad85..464c6e73 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -67,8 +67,6 @@ pub fn default_filter() -> Targets { // Avoid constructing backend diagnostics when no other layer needs them. .with_targets(SQLX_LOG_TARGETS.map(|target| (format!("{target}::"), LevelFilter::OFF))) .with_target("codex_rmcp_client", LevelFilter::INFO) - .with_target("opentelemetry-otlp", LevelFilter::OFF) - .with_target("opentelemetry-http", LevelFilter::OFF) .with_target("tonic::transport", LevelFilter::WARN) .with_target("tower::buffer", LevelFilter::WARN) .with_target("codex_otel.log_only", LevelFilter::OFF) @@ -299,10 +297,7 @@ where // `tracing-log` checks filters with the original log target before // dispatching an event whose tracing target is `log`, so the outer // target filter cannot reliably reject these bridged events. - // OTLP exporters and their HTTP adapters log every export. Recording - // those events would create another SQLite-write metric and keep the - // exporter active indefinitely, including when its queue is full. - if matches!(target, "log" | "opentelemetry-otlp" | "opentelemetry-http") { + if target == "log" { return; } @@ -319,7 +314,7 @@ where let mut visitor = MessageVisitor::default(); event.record(&mut visitor); - // OTLP gRPC connections run on their own task, so an unsolicited PING + // gRPC connections run on their own task, so an unsolicited PING // ACK can emit this benign warning after every otherwise successful // export. Drop only that warning before queue/drop accounting; other // HTTP/2 diagnostics must remain available to unrelated clients. diff --git a/codex-rs/state/src/log_db_filter_tests.rs b/codex-rs/state/src/log_db_filter_tests.rs index 3f04e104..eca8f49a 100644 --- a/codex-rs/state/src/log_db_filter_tests.rs +++ b/codex-rs/state/src/log_db_filter_tests.rs @@ -35,8 +35,6 @@ async fn sqlite_sink_filters_noisy_targets_without_dropping_useful_diagnostics() tracing::warn!(target: "sqlx::pool::acquire", "dropped-slow-acquire-warning"); tracing::warn!(target: "sqlx::other", "dropped-sqlx-warning"); tracing::info!(target: "sqlx_application", "retained-unrelated-target"); - tracing::debug!(target: "opentelemetry-otlp", "dropped-otlp-export"); - tracing::error!(target: "opentelemetry-http", "dropped-http-export"); tracing::trace!(target: "h2::proto::streams", "dropped-http2-trace"); tracing::debug!(target: "tonic::transport::channel", "dropped-grpc-transport-debug"); tracing::debug!(target: "tower::buffer::worker", "dropped-grpc-buffer-debug"); diff --git a/codex-rs/state/src/model/thread_metadata.rs b/codex-rs/state/src/model/thread_metadata.rs index 16edd4c8..c0172db0 100644 --- a/codex-rs/state/src/model/thread_metadata.rs +++ b/codex-rs/state/src/model/thread_metadata.rs @@ -147,7 +147,7 @@ pub struct ThreadMetadata { pub source: String, /// Persisted thread history contract selected when this thread was created. pub history_mode: ThreadHistoryMode, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub thread_source: Option, /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. pub agent_nickname: Option, @@ -222,7 +222,7 @@ pub struct ThreadMetadataBuilder { pub source: SessionSource, /// Persisted thread history contract selected when this thread was created. pub history_mode: ThreadHistoryMode, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub thread_source: Option, /// Optional random unique nickname assigned to the session. pub agent_nickname: Option, diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index f7a93275..1e22da1a 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -160,7 +160,6 @@ async fn run_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { environment_manager, Arc::new(extensions.build()), user_instructions_provider, - /*analytics_events_client*/ None, passthrough_image_store(), Arc::clone(&thread_store), local_agent_graph_store_from_state_db(state_db.as_ref()), @@ -411,7 +410,6 @@ async fn new_config( notices: Notice::default(), check_for_update_on_startup: false, disable_paste_burst: false, - analytics_enabled: Some(false), feedback_enabled: false, tool_suggest: ToolSuggestConfig::default(), otel: OtelConfig::default(), diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index 8effae5d..82945365 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -93,9 +93,9 @@ pub struct CreateThreadParams { pub parent_thread_id: Option, /// Runtime source for the thread. pub source: SessionSource, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub thread_source: Option, - /// Effective originator used for this thread's Responses requests and analytics events. + /// Effective originator used for this thread's Responses requests. pub originator: String, /// Base instructions persisted in session metadata. pub base_instructions: BaseInstructions, @@ -698,7 +698,7 @@ pub struct StoredThread { pub source: SessionSource, /// Persisted thread history contract selected when this thread was created. pub history_mode: ThreadHistoryMode, - /// Optional analytics source classification for this thread. + /// Optional source classification for this thread. pub thread_source: Option, /// Optional random nickname for thread-spawn sub-agents. pub agent_nickname: Option, @@ -812,7 +812,7 @@ pub struct ThreadMetadataPatch { pub creator_account_id: Option, /// Recorded creation-time originator. Only fills a missing stored value. pub originator: Option, - /// Optional analytics source classification. + /// Optional source classification. #[serde( default, skip_serializing_if = "Option::is_none", diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 9e3e7567..e3515bb1 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -27,7 +27,6 @@ use crate::bottom_pane::AppLinkViewParams; use crate::bottom_pane::ApplyPatchApprovalRequest; use crate::bottom_pane::ApprovalRequest; use crate::bottom_pane::ExecApprovalRequest; -use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::McpElicitationApprovalRequest; use crate::bottom_pane::McpServerElicitationFormRequest; use crate::bottom_pane::PermissionsApprovalRequest; @@ -101,7 +100,7 @@ use codex_app_server_protocol::ConfigBatchWriteParams; use codex_app_server_protocol::ConfigReadResponse; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ConfigWriteResponse; -use codex_app_server_protocol::FeedbackUploadParams; +use codex_app_server_protocol::FeedbackReportParams; use codex_app_server_protocol::HooksListEntry; use codex_app_server_protocol::ListMcpServerStatusParams; use codex_app_server_protocol::ListMcpServerStatusResponse; @@ -228,7 +227,7 @@ mod empty_state_policy; mod event_dispatch; mod exit_summary; mod experimental_features; -mod feedback_upload; +mod feedback_save; mod file_change_approvals; mod history_pagination; mod history_ui; @@ -548,7 +547,6 @@ pub(crate) struct App { config_notification_test_pending: Option, model_catalog: Arc, pub(crate) session_telemetry: SessionTelemetry, - terminal_size_tags: crate::terminal_size_telemetry::LaunchTags, pub(crate) app_event_tx: AppEventSender, pub(crate) chat_widget: ChatWidget, workspace_command_runner: Option, @@ -584,7 +582,7 @@ pub(crate) struct App { #[cfg_attr(not(test), allow(dead_code))] last_rendered_history_tail: Option, - // Alternate-screen overlays: transcript, diff, and analytics. + // Alternate-screen overlays: transcript and diff. pub(crate) overlay: Option, pub(crate) deferred_history_lines: Vec, has_emitted_history_lines: bool, @@ -614,7 +612,6 @@ pub(crate) struct App { /// This keeps scrollback consistent with the retained transcript after backtracking. pub(crate) backtrack_render_pending: bool, pub(crate) feedback: codex_feedback::CodexFeedback, - feedback_audience: FeedbackAudience, environment_manager: Arc, app_server_target: AppServerTarget, reconnect: reconnect::ReconnectState, diff --git a/codex-rs/tui/src/app/backend_selection.rs b/codex-rs/tui/src/app/backend_selection.rs index 4e72b34e..084d9988 100644 --- a/codex-rs/tui/src/app/backend_selection.rs +++ b/codex-rs/tui/src/app/backend_selection.rs @@ -402,7 +402,6 @@ impl App { .for_backend(destination.backend_id(), &mut self.provider_writes) .with_collaboration_modes(bootstrap.collaboration_modes), ); - self.feedback_audience = bootstrap.feedback_audience; self.chat_widget.requires_openai_auth = bootstrap.requires_openai_auth; self.chat_widget.invalidate_security_setup(); self.chat_widget.update_account_state( diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 1b39ab9f..72ab6870 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -1,10 +1,10 @@ //! Background app-server requests launched by the TUI app. //! //! This module owns fire-and-forget fetch/write helpers for MCP inventory, skills, plugins, rate -//! limits, add-credit nudges, and feedback uploads. Results are routed back through `AppEvent` so +//! limits, add-credit nudges, and local feedback saves. Results are routed back through `AppEvent` so //! the main event loop remains single-threaded. -use super::feedback_upload::fetch_feedback_upload; +use super::feedback_save::save_feedback_locally; use super::plugin_mentions::fetch_plugin_mentions; use super::*; use crate::app_event::ConnectorsSnapshot; @@ -482,7 +482,7 @@ impl App { } else { None }; - let params = build_feedback_upload_params( + let params = build_feedback_report_params( origin_thread_id, rollout_path, category, @@ -493,9 +493,12 @@ impl App { let codex_home = app_server.codex_home_path(&self.config.codex_home); let feedback = self.feedback.clone(); tokio::spawn(async move { - let result = fetch_feedback_upload(request_handle, codex_home, params, feedback) + let result = save_feedback_locally(request_handle, codex_home, params, feedback) .await - .map(|response| response.thread_id) + .map(|response| crate::app_event::SavedFeedback { + thread_id: response.thread_id, + saved_path: response.saved_path.render_for_ui(), + }) .map_err(|err| err.to_string()); app_event_tx.send(AppEvent::FeedbackSubmitted { origin_thread_id, @@ -508,19 +511,18 @@ impl App { pub(super) fn handle_feedback_thread_event(&mut self, event: FeedbackThreadEvent) { match event.result { - Ok(thread_id) => { + Ok(saved) => { self.chat_widget .add_to_history(crate::bottom_pane::feedback_success_cell( - event.category, event.include_logs, - &thread_id, - event.feedback_audience, + &saved.saved_path, + &saved.thread_id, )) } Err(err) => self .chat_widget .add_to_history(history_cell::new_error_event(format!( - "Failed to upload feedback: {err}" + "Failed to save feedback: {err}" ))), } } @@ -564,12 +566,11 @@ impl App { origin_thread_id: Option, category: FeedbackCategory, include_logs: bool, - result: Result, + result: Result, ) { let event = FeedbackThreadEvent { category, include_logs, - feedback_audience: self.feedback_audience, result, }; if let Some(thread_id) = origin_thread_id { @@ -1037,21 +1038,21 @@ pub(super) async fn write_hook_enabled( .wrap_err("config/batchWrite failed while updating hook enablement in TUI") } -pub(super) fn build_feedback_upload_params( +pub(super) fn build_feedback_report_params( origin_thread_id: Option, rollout_path: Option, category: FeedbackCategory, reason: Option, turn_id: Option, include_logs: bool, -) -> FeedbackUploadParams { +) -> FeedbackReportParams { let extra_log_files = if include_logs { rollout_path.map(|rollout_path| vec![rollout_path]) } else { None }; let tags = turn_id.map(|turn_id| BTreeMap::from([(String::from("turn_id"), turn_id)])); - FeedbackUploadParams { + FeedbackReportParams { classification: crate::bottom_pane::feedback_classification(category).to_string(), reason, thread_id: origin_thread_id.map(|thread_id| thread_id.to_string()), @@ -1345,11 +1346,11 @@ mod tests { } #[test] - fn build_feedback_upload_params_includes_thread_id_and_rollout_path() { + fn build_feedback_report_params_includes_thread_id_and_rollout_path() { let thread_id = ThreadId::new(); let rollout_path = PathBuf::from("/tmp/rollout.jsonl"); - let params = build_feedback_upload_params( + let params = build_feedback_report_params( Some(thread_id), Some(rollout_path.clone()), FeedbackCategory::SafetyCheck, @@ -1374,8 +1375,8 @@ mod tests { } #[test] - fn build_feedback_upload_params_omits_rollout_path_without_logs() { - let params = build_feedback_upload_params( + fn build_feedback_report_params_omits_rollout_path_without_logs() { + let params = build_feedback_report_params( /*origin_thread_id*/ None, Some(PathBuf::from("/tmp/rollout.jsonl")), FeedbackCategory::GoodResult, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index f94cd8a1..e1c946ce 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -2403,7 +2403,7 @@ impl App { category, include_logs, } => { - self.chat_widget.open_feedback_note(category, include_logs, self.feedback_audience); + self.chat_widget.open_feedback_note(category, include_logs); } AppEvent::OpenFeedbackConsent { category } => { self.chat_widget.open_feedback_consent(category); diff --git a/codex-rs/tui/src/app/feedback_upload.rs b/codex-rs/tui/src/app/feedback_save.rs similarity index 56% rename from codex-rs/tui/src/app/feedback_upload.rs rename to codex-rs/tui/src/app/feedback_save.rs index 13ba9b9d..193dcdd1 100644 --- a/codex-rs/tui/src/app/feedback_upload.rs +++ b/codex-rs/tui/src/app/feedback_save.rs @@ -1,14 +1,17 @@ -//! Stage bounded TUI diagnostics on the app-server host for a single feedback upload. -//! Log consent gates all staging; cleanup runs after staging or upload failures too. +//! Save a feedback report as a local ZIP archive on the app-server host. +//! Feedback is never uploaded. Log consent gates staging of the TUI client logs; +//! cleanup runs after staging or save failures too. use crate::app_server_session::fs::AppServerFileSystem; use codex_app_server_client::AppServerPath; use codex_app_server_client::AppServerRequestHandle; use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::FeedbackUploadParams; -use codex_app_server_protocol::FeedbackUploadResponse; +use codex_app_server_protocol::FeedbackReportParams; +use codex_app_server_protocol::FeedbackSaveParams; +use codex_app_server_protocol::FeedbackSaveResponse; use codex_app_server_protocol::RequestId; use codex_feedback::CodexFeedback; +use codex_utils_path_uri::LegacyAppPathString; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; use color_eyre::eyre::eyre; @@ -18,23 +21,23 @@ use uuid::Uuid; // Base64 adds only a third to this size, keeping fs/writeFile below the 16 MiB frame limit. const MAX_CLIENT_LOG_SIZE: usize = 1024 * 1024; -pub(super) async fn fetch_feedback_upload( +pub(super) async fn save_feedback_locally( request_handle: AppServerRequestHandle, codex_home: Option, - mut params: FeedbackUploadParams, + mut params: FeedbackReportParams, feedback: CodexFeedback, -) -> Result { +) -> Result { let fs = AppServerFileSystem { request_handle }; - let staging_dir = codex_home.filter(|_| params.include_logs).map(|home| { - home.join("tmp") + let codex_home = codex_home + .ok_or_else(|| eyre!("App server did not report $CODEX_HOME; cannot save feedback"))?; + let staging_dir = params.include_logs.then(|| { + codex_home + .join("tmp") .join(format!("tui-feedback-{}", Uuid::new_v4())) }); - if params.include_logs { + if let Some(directory) = staging_dir.as_ref() { let staged = async { - let directory = staging_dir.as_ref().ok_or_else(|| { - eyre!("App server did not report $CODEX_HOME; cannot stage feedback logs") - })?; - // These RPCs use the app-server's local filesystem, where feedback/upload + // These RPCs use the app-server's local filesystem, where feedback/save // reads extraLogFiles, independently of the thread's executor environment. fs.fs_create_directory_all_path(directory).await?; let path = directory.join("client-logs.txt"); @@ -60,12 +63,27 @@ pub(super) async fn fetch_feedback_upload( } } } - let request_id = RequestId::String(format!("feedback-upload-{}", Uuid::new_v4())); - let result = fs - .request_handle - .request_typed(ClientRequest::FeedbackUpload { request_id, params }) - .await - .wrap_err("feedback/upload failed in TUI"); + let result = async { + let feedback_dir = codex_home.join("feedback"); + fs.fs_create_directory_all_path(&feedback_dir).await?; + let save_path = feedback_dir.join(format!( + "feedback-{}-{}.zip", + chrono::Local::now().format("%Y%m%d-%H%M%S"), + Uuid::new_v4().simple() + )); + let request_id = RequestId::String(format!("feedback-save-{}", Uuid::new_v4())); + fs.request_handle + .request_typed(ClientRequest::FeedbackSave { + request_id, + params: FeedbackSaveParams { + feedback: params, + save_path: LegacyAppPathString::from_string(save_path.as_str()), + }, + }) + .await + .wrap_err("feedback/save failed in TUI") + } + .await; if let Some(directory) = staging_dir && let Err(err) = fs.fs_remove_path(&directory).await diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index cc801cb2..5b8a9d95 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -596,7 +596,6 @@ impl App { self.chat_widget.security_setup_request_id, ); } - self.feedback_audience = bootstrap.feedback_audience; if displayed.is_some_and(|id| !self.thread_unavailable(id)) { self.chat_widget.maybe_send_next_queued_input(); } diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 5f443088..331d339d 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -1384,7 +1384,6 @@ impl App { ); if let Some(account) = account { self.account_email_request_id = None; - self.feedback_audience = account.feedback_audience(); init.has_chatgpt_account = account.has_chatgpt_account(); init.has_codex_backend_auth = init.has_chatgpt_account; init.requires_openai_auth = account.requires_openai_auth; diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 3f17cb20..d385b053 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -535,7 +535,6 @@ impl App { .for_backend(app_server.backend_id(), &mut provider_writes) .with_collaboration_modes(bootstrap.collaboration_modes), ); - let feedback_audience = bootstrap.feedback_audience; let auth_mode = bootstrap.auth_mode; let has_chatgpt_account = bootstrap.has_chatgpt_account; let has_codex_backend_auth = matches!(auth_mode, Some(TelemetryAuthMode::Chatgpt)); @@ -991,7 +990,6 @@ See the Codex keymap documentation for supported actions and examples." config_notification_test_pending: None, model_catalog, session_telemetry: session_telemetry.clone(), - terminal_size_tags: tui.terminal_size_tags.clone(), app_event_tx, chat_widget, workspace_command_runner: Some(workspace_command_runner), @@ -1034,7 +1032,6 @@ See the Codex keymap documentation for supported actions and examples." backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: feedback.clone(), - feedback_audience, environment_manager, app_server_target, pending_right_click_paste: None, @@ -1266,9 +1263,6 @@ See the Codex keymap documentation for supported actions and examples." ); } - let mut last_screen_size = tui.terminal.last_known_screen_size; - let mut settled_size_tags = crate::terminal_size_telemetry::tags(last_screen_size); - let mut pending_resize: Option<(ratatui::layout::Size, Instant)> = None; let mut reconnect = None; let mut waiting_for_initial_session_configured = wait_for_initial_session_configured; let mut waiting_for_initial_session_header = true; @@ -1453,19 +1447,6 @@ See the Codex keymap documentation for supported actions and examples." && has_pending_app_events || (!waiting_for_initial_session_configured && app.has_queued_startup_protected_request()); - // The screen cache is physical geometry, not the inline viewport. This also - // notices the final size after returning from a standalone nested screen. - let size = tui.terminal.last_known_screen_size; - if !crate::terminal_size_telemetry::enabled(&app.config) - || app.terminal_size_tags.is_empty() - { - pending_resize = None; - settled_size_tags = crate::terminal_size_telemetry::tags(size); - } else if size != last_screen_size { - pending_resize = - Some((size, Instant::now() + Duration::from_secs(/*secs*/ 15))); - } - last_screen_size = size; let control = select! { result = async { match app.daemon_restart.as_mut() { @@ -1665,28 +1646,6 @@ See the Codex keymap documentation for supported actions and examples." } AppRunControl::Continue } - () = async { - match pending_resize { - Some((_, deadline)) => tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await, - None => std::future::pending().await, - } - } => { - if let Some((expected, _)) = pending_resize.take() - && crate::terminal_size_telemetry::enabled(&app.config) - { - let actual = crate::terminal_size_telemetry::read_size(); - if actual != expected { - pending_resize = Some((actual, Instant::now() + Duration::from_secs(/*secs*/ 15))); - } else { - let tags = crate::terminal_size_telemetry::tags(actual); - if tags != settled_size_tags { - crate::terminal_size_telemetry::record(&app.terminal_size_tags, &app.config, "resize", actual); - } - settled_size_tags = tags; - } - } - AppRunControl::Continue - } () = async { match app.chat_widget.terminal_title_next_refresh { Some(deadline) => { diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 2d6ed293..97f8b182 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -49,7 +49,6 @@ pub(crate) async fn make_test_app() -> Box { config_notification_test_pending: None, model_catalog: chat_widget.model_catalog(), session_telemetry, - terminal_size_tags: Vec::new(), app_event_tx, chat_widget, workspace_command_runner: None, @@ -95,7 +94,6 @@ pub(crate) async fn make_test_app() -> Box { backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: codex_feedback::CodexFeedback::new(), - feedback_audience: FeedbackAudience::External, environment_manager: Arc::new(EnvironmentManager::default_for_tests()), app_server_target: crate::AppServerTarget::Embedded, pending_right_click_paste: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index a263eff8..4ec3f581 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -1,8 +1,5 @@ //! App-level orchestration tests for the TUI. -#[path = "tests/terminal_size_telemetry_tests.rs"] -mod terminal_size_telemetry_tests; - #[path = "tests/copy_mode_tests.rs"] mod copy_mode_tests; #[path = "tests/mcp_login_tests.rs"] @@ -4947,7 +4944,10 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() origin_thread_id: Some(side_thread_id), category: FeedbackCategory::Bug, include_logs: false, - result: Ok("uploaded-thread".to_string()), + result: Ok(crate::app_event::SavedFeedback { + thread_id: "saved-thread".to_string(), + saved_path: "/tmp/feedback.zip".to_string(), + }), }); app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) .await?; @@ -4962,7 +4962,7 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() ); assert!(app.transcript_cells.iter().any(|cell| { lines_to_single_string(&cell.display_lines(/*width*/ 120)) - .contains("Feedback recorded (no logs).") + .contains("Feedback saved locally (no logs).") })); // A completion restored with the parent draft must not receive the chooser's Enter. @@ -8610,7 +8610,6 @@ async fn make_test_app() -> Box { config_notification_test_pending: None, model_catalog: chat_widget.model_catalog(), session_telemetry, - terminal_size_tags: Vec::new(), app_event_tx, chat_widget, workspace_command_runner: None, @@ -8655,7 +8654,6 @@ async fn make_test_app() -> Box { backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: codex_feedback::CodexFeedback::new(), - feedback_audience: FeedbackAudience::External, environment_manager: Arc::new(EnvironmentManager::default_for_tests()), app_server_target: crate::AppServerTarget::Embedded, reconnect: Default::default(), @@ -8744,7 +8742,6 @@ pub(super) async fn make_test_app_with_channels() -> ( config_notification_test_pending: None, model_catalog: chat_widget.model_catalog(), session_telemetry, - terminal_size_tags: Vec::new(), app_event_tx, chat_widget, workspace_command_runner: None, @@ -8789,7 +8786,6 @@ pub(super) async fn make_test_app_with_channels() -> ( backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: codex_feedback::CodexFeedback::new(), - feedback_audience: FeedbackAudience::External, environment_manager: Arc::new(EnvironmentManager::default_for_tests()), app_server_target: crate::AppServerTarget::Embedded, reconnect: Default::default(), @@ -9981,7 +9977,7 @@ async fn feedback_submission_stages_logs_cleans_up_and_emits_error_history_cell( if staging_fails { std::fs::write(&tmp, "not a directory")?; } - let mut params = background_requests::build_feedback_upload_params( + let mut params = background_requests::build_feedback_report_params( /*origin_thread_id*/ None, Some(PathBuf::from("existing-rollout.jsonl")), FeedbackCategory::Bug, @@ -9989,9 +9985,9 @@ async fn feedback_submission_stages_logs_cleans_up_and_emits_error_history_cell( /*turn_id*/ None, include_logs, ); - // Reject before network upload, after the client has staged its diagnostics. + // Reject before saving, after the client has staged its diagnostics. params.thread_id = Some("invalid-thread-id".into()); - let error = feedback_upload::fetch_feedback_upload( + let error = feedback_save::save_feedback_locally( server.request_handle(), Some(AppServerPath::from_app_server( home.path().display().to_string(), @@ -10003,11 +9999,18 @@ async fn feedback_submission_stages_logs_cleans_up_and_emits_error_history_cell( .unwrap_err(); assert!(format!("{error:#}").contains("invalid thread id")); let recorded = std::mem::take(&mut *requests.lock().unwrap()); - let upload = recorded + let save = recorded .iter() - .find(|r| r.method == "feedback/upload") + .find(|r| r.method == "feedback/save") .unwrap(); - let upload: FeedbackUploadParams = serde_json::from_value(upload.params.clone().unwrap())?; + let save: codex_app_server_protocol::FeedbackSaveParams = + serde_json::from_value(save.params.clone().unwrap())?; + assert!( + save.save_path + .as_str() + .starts_with(&home.path().join("feedback").display().to_string()) + ); + let upload = save.feedback; if include_logs && !staging_fails { let write = recorded .iter() @@ -10038,7 +10041,7 @@ async fn feedback_submission_stages_logs_cleans_up_and_emits_error_history_cell( .contains("TUI client logs were omitted") ); } else { - assert_eq!(recorded.len(), 1); + assert!(!recorded.iter().any(|r| r.method == "fs/writeFile")); assert_eq!(upload.extra_log_files, None); assert!(!tmp.exists()); } @@ -10060,7 +10063,7 @@ async fn feedback_submission_stages_logs_cleans_up_and_emits_error_history_cell( }; assert_eq!( lines_to_single_string(&cell.display_lines(/*width*/ 120)), - "■ Failed to upload feedback: boom" + "■ Failed to save feedback: boom" ); Ok(()) } @@ -10096,7 +10099,10 @@ async fn feedback_submission_for_inactive_thread_replays_into_origin_thread() { Some(origin_thread_id), FeedbackCategory::Bug, /*include_logs*/ true, - Ok("uploaded-thread".to_string()), + Ok(crate::app_event::SavedFeedback { + thread_id: "saved-thread".to_string(), + saved_path: "/tmp/feedback.zip".to_string(), + }), ) .await; @@ -10127,8 +10133,7 @@ async fn feedback_submission_for_inactive_thread_replays_into_origin_thread() { } } assert!(rendered_cells.iter().any(|cell| { - cell.contains("• Feedback uploaded. Please open an issue using the following URL:") - && cell.contains("uploaded-thread") + cell.contains("• Feedback saved locally with logs.") && cell.contains("saved-thread") })); } diff --git a/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs b/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs deleted file mode 100644 index a519eafe..00000000 --- a/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Terminal-size observation eligibility follows the config reloaded for resume. - -use super::*; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn terminal_size_telemetry_respects_reloaded_exporter_and_consent() -> Result<()> { - let (mut app, _app_event_rx, _op_rx) = Box::pin(make_test_app_with_channels()).await; - let cwd = app.config.cwd.to_path_buf(); - let mut enabled = Vec::new(); - for config in [ - "[otel]\nmetrics_exporter = \"statsig\"\n", - "[otel]\nmetrics_exporter = \"none\"\n", - "[otel]\nmetrics_exporter = \"statsig\"\n[analytics]\nenabled = false\n", - "analytics.enabled = false\n[otel.metrics_exporter.otlp-http]\nendpoint = \"http://127.0.0.1:4318/v1/metrics\"\nprotocol = \"json\"\n", - ] { - std::fs::write(app.config.codex_home.join("config.toml"), config)?; - let (config, local_settings) = Box::pin(app.rebuild_config_for_resume_or_fallback( - &cwd, - cwd.clone(), - (&app.config, &app.local_settings), - )) - .await?; - app.config = config; - app.local_settings = local_settings; - enabled.push(crate::terminal_size_telemetry::enabled(&app.config)); - } - // aKode: Statsig never enables terminal-size observations. - assert_eq!(enabled, vec![false, false, false, true]); - Ok(()) -} diff --git a/codex-rs/tui/src/app/tests/transcript_composer.rs b/codex-rs/tui/src/app/tests/transcript_composer.rs index 60d056cf..302f92a4 100644 --- a/codex-rs/tui/src/app/tests/transcript_composer.rs +++ b/codex-rs/tui/src/app/tests/transcript_composer.rs @@ -1,7 +1,6 @@ //! Regression coverage for transcript viewer input, prompt selection, and restoration. //! //! The default-off feature must leave the existing viewer and its draft intact. -//! Analytics also preserves the composer and stays separate from transcript backtracking. use super::*; use crate::pager_overlay::TranscriptHistoryState; diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index fec1b59f..ff299ec1 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -83,8 +83,7 @@ fn hide_private_items_after_voice_handoff( pub(super) struct FeedbackThreadEvent { pub(super) category: FeedbackCategory, pub(super) include_logs: bool, - pub(super) feedback_audience: FeedbackAudience, - pub(super) result: Result, + pub(super) result: Result, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 4eb16ba6..ee93a9e8 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -2001,23 +2001,6 @@ impl App { } pub(super) fn handle_thread_event_now(&mut self, event: ThreadBufferedEvent) { - // Replay has its own handler; suppress repeated notifications for the current turn. - if crate::terminal_size_telemetry::enabled(&self.config) - && !self.terminal_size_tags.is_empty() - && let ThreadBufferedEvent::Notification(notification) = &event - && let ServerNotification::TurnStarted(started) = notification.as_ref() - && self - .active_thread_id - .is_some_and(|id| id.to_string() == started.thread_id) - && self.chat_widget.last_turn_id() != Some(started.turn.id.as_str()) - { - crate::terminal_size_telemetry::record( - &self.terminal_size_tags, - &self.config, - "turn_start", - crate::terminal_size_telemetry::read_size(), - ); - } let needs_refresh = matches!( &event, ThreadBufferedEvent::Notification(notification) diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index bff646cc..adad8c3f 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -228,7 +228,7 @@ impl App { tui.frame_requester().schedule_frame(); } - /// Close the current overlay and restore normal UI, retaining Analytics navigation state. + /// Close the current overlay and restore normal UI. pub(crate) fn close_transcript_overlay(&mut self, tui: &mut tui::Tui) { if tui.is_owned_screen() && self.overlay.is_none() { self.transcript_view.set_presentation( diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 0cc984f6..adfdd0f6 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -313,6 +313,13 @@ impl CapturedSideWork { } } +/// Location of a feedback report saved locally by `/feedback`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SavedFeedback { + pub(crate) thread_id: String, + pub(crate) saved_path: String, +} + #[allow(clippy::large_enum_variant)] #[derive(Debug, IntoStaticStr)] pub(crate) enum AppEvent { @@ -1651,12 +1658,12 @@ pub(crate) enum AppEvent { include_logs: bool, }, - /// Result of a feedback upload request initiated by the TUI. + /// Result of a local feedback save initiated by the TUI. FeedbackSubmitted { origin_thread_id: Option, category: FeedbackCategory, include_logs: bool, - result: Result, + result: Result, }, /// Launch the external editor after a normal draw has completed. diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index fcdbcde2..1ca2ce09 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -43,7 +43,6 @@ pub(crate) use startup_launch::StartupLaunchChoices; use crate::app_event::PermissionProfileSelection; use crate::app_event_sender::AppEventSender; -use crate::bottom_pane::FeedbackAudience; use crate::dynamic_tools_mcp::DynamicToolMcpServer; use crate::dynamic_tools_mcp::ThreadToolTransport; use crate::legacy_core::config::Config; @@ -356,7 +355,6 @@ pub(crate) struct AppServerBootstrap { pub(crate) requires_openai_auth: bool, /// Cloud supplies its model when it starts or resumes a thread. pub(crate) default_model: Option, - pub(crate) feedback_audience: FeedbackAudience, pub(crate) has_chatgpt_account: bool, pub(crate) available_models: Vec, pub(crate) collaboration_modes: Vec, @@ -984,7 +982,6 @@ impl AppServerSession { duration: started_at.elapsed(), account_email: account.email().map(str::to_owned), auth_mode: account.auth_mode(), - feedback_audience: account.feedback_audience(), has_chatgpt_account: account.has_chatgpt_account(), status_account_display: account.display, plan_type: account.plan, @@ -3187,14 +3184,12 @@ mod tests { bootstrap.account_email.as_deref(), bootstrap.auth_mode, bootstrap.plan_type, - bootstrap.feedback_audience, bootstrap.has_chatgpt_account, ), ( Some("teammate@openai.com"), Some(TelemetryAuthMode::Chatgpt), Some(codex_protocol::account::PlanType::Plus), - FeedbackAudience::OpenAiEmployee, true, ) ); diff --git a/codex-rs/tui/src/app_server_session/account.rs b/codex-rs/tui/src/app_server_session/account.rs index 0077a117..1d7508d9 100644 --- a/codex-rs/tui/src/app_server_session/account.rs +++ b/codex-rs/tui/src/app_server_session/account.rs @@ -58,17 +58,6 @@ impl SessionAccount { Some(StatusAccountDisplay::ApiKey) | None => None, } } - - pub(crate) fn feedback_audience(&self) -> FeedbackAudience { - if self - .email() - .is_some_and(|email| email.ends_with("@openai.com")) - { - FeedbackAudience::OpenAiEmployee - } else { - FeedbackAudience::External - } - } } impl AppServerSession { diff --git a/codex-rs/tui/src/bottom_pane/feedback_note_view.rs b/codex-rs/tui/src/bottom_pane/feedback_note_view.rs index 488876f5..d8751009 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_note_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_note_view.rs @@ -1,4 +1,4 @@ -//! Collects a feedback note with audience-specific disclosure and independent log consent. +//! Collects a feedback note with a local-save disclosure and independent log consent. //! The editor and submission controls remain visible when the disclosure must scroll. //! Unbracketed paste bursts insert newlines; Enter submits after the burst ends. @@ -24,21 +24,16 @@ use crate::app_event_sender::AppEventSender; use crate::key_hint; use crate::key_hint::has_ctrl_or_alt; use crate::render::renderable::Renderable; -use crate::terminal_hyperlinks::mark_underlined_hyperlink; use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_lines; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; -use super::feedback_view::FeedbackAudience; use super::paste_burst::PasteBurst; use super::popup_consts::accept_cancel_hint_line; use super::textarea::TextArea; use super::textarea::TextAreaState; -const FEEDBACK_POLICY_URL: &str = "https://help.openai.com/en/articles/5722486-how-your-data-is-used-to-improve-model-performance"; -const EMPLOYEE_FEEDBACK_FAQ_URL: &str = "https://go/codex-employee-feedback-faq"; - enum IntroContent { Full, DisclosureOnly, @@ -51,7 +46,6 @@ pub(crate) struct FeedbackNoteView { turn_id: Option, app_event_tx: AppEventSender, include_logs: bool, - feedback_audience: FeedbackAudience, // UI state textarea: TextArea, @@ -68,14 +62,12 @@ impl FeedbackNoteView { turn_id: Option, app_event_tx: AppEventSender, include_logs: bool, - feedback_audience: FeedbackAudience, ) -> Self { Self { category, turn_id, app_event_tx, include_logs, - feedback_audience, textarea: TextArea::new(), textarea_state: RefCell::new(TextAreaState::default()), paste_burst: PasteBurst::default(), @@ -261,11 +253,6 @@ impl Renderable for FeedbackNoteView { buf, ); } - let disclosure_url = match self.feedback_audience { - FeedbackAudience::OpenAiEmployee => EMPLOYEE_FEEDBACK_FAQ_URL, - FeedbackAudience::External => FEEDBACK_POLICY_URL, - }; - mark_underlined_hyperlink(buf, intro_area, disclosure_url); // Input line if input_area.width >= 2 { @@ -379,25 +366,14 @@ impl FeedbackNoteView { IntroContent::Full => vec![title.bold().into(), "".into()], IntroContent::DisclosureOnly => Vec::new(), }; - match self.feedback_audience { - FeedbackAudience::OpenAiEmployee => { - lines.push( - "Your data may be used to improve our models and products" - .bold() - .into(), - ); - lines.push(Line::from(vec![ - "By submitting feedback, you agree that OpenAI can use your feedback for safety purposes and internal model training, as explained in more detail ".dim(), - "here".fg(crate::style::accent_color()).underlined(), - ". Please avoid sharing tented information under NDA, or privileged, HR-related, or sensitive personal information.".dim(), - ])); - } - FeedbackAudience::External => lines.push(Line::from(vec![ - "Your feedback can be used to improve ChatGPT. ".dim(), - "Learn more".fg(crate::style::accent_color()).underlined(), - ".".dim(), - ])), - } + lines.push( + "Feedback is saved to a local file and never uploaded" + .bold() + .into(), + ); + lines.push(Line::from(vec![ + "The report is written as a ZIP archive under $CODEX_HOME/feedback. Review it before sharing it with anyone: logs can contain prompts, file contents, or other sensitive personal information.".dim(), + ])); word_wrap_lines( lines, RtOptions::new(usize::from(width.max(1))) diff --git a/codex-rs/tui/src/bottom_pane/feedback_note_view_tests.rs b/codex-rs/tui/src/bottom_pane/feedback_note_view_tests.rs index b00ec3f0..c0506652 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_note_view_tests.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_note_view_tests.rs @@ -39,11 +39,7 @@ fn make_view(category: FeedbackCategory) -> FeedbackNoteView { let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); let tx = AppEventSender::new(tx_raw); FeedbackNoteView::new( - category, - /*turn_id*/ None, - tx, - /*include_logs*/ true, - FeedbackAudience::External, + category, /*turn_id*/ None, tx, /*include_logs*/ true, ) } @@ -75,46 +71,22 @@ fn feedback_view_safety_check() { } #[test] -fn feedback_disclosure_matches_audience_at_normal_and_narrow_widths() { +fn feedback_disclosure_at_normal_and_narrow_widths() { let mut rendered = Vec::new(); - for (audience, name, url, link_label) in [ - ( - FeedbackAudience::External, - "external", - FEEDBACK_POLICY_URL, - "Learnmore", - ), - ( - FeedbackAudience::OpenAiEmployee, - "employee", - EMPLOYEE_FEEDBACK_FAQ_URL, - "here", - ), - ] { - let mut view = make_view(FeedbackCategory::Bug); - view.feedback_audience = audience; - for width in [80, 40] { - let area = Rect::new( - /*x*/ 0, - /*y*/ 0, - width, - view.desired_height(width), - ); - let mut buf = Buffer::empty(area); - view.render(area, &mut buf); - - let linked_text = buf - .content - .iter() - .filter(|cell| cell.symbol().contains(&format!("\x1b]8;;{url}\x07"))) - .map(|cell| crate::terminal_hyperlinks::strip_osc8(cell.symbol())) - .collect::(); - assert_eq!(linked_text, link_label); - rendered.push(format!( - "{name} ({width} columns)\n{}", - render_buffer(area, &buf) - )); - } + let view = make_view(FeedbackCategory::Bug); + for width in [80, 40] { + let area = Rect::new( + /*x*/ 0, + /*y*/ 0, + width, + view.desired_height(width), + ); + let mut buf = Buffer::empty(area); + view.render(area, &mut buf); + rendered.push(format!( + "local ({width} columns)\n{}", + render_buffer(area, &buf) + )); } insta::assert_snapshot!("feedback_disclosures", rendered.join("\n\n")); } @@ -124,7 +96,6 @@ fn feedback_disclosure_scrolls_without_hiding_input_in_short_panes() { let mut rendered = Vec::new(); for (width, height) in [(40, 12), (80, 8)] { let mut view = make_view(FeedbackCategory::Bug); - view.feedback_audience = FeedbackAudience::OpenAiEmployee; view.handle_paste("A visible note.".to_string()); let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height); for (stage, key) in [ @@ -157,7 +128,6 @@ fn feedback_disclosure_scrolls_without_hiding_input_in_short_panes() { #[test] fn feedback_disclosure_keeps_editor_visible_in_four_rows() { let mut view = make_view(FeedbackCategory::Bug); - view.feedback_audience = FeedbackAudience::OpenAiEmployee; view.handle_paste("A visible note.".to_string()); let area = Rect::new( /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 4, @@ -170,7 +140,7 @@ fn feedback_disclosure_keeps_editor_visible_in_four_rows() { .is_some_and(|(x, y)| area.contains((x, y).into())) ); let initial = render_buffer(area, &buf); - assert!(initial.contains("Your data may be used to improve our models and products")); + assert!(initial.contains("Feedback is saved to a local file and never uploaded")); for _ in view.intro_lines(area.width, IntroContent::Full) { view.handle_key_event(KeyEvent::from(KeyCode::PageDown)); buf = Buffer::empty(area); @@ -186,16 +156,10 @@ fn feedback_disclosure_keeps_editor_visible_in_four_rows() { let narrow_area = Rect::new( /*x*/ 0, /*y*/ 0, /*width*/ 24, /*height*/ 4, ); - for (audience, disclosure) in [ - (FeedbackAudience::OpenAiEmployee, "Your data"), - (FeedbackAudience::External, "Your feedback"), - ] { - let mut view = make_view(FeedbackCategory::SafetyCheck); - view.feedback_audience = audience; - let mut buf = Buffer::empty(narrow_area); - view.render(narrow_area, &mut buf); - assert!(render_buffer(narrow_area, &buf).contains(disclosure)); - } + let view = make_view(FeedbackCategory::SafetyCheck); + let mut buf = Buffer::empty(narrow_area); + view.render(narrow_area, &mut buf); + assert!(render_buffer(narrow_area, &buf).contains("Feedback is")); } #[test] @@ -208,7 +172,6 @@ fn feedback_paste_burst_preserves_multiline_note_until_submit() { /*turn_id*/ None, AppEventSender::new(tx), include_logs, - FeedbackAudience::External, ); let now = Instant::now(); for (index, ch) in note.chars().enumerate() { @@ -270,7 +233,6 @@ fn feedback_bracketed_paste_does_not_reach_chat_composer() { /*turn_id*/ None, tx, include_logs, - FeedbackAudience::External, ))); // An explicit paste ends any preceding keystroke burst. pane.handle_key_event(KeyEvent::from(KeyCode::Char('x'))); @@ -306,7 +268,6 @@ fn submit_feedback_emits_submit_event_with_trimmed_note() { Some("turn-123".to_string()), tx, /*include_logs*/ true, - FeedbackAudience::OpenAiEmployee, ); view.textarea.insert_str(" something broke "); @@ -334,7 +295,6 @@ fn submit_feedback_omits_empty_note() { /*turn_id*/ None, tx, /*include_logs*/ false, - FeedbackAudience::External, ); view.submit(); @@ -359,7 +319,6 @@ fn feedback_note_cancel_does_not_submit() { /*turn_id*/ None, AppEventSender::new(tx_raw), /*include_logs*/ false, - FeedbackAudience::OpenAiEmployee, ); view.textarea.insert_str("unfinished feedback"); diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index f576f13b..47f2aeb3 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -14,20 +14,6 @@ use crate::history_cell; use super::popup_consts::standard_popup_hint_line; -const BASE_CLI_BUG_ISSUE_URL: &str = - "https://github.com/openai/codex/issues/new?template=3-cli.yml"; -/// Internal routing link for employee feedback follow-ups. This must not be shown to external users. -const CODEX_FEEDBACK_INTERNAL_URL: &str = "http://go/codex-feedback-internal"; - -/// The target audience for feedback disclosure and follow-up instructions. -/// -/// This controls displayed copy and links, not feedback upload behavior. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum FeedbackAudience { - OpenAiEmployee, - External, -} - pub(crate) fn should_show_feedback_connectivity_details( category: FeedbackCategory, diagnostics: &FeedbackDiagnostics, @@ -45,101 +31,26 @@ pub(crate) fn feedback_classification(category: FeedbackCategory) -> &'static st } } +/// History cell shown after `/feedback` saved a local report archive. pub(crate) fn feedback_success_cell( - category: FeedbackCategory, include_logs: bool, + saved_path: &str, thread_id: &str, - feedback_audience: FeedbackAudience, ) -> history_cell::WebHyperlinkHistoryCell { let prefix = if include_logs { - "• Feedback uploaded." + "• Feedback saved locally with logs." } else { - "• Feedback recorded (no logs)." + "• Feedback saved locally (no logs)." }; - let issue_url = issue_url_for_category(category, thread_id, feedback_audience); - let mut lines = vec![Line::from(match issue_url.as_ref() { - Some(_) if feedback_audience == FeedbackAudience::OpenAiEmployee => { - format!("{prefix} You can share this in #codex-feedback:") - } - Some(_) => format!("{prefix} Please open an issue using the following URL:"), - None => format!("{prefix} Thanks for the feedback!"), - })]; - match issue_url { - Some(url) if feedback_audience == FeedbackAudience::OpenAiEmployee => { - lines.extend([ - "".into(), - Line::from(vec![ - " ".into(), - url.fg(crate::style::accent_color()).underlined(), - ]), - "".into(), - Line::from(vec![ - " Sentry Feedback ID: ".into(), - thread_id.to_string().bold(), - ]), - Line::from(vec![ - " Sentry URL: ".into(), - format!("https://go/codex-feedback/{thread_id}") - .fg(crate::style::accent_color()) - .underlined(), - ]), - ]); - } - Some(url) => { - lines.extend([ - "".into(), - Line::from(vec![ - " ".into(), - url.fg(crate::style::accent_color()).underlined(), - ]), - "".into(), - Line::from(vec![ - " Or mention your thread ID ".into(), - thread_id.to_string().bold(), - " in an existing issue.".into(), - ]), - ]); - } - None => { - lines.extend([ - "".into(), - Line::from(vec![" Thread ID: ".into(), thread_id.to_string().bold()]), - ]); - } - } + let lines = vec![ + Line::from(format!("{prefix} Nothing was sent anywhere.")), + "".into(), + Line::from(vec![" File: ".into(), saved_path.to_string().bold()]), + Line::from(vec![" Thread ID: ".into(), thread_id.to_string().bold()]), + ]; history_cell::WebHyperlinkHistoryCell::new(lines) } -fn issue_url_for_category( - category: FeedbackCategory, - thread_id: &str, - feedback_audience: FeedbackAudience, -) -> Option { - // Only certain categories provide a follow-up link. We intentionally keep - // the external GitHub behavior identical while routing internal users to - // the internal go link. - match category { - FeedbackCategory::Bug - | FeedbackCategory::BadResult - | FeedbackCategory::SafetyCheck - | FeedbackCategory::Other => Some(match feedback_audience { - FeedbackAudience::OpenAiEmployee => slack_feedback_url(thread_id), - FeedbackAudience::External => { - format!("{BASE_CLI_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}") - } - }), - FeedbackCategory::GoodResult => None, - } -} - -/// Build the internal follow-up URL. -/// -/// We accept a `thread_id` so the call site stays symmetric with the external -/// path, but we currently point to a fixed channel without prefilling text. -fn slack_feedback_url(_thread_id: &str) -> String { - CODEX_FEEDBACK_INTERNAL_URL.to_string() -} - // Build the selection popup params for feedback categories. pub(crate) fn feedback_selection_params( app_event_tx: AppEventSender, @@ -185,7 +96,7 @@ pub(crate) fn feedback_selection_params( /// Build the selection popup params shown when feedback is disabled. pub(crate) fn feedback_disabled_params() -> super::SelectionViewParams { super::SelectionViewParams { - title: Some("Sending feedback is disabled".to_string()), + title: Some("Feedback is disabled".to_string()), subtitle: Some("This action is disabled by configuration.".to_string()), footer_hint: Some(standard_popup_hint_line()), items: vec![super::SelectionItem { @@ -215,8 +126,8 @@ fn make_feedback_item( } } -/// Build the upload consent popup params for a given feedback category. -pub(crate) fn feedback_upload_consent_params( +/// Build the log consent popup params for a locally saved feedback report. +pub(crate) fn feedback_logs_consent_params( app_event_tx: AppEventSender, category: FeedbackCategory, rollout_path: Option, @@ -247,11 +158,11 @@ pub(crate) fn feedback_upload_consent_params( } }); - // Build header listing files that would be sent if user consents. + // Build header listing files that would be included in the local report. let mut header_lines: Vec> = vec![ - Line::from("Upload logs?".bold()).into(), + Line::from("Include logs in the saved report?".bold()).into(), Line::from("").into(), - Line::from("The following files will be sent:".dim()).into(), + Line::from("The following files will be saved locally (nothing is sent):".dim()).into(), Line::from(vec![" • ".into(), "codex-logs.log".into()]).into(), Line::from(vec![" • ".into(), "client-logs.txt (if available)".into()]).into(), Line::from(vec![ @@ -314,7 +225,7 @@ pub(crate) fn feedback_upload_consent_params( super::SelectionItem { name: "Yes".to_string(), description: Some( - "Share the current Codex session logs and diagnostics with the team for troubleshooting" + "Save the current session logs and diagnostics in the local feedback file" .to_string(), ), actions: vec![yes_action], @@ -395,10 +306,10 @@ mod tests { } #[test] - fn feedback_upload_consent_lists_doctor_report() { + fn feedback_logs_consent_lists_doctor_report() { let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); let tx = AppEventSender::new(tx_raw); - let params = feedback_upload_consent_params( + let params = feedback_logs_consent_params( tx, FeedbackCategory::Bug, Some(std::path::PathBuf::from("rollout.jsonl")), @@ -409,14 +320,14 @@ mod tests { let rendered = render_renderable(params.header.as_ref(), /*width*/ 60); - insta::assert_snapshot!("feedback_upload_consent_lists_doctor_report", rendered); + insta::assert_snapshot!("feedback_logs_consent_lists_doctor_report", rendered); } #[test] - fn feedback_upload_consent_lists_windows_sandbox_log_when_included() { + fn feedback_logs_consent_lists_windows_sandbox_log_when_included() { let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); let tx = AppEventSender::new(tx_raw); - let params = feedback_upload_consent_params( + let params = feedback_logs_consent_params( tx, FeedbackCategory::Bug, Some(std::path::PathBuf::from("rollout.jsonl")), @@ -428,7 +339,7 @@ mod tests { let rendered = render_renderable(params.header.as_ref(), /*width*/ 60); insta::assert_snapshot!( - "feedback_upload_consent_lists_windows_sandbox_log_when_included", + "feedback_logs_consent_lists_windows_sandbox_log_when_included", rendered ); } @@ -459,116 +370,24 @@ mod tests { } #[test] - fn issue_url_available_for_bug_bad_result_safety_check_and_other() { - let bug_url = issue_url_for_category( - FeedbackCategory::Bug, - "thread-1", - FeedbackAudience::OpenAiEmployee, - ); - let expected_slack_url = "http://go/codex-feedback-internal".to_string(); - assert_eq!(bug_url.as_deref(), Some(expected_slack_url.as_str())); - - let bad_result_url = issue_url_for_category( - FeedbackCategory::BadResult, - "thread-2", - FeedbackAudience::OpenAiEmployee, - ); - assert!(bad_result_url.is_some()); - - let other_url = issue_url_for_category( - FeedbackCategory::Other, - "thread-3", - FeedbackAudience::OpenAiEmployee, - ); - assert!(other_url.is_some()); - - let safety_check_url = issue_url_for_category( - FeedbackCategory::SafetyCheck, - "thread-4", - FeedbackAudience::OpenAiEmployee, - ); - assert!(safety_check_url.is_some()); - - assert!( - issue_url_for_category( - FeedbackCategory::GoodResult, - "t", - FeedbackAudience::OpenAiEmployee - ) - .is_none() - ); - let bug_url_non_employee = - issue_url_for_category(FeedbackCategory::Bug, "t", FeedbackAudience::External); - let expected_external_url = "https://github.com/openai/codex/issues/new?template=3-cli.yml&steps=Uploaded%20thread:%20t"; - assert_eq!(bug_url_non_employee.as_deref(), Some(expected_external_url)); - } - - #[test] - fn feedback_success_cell_matches_external_bug_copy() { + fn feedback_success_cell_reports_local_file() { let rendered = render_cell( - &feedback_success_cell( - FeedbackCategory::Bug, - /*include_logs*/ true, - "thread-1", - FeedbackAudience::External, - ), + &feedback_success_cell(/*include_logs*/ true, "/tmp/feedback.zip", "thread-1"), /*width*/ 120, ); assert_eq!( rendered, - "• Feedback uploaded. Please open an issue using the following URL:\n\n https://github.com/openai/codex/issues/new?template=3-cli.yml&steps=Uploaded%20thread:%20thread-1\n\n Or mention your thread ID thread-1 in an existing issue." + "• Feedback saved locally with logs. Nothing was sent anywhere.\n\n File: /tmp/feedback.zip\n Thread ID: thread-1" ); } #[test] - fn feedback_success_cell_matches_employee_bug_copy() { + fn feedback_success_cell_reports_missing_logs() { let rendered = render_cell( - &feedback_success_cell( - FeedbackCategory::Bug, - /*include_logs*/ true, - "thread-2", - FeedbackAudience::OpenAiEmployee, - ), + &feedback_success_cell(/*include_logs*/ false, "/tmp/feedback.zip", "thread-3"), /*width*/ 120, ); - insta::assert_snapshot!("feedback_success_employee", rendered); - } - - #[test] - fn feedback_success_cell_matches_good_result_copy() { - let rendered = render_cell( - &feedback_success_cell( - FeedbackCategory::GoodResult, - /*include_logs*/ false, - "thread-3", - FeedbackAudience::External, - ), - /*width*/ 120, - ); - assert_eq!( - rendered, - "• Feedback recorded (no logs). Thanks for the feedback!\n\n Thread ID: thread-3" - ); - } - - #[test] - fn feedback_success_cell_uses_issue_links_for_remaining_categories() { - for category in [ - FeedbackCategory::BadResult, - FeedbackCategory::SafetyCheck, - FeedbackCategory::Other, - ] { - let rendered = render_cell( - &feedback_success_cell( - category, - /*include_logs*/ false, - "thread-4", - FeedbackAudience::External, - ), - /*width*/ 120, - ); - assert!(rendered.contains("Please open an issue using the following URL:")); - assert!(rendered.contains("thread-4")); - } + assert!(rendered.starts_with("• Feedback saved locally (no logs).")); + assert!(rendered.contains("thread-3")); } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 046b5809..cad53288 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -196,12 +196,11 @@ use slash_commands::ServiceTierCommand; mod feedback_note_view; mod feedback_view; mod hooks_browser_view; -pub(crate) use feedback_view::FeedbackAudience; pub(crate) use feedback_view::feedback_classification; pub(crate) use feedback_view::feedback_disabled_params; +pub(crate) use feedback_view::feedback_logs_consent_params; pub(crate) use feedback_view::feedback_selection_params; pub(crate) use feedback_view::feedback_success_cell; -pub(crate) use feedback_view::feedback_upload_consent_params; pub(crate) use skills_toggle_view::SkillsToggleItem; pub(crate) use skills_toggle_view::SkillsToggleView; pub(crate) use status_line_setup::StatusLineItem; diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_four_rows.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_four_rows.snap index 78d4b6dc..0f19826d 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_four_rows.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_four_rows.snap @@ -2,12 +2,12 @@ source: tui/src/bottom_pane/feedback_note_view_tests.rs expression: "format!(\"{initial}\\n\\n{scrolled}\")" --- -▌ Your data may be used to improve our models and products +▌ Feedback is saved to a local file and never uploaded ▌ ▌ A visible note. Press enter to submit or esc to cancel -▌ sensitive personal information. +▌ other sensitive personal information. ▌ ▌ A visible note. Press enter to submit or esc to cancel diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_short_panes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_short_panes.snap index c3a55552..99598bce 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_short_panes.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosure_short_panes.snap @@ -5,26 +5,26 @@ expression: "rendered.join(\"\\n\\n\")" 40x12 initial ▌ Tell us more (bug) ▌ -▌ Your data may be used to improve our -▌ models and products -▌ By submitting feedback, you agree that -▌ OpenAI can use your feedback for -▌ safety purposes and internal model -▌ training, as explained in more detail +▌ Feedback is saved to a local file and +▌ never uploaded +▌ The report is written as a ZIP archive +▌ under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs +▌ can contain prompts, file contents, or ▌ ▌ A visible note. pgup/pgdn scroll disclosure Press enter to submit or esc to cancel 40x12 scrolled -▌ By submitting feedback, you agree that -▌ OpenAI can use your feedback for -▌ safety purposes and internal model -▌ training, as explained in more detail -▌ here. Please avoid sharing tented -▌ information under NDA, or privileged, -▌ HR-related, or sensitive personal -▌ information. +▌ +▌ Feedback is saved to a local file and +▌ never uploaded +▌ The report is written as a ZIP archive +▌ under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs +▌ can contain prompts, file contents, or +▌ other sensitive personal information. ▌ ▌ A visible note. pgup/pgdn scroll disclosure @@ -33,12 +33,12 @@ Press enter to submit or esc to cancel 40x12 restored ▌ Tell us more (bug) ▌ -▌ Your data may be used to improve our -▌ models and products -▌ By submitting feedback, you agree that -▌ OpenAI can use your feedback for -▌ safety purposes and internal model -▌ training, as explained in more detail +▌ Feedback is saved to a local file and +▌ never uploaded +▌ The report is written as a ZIP archive +▌ under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs +▌ can contain prompts, file contents, or ▌ ▌ A visible note. pgup/pgdn scroll disclosure @@ -47,18 +47,18 @@ Press enter to submit or esc to cancel 80x8 initial ▌ Tell us more (bug) ▌ -▌ Your data may be used to improve our models and products -▌ By submitting feedback, you agree that OpenAI can use your feedback for safety +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/feedback. Review it ▌ ▌ A visible note. pgup/pgdn scroll disclosure Press enter to submit or esc to cancel 80x8 scrolled -▌ By submitting feedback, you agree that OpenAI can use your feedback for safety -▌ purposes and internal model training, as explained in more detail here. Please -▌ avoid sharing tented information under NDA, or privileged, HR-related, or -▌ sensitive personal information. +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs can contain prompts, file contents, or +▌ other sensitive personal information. ▌ ▌ A visible note. pgup/pgdn scroll disclosure @@ -67,8 +67,8 @@ Press enter to submit or esc to cancel 80x8 restored ▌ Tell us more (bug) ▌ -▌ Your data may be used to improve our models and products -▌ By submitting feedback, you agree that OpenAI can use your feedback for safety +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/feedback. Review it ▌ ▌ A visible note. pgup/pgdn scroll disclosure diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosures.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosures.snap index 8440474e..751058ee 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosures.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_disclosures.snap @@ -2,51 +2,28 @@ source: tui/src/bottom_pane/feedback_note_view_tests.rs expression: "rendered.join(\"\\n\\n\")" --- -external (80 columns) +local (80 columns) ▌ Tell us more (bug) ▌ -▌ Your feedback can be used to improve ChatGPT. Learn more. +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs can contain prompts, file contents, or +▌ other sensitive personal information. ▌ ▌ (optional) Write a short description to help us further Press enter to submit or esc to cancel -external (40 columns) +local (40 columns) ▌ Tell us more (bug) ▌ -▌ Your feedback can be used to improve -▌ ChatGPT. Learn more. -▌ -▌ (optional) Write a short description t - -Press enter to submit or esc to cancel - -employee (80 columns) -▌ Tell us more (bug) -▌ -▌ Your data may be used to improve our models and products -▌ By submitting feedback, you agree that OpenAI can use your feedback for safety -▌ purposes and internal model training, as explained in more detail here. Please -▌ avoid sharing tented information under NDA, or privileged, HR-related, or -▌ sensitive personal information. -▌ -▌ (optional) Write a short description to help us further - -Press enter to submit or esc to cancel - -employee (40 columns) -▌ Tell us more (bug) -▌ -▌ Your data may be used to improve our -▌ models and products -▌ By submitting feedback, you agree that -▌ OpenAI can use your feedback for -▌ safety purposes and internal model -▌ training, as explained in more detail -▌ here. Please avoid sharing tented -▌ information under NDA, or privileged, -▌ HR-related, or sensitive personal -▌ information. +▌ Feedback is saved to a local file and +▌ never uploaded +▌ The report is written as a ZIP archive +▌ under $CODEX_HOME/feedback. Review it +▌ before sharing it with anyone: logs +▌ can contain prompts, file contents, or +▌ other sensitive personal information. ▌ ▌ (optional) Write a short description t diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_multiline_paste.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_multiline_paste.snap index 4b2ff023..2a07afcf 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_multiline_paste.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_multiline_paste.snap @@ -4,7 +4,11 @@ expression: "render(&view, 60)" --- ▌ Tell us more (bug) ▌ -▌ Your feedback can be used to improve ChatGPT. Learn more. +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/ +▌ feedback. Review it before sharing it with anyone: logs +▌ can contain prompts, file contents, or other sensitive +▌ personal information. ▌ ▌ foo ▌ bar diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_bug.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_bug.snap index 2183ee61..81532b9c 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_bug.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_bug.snap @@ -4,7 +4,11 @@ expression: rendered --- ▌ Tell us more (bug) ▌ -▌ Your feedback can be used to improve ChatGPT. Learn more. +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/ +▌ feedback. Review it before sharing it with anyone: logs +▌ can contain prompts, file contents, or other sensitive +▌ personal information. ▌ ▌ (optional) Write a short description to help us further diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_safety_check.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_safety_check.snap index faee63e0..4f0ed3b7 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_safety_check.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_note_view__tests__feedback_view_safety_check.snap @@ -4,7 +4,11 @@ expression: rendered --- ▌ Tell us more (safety check) ▌ -▌ Your feedback can be used to improve ChatGPT. Learn more. +▌ Feedback is saved to a local file and never uploaded +▌ The report is written as a ZIP archive under $CODEX_HOME/ +▌ feedback. Review it before sharing it with anyone: logs +▌ can contain prompts, file contents, or other sensitive +▌ personal information. ▌ ▌ (optional) Share what was refused and why it should have b diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_doctor_report.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_doctor_report.snap similarity index 76% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_doctor_report.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_doctor_report.snap index bbc17375..6588f2bb 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_doctor_report.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_doctor_report.snap @@ -1,11 +1,10 @@ --- source: tui/src/bottom_pane/feedback_view.rs -assertion_line: 728 expression: rendered --- -Upload logs? +Include logs in the saved report? -The following files will be sent: +The following files will be saved locally (nothing is sent): • codex-logs.log • client-logs.txt (if available) • codex-doctor-report.json diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_windows_sandbox_log_when_included.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_windows_sandbox_log_when_included.snap similarity index 78% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_windows_sandbox_log_when_included.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_windows_sandbox_log_when_included.snap index edb8291a..4de097f9 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_upload_consent_lists_windows_sandbox_log_when_included.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_logs_consent_lists_windows_sandbox_log_when_included.snap @@ -1,11 +1,10 @@ --- source: tui/src/bottom_pane/feedback_view.rs -assertion_line: 746 expression: rendered --- -Upload logs? +Include logs in the saved report? -The following files will be sent: +The following files will be saved locally (nothing is sent): • codex-logs.log • client-logs.txt (if available) • codex-doctor-report.json diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_success_employee.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_success_employee.snap deleted file mode 100644 index b69ba4bf..00000000 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_success_employee.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: tui/src/bottom_pane/feedback_view.rs -expression: rendered ---- -• Feedback uploaded. You can share this in #codex-feedback: - - http://go/codex-feedback-internal - - Sentry Feedback ID: thread-2 - Sentry URL: https://go/codex-feedback/thread-2 diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index d4b7af59..63108bd4 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -337,8 +337,8 @@ mod permissions_menu; pub(crate) use self::permissions_menu::auto_review_available; pub(crate) use self::permissions_menu::cyber_model_approval_reviewer; mod compaction; -mod security_setup; mod protocol; +mod security_setup; pub(crate) use protocol::final_agent_message; pub(crate) use protocol::needs_agent_message; mod protocol_requests; @@ -965,14 +965,12 @@ impl ChatWidget { &mut self, category: crate::app_event::FeedbackCategory, include_logs: bool, - feedback_audience: crate::bottom_pane::FeedbackAudience, ) { let view = crate::bottom_pane::FeedbackNoteView::new( category, self.turn_lifecycle.last_turn_id.clone(), self.app_event_tx.clone(), include_logs, - feedback_audience, ); self.bottom_pane.show_view(Box::new(view)); self.request_redraw(); @@ -1024,7 +1022,7 @@ impl ChatWidget { .is_file(); #[cfg(not(target_os = "windows"))] let include_windows_sandbox_log = false; - let params = crate::bottom_pane::feedback_upload_consent_params( + let params = crate::bottom_pane::feedback_logs_consent_params( self.app_event_tx.clone(), category, self.current_rollout_path.clone(), diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap index ff69171a..265c12b4 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap @@ -2,9 +2,9 @@ source: tui/src/chatwidget/tests/popups_and_settings.rs expression: popup --- - Upload logs? + Include logs in the saved report? › As - The following files will be sent: + The following files will be saved locally (nothing is sent): GP • codex-logs.log • client-logs.txt (if available) • codex-doctor-report.json @@ -14,8 +14,8 @@ expression: popup • codex-connectivity-diagnostics.txt - › 1. Yes Share the current Codex session logs and diagnostics with the - team for troubleshooting + › 1. Yes Save the current session logs and diagnostics in the local + feedback file 2. No enter select · esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_logs_consent_popup.snap similarity index 74% rename from codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap rename to codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_logs_consent_popup.snap index 99a9916b..1e4925ea 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_logs_consent_popup.snap @@ -2,9 +2,9 @@ source: tui/src/chatwidget/tests/popups_and_settings.rs expression: popup --- - Upload logs? + Include logs in the saved report? › As - The following files will be sent: + The following files will be saved locally (nothing is sent): GP • codex-logs.log • client-logs.txt (if available) • codex-doctor-report.json @@ -19,8 +19,8 @@ expression: popup - HTTPS_PROXY = hello - › 1. Yes Share the current Codex session logs and diagnostics with the - team for troubleshooting + › 1. Yes Save the current session logs and diagnostics in the local + feedback file 2. No enter select · esc back diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index bf9b1084..cb27bbbd 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -1045,7 +1045,6 @@ async fn live_app_server_turn_started_sets_feedback_turn_id() { chat.open_feedback_note( crate::app_event::FeedbackCategory::Bug, /*include_logs*/ false, - crate::bottom_pane::FeedbackAudience::External, ); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index 6a5d4e04..9dc64d32 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -4328,10 +4328,10 @@ async fn feedback_selection_popup_snapshot() { } #[tokio::test] -async fn feedback_upload_consent_popup_snapshot() { +async fn feedback_logs_consent_popup_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.show_selection_view(crate::bottom_pane::feedback_upload_consent_params( + chat.show_selection_view(crate::bottom_pane::feedback_logs_consent_params( chat.app_event_tx.clone(), crate::app_event::FeedbackCategory::Bug, chat.current_rollout_path.clone(), @@ -4345,14 +4345,14 @@ async fn feedback_upload_consent_popup_snapshot() { )); let popup = render_bottom_popup(&chat, /*width*/ 80); - assert_chatwidget_snapshot!("feedback_upload_consent_popup", popup); + assert_chatwidget_snapshot!("feedback_logs_consent_popup", popup); } #[tokio::test] async fn feedback_good_result_consent_popup_includes_connectivity_diagnostics_filename() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.show_selection_view(crate::bottom_pane::feedback_upload_consent_params( + chat.show_selection_view(crate::bottom_pane::feedback_logs_consent_params( chat.app_event_tx.clone(), crate::app_event::FeedbackCategory::GoodResult, chat.current_rollout_path.clone(), diff --git a/codex-rs/tui/src/daemon_startup_tests.rs b/codex-rs/tui/src/daemon_startup_tests.rs index e80c9b19..e9d8a6b9 100644 --- a/codex-rs/tui/src/daemon_startup_tests.rs +++ b/codex-rs/tui/src/daemon_startup_tests.rs @@ -44,26 +44,6 @@ fn feature_overrides_allow_daemon_without_allowing_arbitrary_config() { } } -#[test] -fn daemon_launch_telemetry_records_once_on_connection_update_or_early_return() { - for mode in [Some("in_process"), Some("update_requested"), None] { - let observations = std::cell::RefCell::new(Vec::new()); - let launch = daemon_telemetry::Launch(Some(|actual| { - observations.borrow_mut().push(actual); - Vec::new() - })); - if let Some(mode) = mode { - launch.record(mode); - } else { - drop(launch); - } - assert_eq!( - observations.into_inner(), - vec![mode.unwrap_or("unconfirmed")] - ); - } -} - #[tokio::test] async fn daemon_feature_compatibility_respects_required_and_optional_attachment() -> color_eyre::Result<()> { diff --git a/codex-rs/tui/src/daemon_telemetry.rs b/codex-rs/tui/src/daemon_telemetry.rs deleted file mode 100644 index 47979df7..00000000 --- a/codex-rs/tui/src/daemon_telemetry.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Records automatic daemon startup and ensures launch observations survive setup failures. - -use super::*; -use crate::terminal_size_telemetry::LaunchTags; - -/// Record the connection mode or update handoff once. Other early exits are unconfirmed. -pub(super) struct Launch LaunchTags>(pub(super) Option); - -impl LaunchTags> Launch { - pub(super) fn record(mut self, app_server_mode: &'static str) -> LaunchTags { - self.0 - .take() - .map(|record| record(app_server_mode)) - .unwrap_or_default() - } -} - -impl LaunchTags> Drop for Launch { - fn drop(&mut self) { - if let Some(record) = self.0.take() { - record("unconfirmed"); - } - } -} - -pub(super) async fn record_start( - config: &Config, - result: &Result< - codex_app_server_daemon::LifecycleOutput, - codex_app_server_daemon::telemetry::StartError, - >, -) { - use codex_app_server_daemon::LifecycleStatus; - let outcome = match result { - Ok(output) => match output.status { - LifecycleStatus::Started => "started", - LifecycleStatus::AlreadyRunning => "already_running", - LifecycleStatus::Restarted => "restarted", - LifecycleStatus::Stopped | LifecycleStatus::NotRunning | LifecycleStatus::Running => { - "unconfirmed" - } - }, - Err(_) => "failed", - }; - // Failure can happen before normal TUI telemetry is initialized. This short-lived - // provider uses exactly the same consent and identity construction as TUI startup. - let Ok(Ok(Some(otel))) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - codex_app_server_client::build_otel_provider( - config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - /*default_analytics_enabled*/ true, - ) - })) else { - return; - }; - if let Some(metrics) = otel.metrics() { - let mut tags = codex_app_server_daemon::telemetry::settings_tags(&config.codex_home) - .await - .to_vec(); - tags.extend([ - ("initiation_source", "tui_auto_start"), - ("outcome", outcome), - ]); - if let Err(error) = result { - tags.push(("failure_reason", error.failure_reason())); - } - let _ = metrics.counter("codex.daemon.start", /*inc*/ 1, &tags); - } - let _ = otel - .shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT) - .await; -} diff --git a/codex-rs/tui/src/history_cell/tests.rs b/codex-rs/tui/src/history_cell/tests.rs index 14ac4d99..ed32704e 100644 --- a/codex-rs/tui/src/history_cell/tests.rs +++ b/codex-rs/tui/src/history_cell/tests.rs @@ -3159,7 +3159,7 @@ fn agent_markdown_cell_survives_insert_history_rewrap() { Canary rollout remained at limited traffic longer than planned because p95 latency briefly regressed during cold-cache periods. Regional expansion succeeded with stable error rates, though internal - analytics lagged temporarily. + dashboards lagged temporarily. "; let cell = AgentMarkdownCell::new(source.to_string(), &test_cwd()); let width: u16 = 80; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 3926fbfd..1da4619c 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -54,7 +54,6 @@ use codex_config::types::ResumeCwdMode; use codex_exec_server::EnvironmentManager; use codex_exec_server::ExecServerRuntimeOptions; use codex_features::Feature; -use codex_login::default_client::originator; use codex_login::default_client::set_default_client_residency_requirement; use codex_login::enforce_login_restrictions; use codex_login::is_workload_identity_selected; @@ -85,7 +84,6 @@ use std::io::IsTerminal; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; -use std::time::Duration; use std::time::Instant; pub use token_usage::TokenUsage; use tracing::error; @@ -226,7 +224,6 @@ mod temporary_structured_request; mod terminal_hyperlinks; mod terminal_palette; mod terminal_probe; -mod terminal_size_telemetry; mod terminal_title; mod terminal_visualization_instructions; mod text_formatting; @@ -283,7 +280,6 @@ pub use public_widgets::composer_input::ComposerInput; // (tests access modules directly within the crate) const TUI_LOG_FILE_NAME: &str = "codex-tui.log"; -const INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(/*millis*/ 500); const AUTO_CONNECT_DAEMON_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(50); @@ -1222,9 +1218,6 @@ async fn run_ratatui_app( managed_worktree: Option, daemon_startup_warning: Option, managed_daemon: bool, - launch_telemetry: daemon_telemetry::Launch< - impl FnOnce(&'static str) -> terminal_size_telemetry::LaunchTags, - >, startup_draft: startup_draft::StartupDraft, ) -> color_eyre::Result { // Capture host credentials and project inputs before resume/fork reloads executor config. @@ -1264,7 +1257,6 @@ async fn run_ratatui_app( UpdatePromptOutcome::Continue => {} UpdatePromptOutcome::RunUpdate(action) => { terminal_restore_guard.restore()?; - launch_telemetry.record("update_requested"); return Ok(AppExitInfo { token_usage: crate::token_usage::TokenUsage::default(), thread_id: None, @@ -1313,20 +1305,12 @@ async fn run_ratatui_app( ) .await; let mut app_server_session = match startup_app_server { - Ok(Ok(app_server)) => { - tui.terminal_size_tags = launch_telemetry.record(match &app_server_target { - AppServerTarget::Embedded => "in_process", - AppServerTarget::LocalDaemon { .. } => "local_daemon", - AppServerTarget::Remote { .. } => "remote", - AppServerTarget::Cloud => "cloud", - }); - AppServerSession::new( - backend_id, - app_server, - app_server_target.thread_params_mode(), - ) - .with_local_codex_home(&initial_config.codex_home) - } + Ok(Ok(app_server)) => AppServerSession::new( + backend_id, + app_server, + app_server_target.thread_params_mode(), + ) + .with_local_codex_home(&initial_config.codex_home), Ok(Err(err)) => { terminal_restore_guard.restore_silently(); session_log::log_session_end(); @@ -1520,7 +1504,6 @@ async fn run_ratatui_app( } let reloaded_config = startup_draft .run_until(&mut tui, async { - // Reload config when persisted trust or auth changes alter the current process. Ok::<_, std::io::Error>( if !uses_remote_workspace @@ -2103,18 +2086,6 @@ async fn run_ratatui_app( config.cwd.as_path(), ); - // Count launches that reach final config resolution, regardless of screen policy. - if config.analytics_enabled != Some(false) - && config.otel.metrics_exporter != codex_config::types::OtelExporterKind::None - && let Some(metrics) = codex_otel::global() - { - let _ = metrics.counter( - "codex.tui.fullscreen_transcript", - /*inc*/ 1, - &[("enabled", &config.tui_fullscreen_transcript.to_string())], - ); - } - // Cloud configuration and session selection can change screen policy after first paint. let use_alt_screen = determine_alt_screen_mode( cli.no_alt_screen, @@ -2563,7 +2534,6 @@ fn should_show_provider_setup_wizard( mod daemon_recovery; mod daemon_startup; -mod daemon_telemetry; #[cfg(test)] #[path = "lib_tests.rs"] diff --git a/codex-rs/tui/src/multi_agents.rs b/codex-rs/tui/src/multi_agents.rs index e7f3d389..92290a64 100644 --- a/codex-rs/tui/src/multi_agents.rs +++ b/codex-rs/tui/src/multi_agents.rs @@ -224,7 +224,7 @@ pub(crate) fn tool_call_history_cell( let prompt = prompt.as_deref().unwrap_or_default(); match tool { - // V2 uses SubAgentActivity for display; these variants are analytics-only. + // V2 uses SubAgentActivity for display; these variants are not displayed. CollabAgentTool::SendMessage | CollabAgentTool::FollowupTask | CollabAgentTool::InterruptAgent diff --git a/codex-rs/tui/src/security_setup.rs b/codex-rs/tui/src/security_setup.rs index 5c7ce789..180a3607 100644 --- a/codex-rs/tui/src/security_setup.rs +++ b/codex-rs/tui/src/security_setup.rs @@ -1,6 +1,6 @@ //! Optional account-security reminders for the local, ChatGPT-authenticated CLI. //! The server owns eligibility, rollout and cutoff copy. Reads never block a turn; -//! no reminder analytics are sent. Unknown or unavailable state produces no notice. +//! nothing is reported anywhere. Unknown or unavailable state produces no notice. use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 0e51ae10..d3fb3458 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -92,7 +92,7 @@ impl SlashCommand { pub fn description(self) -> &'static str { match self { SlashCommand::Config => "configure Codex preferences", - SlashCommand::Feedback => "send logs to maintainers", + SlashCommand::Feedback => "save a feedback report with logs locally", SlashCommand::New => "start a new chat during a conversation", SlashCommand::Init => "create an AGENTS.md file with instructions for Codex", SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", diff --git a/codex-rs/tui/src/startup_orchestration.rs b/codex-rs/tui/src/startup_orchestration.rs index 8d5414c3..eae817da 100644 --- a/codex-rs/tui/src/startup_orchestration.rs +++ b/codex-rs/tui/src/startup_orchestration.rs @@ -4,8 +4,6 @@ //! configuration and app-server initialization remain responsive to safe local editing. use super::*; -use codex_terminal_detection::Multiplexer; -use codex_terminal_detection::TerminalName; pub(super) async fn run_main_inner( mut cli: Cli, @@ -64,7 +62,6 @@ pub(super) async fn run_main_inner( .take_auto_review_config_overrides(&mut cli.config_overrides); // Map the legacy --search flag to the canonical web_search mode. - let overrides_before_search = cli.config_overrides.raw_overrides.len(); if cli.web_search { cli.config_overrides .raw_overrides @@ -221,14 +218,6 @@ pub(super) async fn run_main_inner( std::env::var_os(codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR).as_deref(), ); let reuse_implicit_local_daemon = daemon_exclusion.is_none(); - let search_forces_embedded = cli.web_search - && daemon_startup::config_exclusion( - &cli_kv_overrides[..overrides_before_search], - &launch_loader_overrides, - strict_config, - cli.bypass_hook_trust, - ) - .is_none(); let search_only_config_override = !workload_identity_selected && cli.web_search && startup_preflight::has_only_search_config_override(&cli_kv_overrides) @@ -320,9 +309,6 @@ pub(super) async fn run_main_inner( }) .await .map_err(std::io::Error::other)??; - // Snapshot the backend size sampled during init, before any viewport changes or resizes. - let initial_terminal_size = initialized_terminal.terminal.last_known_screen_size; - let terminal_size_tags = crate::terminal_size_telemetry::tags(initial_terminal_size); let startup_presentation::StartupPresentation { bootstrap_config, config_cwd, @@ -596,7 +582,6 @@ pub(super) async fn run_main_inner( let result = codex_app_server_daemon::start_with_features_classified(&Default::default()) .await; - daemon_telemetry::record_start(&config, &result).await; match result.map_err(|err| err.error) { Ok(output) => Ok(Some(output)), #[cfg(windows)] @@ -666,156 +651,6 @@ pub(super) async fn run_main_inner( remove_legacy_tui_log_file(config.codex_home.as_path()); - let otel_originator = originator().value; - let otel = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - codex_app_server_client::build_otel_provider( - &config, - env!("CARGO_PKG_VERSION"), - /*service_name_override*/ None, - /*default_analytics_enabled*/ true, - ) - })) { - Ok(Ok(otel)) => otel, - Ok(Err(e)) => { - startup_draft.flush_pending_events().await?; - startup_draft - .tui_mut() - .with_restored(crate::tui::TerminalHandoff::Restore, || async { - #[allow(clippy::print_stderr)] - { - eprintln!("Could not create otel exporter: {e}"); - } - }) - .await; - None - } - Err(_) => { - #[allow(clippy::print_stderr)] - { - eprintln!("Could not create otel exporter: panicked during initialization"); - } - startup_draft.tui_mut().recover_after_caught_panic()?; - None - } - }; - let metrics = otel - .as_ref() - .and_then(codex_otel::OtelProvider::metrics) - .cloned(); - if let Some(metrics) = &metrics { - let _ = codex_otel::record_process_start_once(metrics, otel_originator.as_str()); - let telemetry = - codex_rollout::sqlite_telemetry_recorder(metrics.clone(), otel_originator.as_str()); - let _ = codex_state::install_process_db_telemetry(telemetry); - } - let selection_reason = match (&app_server_target, daemon_exclusion) { - (AppServerTarget::Remote { .. }, _) => "explicit_remote", - (AppServerTarget::Cloud, _) => "cloud", - _ if cli.agents_overview => "agents", - _ if elevated_warning.is_some() => "elevated_windows", - (_, Some("--no-daemon")) => "explicit_no_daemon", - (_, Some(_)) => "incompatible_option", - _ if auto_start_daemon => "auto_start", - (AppServerTarget::LocalDaemon { .. }, _) => "existing_daemon", - (AppServerTarget::Embedded, None) => "auto_start_disabled", - }; - let daemon_settings = if metrics.is_some() { - codex_app_server_daemon::telemetry::settings_tags(&config.codex_home) - .await - .to_vec() - } else { - Vec::new() - }; - let mut launch_tags = daemon_settings.to_vec(); - launch_tags.extend(terminal_size_tags); - launch_tags.extend([ - ("daemon_selection_reason", selection_reason), - ( - "daemon_auto_start", - if config.features.enabled(Feature::DaemonAutoStart) { - "enabled" - } else { - "disabled" - }, - ), - ]); - let selected_local_daemon = matches!(app_server_target, AppServerTarget::LocalDaemon { .. }); - let launch_telemetry = move |app_server_mode| { - let Some(metrics) = metrics else { - return Vec::new(); - }; - // Use a fixed category, not the versioned or user-provided terminal identifier. - let terminal_info = codex_terminal_detection::terminal_info(); - let terminal_name = match terminal_info.name { - TerminalName::AppleTerminal => "apple_terminal", - TerminalName::Ghostty => "ghostty", - TerminalName::Rex => "rex", - TerminalName::Iterm2 => "iterm2", - TerminalName::WarpTerminal => "warp", - TerminalName::VsCode => "vscode", - TerminalName::WezTerm => "wezterm", - TerminalName::Kitty => "kitty", - TerminalName::Alacritty => "alacritty", - TerminalName::Konsole => "konsole", - TerminalName::GnomeTerminal => "gnome_terminal", - TerminalName::Vte => "vte", - TerminalName::WindowsTerminal => "windows_terminal", - TerminalName::Dumb => "dumb", - TerminalName::Unknown => "unknown", - }; - let multiplexer = match terminal_info.multiplexer { - Some(Multiplexer::Tmux { .. }) => "tmux", - Some(Multiplexer::Zellij { .. }) => "zellij", - None => "none", - }; - launch_tags.extend([ - ("app_server_mode", app_server_mode), - ("terminal_name", terminal_name), - ("multiplexer", multiplexer), - ]); - let _ = metrics.counter("codex.tui.start", /*inc*/ 1, &launch_tags); - if app_server_mode == "in_process" { - let reason = match daemon_exclusion { - _ if elevated_warning.is_some() => "windows_elevated", - Some("--no-daemon") => "explicit_no_daemon", - Some("--profile") => "profile", - Some("--oss") => "oss", - Some("--strict-config") => "strict_config", - Some("--dangerously-bypass-hook-trust") => "bypass_hook_trust", - Some("workload identity") => "workload_identity", - Some("executor selection (CODEX_EXEC_SERVER_URL)") => "exec_server_url", - Some("custom configuration loader") => "custom_config_loader", - Some( - "command-line configuration overrides (-c, --enable, --disable, or --search)", - ) => { - if search_forces_embedded { - "search" - } else { - "config_override" - } - } - Some("GCP sign-in") => "gcp_sign_in", - Some(daemon_startup::GATEWAY_SIGN_IN_EXCLUSION) => "gateway_sign_in", - Some(daemon_startup::WSL_DRVFS_EXCLUSION) => "wsl_drvfs", - Some("this Windows launcher") => "windows_detach_restricted", - Some("daemon feature settings") => "daemon_compatibility", - None if selection_reason == "auto_start_disabled" => { - "auto_start_disabled_no_daemon" - } - None if selected_local_daemon => "daemon_connection_failed", - None if selection_reason == "agents" => "agents_no_daemon_discovered", - Some(_) | None => "unclassified", - }; - let _ = metrics.counter( - "codex.tui.embedded_start", - /*inc*/ 1, - &[("reason", reason)], - ); - } - launch_tags.retain(|(key, _)| !matches!(*key, "terminal_columns" | "terminal_rows")); - launch_tags - }; - let launch_telemetry = daemon_telemetry::Launch(Some(launch_telemetry)); let state_db = startup_draft .run_until(init_state_db_for_app_server_target( &config, @@ -847,12 +682,6 @@ pub(super) async fn run_main_inner( if let Some(worktree) = managed_worktree.as_ref() { worktree.report_startup_failure(); } - drop(launch_telemetry); - if let Some(otel) = otel { - let _ = otel - .shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT) - .await; - } std::process::exit(1); } } @@ -868,12 +697,6 @@ pub(super) async fn run_main_inner( if let Some(worktree) = managed_worktree.as_ref() { worktree.report_startup_failure(); } - drop(launch_telemetry); - if let Some(otel) = otel { - let _ = otel - .shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT) - .await; - } std::process::exit(1); } } @@ -942,10 +765,6 @@ pub(super) async fn run_main_inner( .await?; } - let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); - - let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); - let log_db = state_db .clone() .map(|state_db| log_db::start(state_db, std::sync::Arc::new(feedback.clone()))); @@ -958,8 +777,6 @@ pub(super) async fn run_main_inner( .with(feedback_layer) .with(feedback_metadata_layer) .with(log_db_layer) - .with(otel_logger_layer) - .with(otel_tracing_layer) .try_init(); if let Err(err) = screen_reader_result { @@ -987,7 +804,6 @@ pub(super) async fn run_main_inner( managed_worktree.clone(), daemon_startup_warning, managed_daemon, - launch_telemetry, startup_draft, )) .await @@ -1000,33 +816,5 @@ pub(super) async fn run_main_inner( worktree.report_startup_failure(); } - // The TUI owns this request's consent. The child is silent; installation remains unconfirmed. - if let Ok(exit) = &app_result - && let Some(UpdateAction::Daemon(source)) = exit.update_action - && let Some(metrics) = otel.as_ref().and_then(codex_otel::OtelProvider::metrics) - { - let mut tags = daemon_settings.to_vec(); - tags.extend([ - ("initiation_source", "tui_handoff"), - ( - "update_target", - match source { - DaemonUpdateSource::PublicStable => "public_stable", - DaemonUpdateSource::ThisCli => "this_cli", - }, - ), - ("outcome", "handoff_requested"), - ]); - let _ = metrics.counter("codex.daemon.update", /*inc*/ 1, &tags); - } - - if let Some(otel) = otel - && let Err(err) = otel - .shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT) - .await - { - warn!(error = %err, "failed to finish interactive telemetry shutdown"); - } - app_result } diff --git a/codex-rs/tui/src/terminal_size_telemetry.rs b/codex-rs/tui/src/terminal_size_telemetry.rs deleted file mode 100644 index 2363561e..00000000 --- a/codex-rs/tui/src/terminal_size_telemetry.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! Shared terminal-cell buckets and best-effort observations using the existing metrics provider. - -use crate::legacy_core::config::Config; -use codex_config::types::OtelExporterKind; -use ratatui::layout::Size; - -pub(crate) type LaunchTags = Vec<(&'static str, &'static str)>; - -pub(crate) fn enabled(config: &Config) -> bool { - match config.otel.metrics_exporter { - // aKode: Statsig export is disabled; only user-configured OTLP exporters observe sizes. - OtelExporterKind::None | OtelExporterKind::Statsig => false, - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true, - } -} - -pub(crate) fn tags(size: Size) -> [(&'static str, &'static str); 2] { - // Keep values compatible with metrics tag validation; `<` and `+` are rejected. - let columns = match size.width { - 0 => "unknown", - 1..40 => "under-40", - 40..80 => "40-79", - 80..120 => "80-119", - 120..240 => "120-239", - 240..480 => "240-479", - 480.. => "480-and-up", - }; - let rows = match size.height { - 0 => "unknown", - 1..15 => "under-15", - 15..24 => "15-23", - 24..40 => "24-39", - 40..80 => "40-79", - 80..120 => "80-119", - 120.. => "120-and-up", - }; - [("terminal_columns", columns), ("terminal_rows", rows)] -} - -pub(crate) fn read_size() -> Size { - // On Unix, size() may synchronously spawn tput when the direct query fails. - #[cfg(unix)] - let size = crossterm::terminal::window_size().map(|size| Size::new(size.columns, size.rows)); - // Windows size() queries the console directly; window_size() is unsupported there. - #[cfg(not(unix))] - let size = crossterm::terminal::size().map(|(width, height)| Size::new(width, height)); - size.unwrap_or_default() -} - -pub(crate) fn record(context: &LaunchTags, config: &Config, reason: &'static str, size: Size) { - if !context.is_empty() - && let Some(metrics) = codex_otel::global() - { - let mut labels = context.clone(); - labels.extend(tags(size)); - labels.push(("observation_reason", reason)); - let _ = metrics.counter_with_analytics_consent( - "codex.tui.terminal_size", - /*inc*/ 1, - &labels, - config.analytics_enabled != Some(false), - ); - } -} diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 30002e85..3e654fb0 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -711,7 +711,6 @@ pub struct Tui { frame_requester: FrameRequester, draw_tx: broadcast::Sender<()>, pub(super) event_broker: Arc, - pub(crate) terminal_size_tags: crate::terminal_size_telemetry::LaunchTags, pub(crate) terminal: Terminal, pending_history_lines: Vec, clear_thread_switch_on_draw: bool, @@ -790,7 +789,6 @@ impl Tui { frame_requester, draw_tx, event_broker: Arc::new(event_broker), - terminal_size_tags: Vec::new(), terminal, pending_history_lines: vec![], clear_thread_switch_on_draw: false, @@ -953,6 +951,7 @@ impl Tui { } /// Reclaim terminal modes and stderr after a panic hook ran inside a recovery boundary. + #[cfg(test)] pub(crate) fn recover_after_caught_panic(&mut self) -> Result<()> { set_modes()?; self._stderr_guard.recover_after_caught_panic()?; diff --git a/codex-rs/tui/src/tui/terminal_stderr.rs b/codex-rs/tui/src/tui/terminal_stderr.rs index dc1f9502..8c6c04fb 100644 --- a/codex-rs/tui/src/tui/terminal_stderr.rs +++ b/codex-rs/tui/src/tui/terminal_stderr.rs @@ -54,6 +54,7 @@ impl TerminalStderrGuard { } /// Reclaim stderr after a caught panic temporarily restored terminal ownership. + #[cfg(test)] pub(super) fn recover_after_caught_panic(&mut self) -> io::Result<()> { if !self.active { return Ok(()); diff --git a/codex-rs/tui/src/worktree_startup.rs b/codex-rs/tui/src/worktree_startup.rs index 23238819..5cf677ad 100644 --- a/codex-rs/tui/src/worktree_startup.rs +++ b/codex-rs/tui/src/worktree_startup.rs @@ -151,8 +151,7 @@ pub(super) async fn prepare( )?; let state = init_state_db_for_app_server_target(&source, &AppServerTarget::Embedded).await?; - let mut lookup_config = source.clone(); - lookup_config.analytics_enabled = Some(false); + let lookup_config = source.clone(); let client = start_embedded_app_server( arg0_paths.clone(), lookup_config, diff --git a/codex-rs/tui/tests/suite/focus_palette.rs b/codex-rs/tui/tests/suite/focus_palette.rs index 62bd74fd..d7d39458 100644 --- a/codex-rs/tui/tests/suite/focus_palette.rs +++ b/codex-rs/tui/tests/suite/focus_palette.rs @@ -572,7 +572,7 @@ pub(super) fn write_test_config(codex_home: &Path, repo_root: &Path) -> Result<( let repo_root = repo_root.display(); let config = format!( "model = \"gpt-5.6-terra\"\nmodel_provider = \"openai\"\n\ - suppress_unstable_features_warning = true\nanalytics.enabled = false\n\ + suppress_unstable_features_warning = true\n\ features.daemon_auto_start = false\n\ notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\n\ [projects.\"{repo_root}\"]\ntrust_level = \"trusted\"\n" diff --git a/codex-rs/tui/tests/suite/resize_reflow.rs b/codex-rs/tui/tests/suite/resize_reflow.rs index 2738c8a8..63e15800 100644 --- a/codex-rs/tui/tests/suite/resize_reflow.rs +++ b/codex-rs/tui/tests/suite/resize_reflow.rs @@ -58,8 +58,6 @@ async fn tmux_split_preserves_fresh_session_composer_row_after_resize_reflow() - .arg(format!("CODEX_HOME={}", codex_home.path().display())) .arg("OPENAI_API_KEY=dummy") .arg(codex) - .arg("-c") - .arg("analytics.enabled=false") .arg("--no-alt-screen") .arg("-C") .arg(&repo_root) @@ -222,8 +220,6 @@ async fn tmux_width_resize_restore_keeps_visible_content_anchored() -> Result<() .arg(format!("CODEX_HOME={}", codex_home.path().display())) .arg("OPENAI_API_KEY=dummy") .arg(codex) - .arg("-c") - .arg("analytics.enabled=false") .arg("--no-alt-screen") .arg("-C") .arg(&repo_root) @@ -350,8 +346,6 @@ async fn tmux_scrolled_composer_resize_preserves_visible_draft_text() -> Result< .arg(codex) .arg("--model") .arg("gpt-5.6-terra") - .arg("-c") - .arg("analytics.enabled=false") .arg("--no-alt-screen") .arg("-C") .arg(&repo_root), @@ -473,8 +467,6 @@ async fn run_repeated_resize_smoke() -> Result<()> { .arg(format!("CODEX_HOME={}", codex_home.path().display())) .arg("OPENAI_API_KEY=dummy") .arg(codex) - .arg("-c") - .arg("analytics.enabled=false") .arg("--no-alt-screen") .arg("-C") .arg(&repo_root) diff --git a/codex-rs/windows-sandbox-rs/src/setup.rs b/codex-rs/windows-sandbox-rs/src/setup.rs index 7c9cd636..404fb89a 100644 --- a/codex-rs/windows-sandbox-rs/src/setup.rs +++ b/codex-rs/windows-sandbox-rs/src/setup.rs @@ -358,7 +358,6 @@ fn run_setup_refresh_inner( deny_write_paths, proxy_ports: offline_proxy_settings.proxy_ports, allow_local_binding: offline_proxy_settings.allow_local_binding, - otel: None, real_user: crate::runtime_ownership::current_setup_user()?, user_profile: std::env::var_os("USERPROFILE") .filter(|value| !value.is_empty()) @@ -720,7 +719,6 @@ struct ElevationPayload { proxy_ports: Vec, #[serde(default)] allow_local_binding: bool, - otel: Option, real_user: String, #[serde(skip_serializing_if = "Option::is_none")] user_profile: Option, @@ -1171,7 +1169,6 @@ fn elevated_provisioning_payload( proxy_ports: offline_proxy_settings.proxy_ports, allow_local_binding: offline_proxy_settings.allow_local_binding, real_user, - otel: codex_otel::global_statsig_metrics_settings(), user_profile: None, mode: SetupMode::InteractiveProvision, runtime: SetupRuntime::Legacy, @@ -1251,7 +1248,6 @@ pub fn run_elevated_provisioning_setup_with_retained_handles( deny_write_paths: Vec::new(), proxy_ports: settings.proxy_ports, allow_local_binding: settings.allow_local_binding, - otel: codex_otel::global_statsig_metrics_settings(), real_user: real_user.to_string(), user_profile: std::env::var_os("USERPROFILE") .filter(|value| !value.is_empty()) diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs index ba93bfac..9864499a 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs @@ -47,7 +47,6 @@ use anyhow::Context; use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; -use codex_otel::StatsigMetricsSettings; use serde::Deserialize; use serde::Serialize; use std::collections::HashSet; @@ -123,8 +122,6 @@ struct Payload { proxy_ports: Vec, #[serde(default)] allow_local_binding: bool, - #[serde(default)] - otel: Option, real_user: String, #[serde(default)] user_profile: Option, @@ -761,14 +758,9 @@ fn provision_sandbox(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> })?; let offline_sid_str = string_from_sid_bytes(&offline_sid).map_err(anyhow::Error::msg)?; configure_offline_sandbox_network(payload, &offline_sid_str, log)?; - let wfp_result = install_wfp_filters( - &payload.codex_home, - &payload.offline_username, - payload.otel.as_ref(), - |message| { - let _ = log_line(log, message); - }, - ); + let wfp_result = install_wfp_filters(&payload.offline_username, |message| { + let _ = log_line(log, message); + }); if repairing_disabled_accounts { // Ordinary setup keeps its best-effort WFP behavior. Recovery must not reopen logons // after cleanup removed protections unless restoring those protections succeeded. @@ -1236,7 +1228,6 @@ mod tests { use crate::path_mask_allows; use crate::path_write_aces_need_refresh; use crate::workspace_write_cap_sid_for_root; - use codex_otel::StatsigMetricsSettings; use pretty_assertions::assert_eq; use serde_json::json; use std::fs; @@ -1258,13 +1249,6 @@ mod tests { }) } - #[test] - fn payload_defaults_otel_absent() { - let payload: Payload = serde_json::from_value(payload_json()).expect("payload"); - - assert_eq!(payload.otel, None); - } - #[test] fn payload_accepts_provision_only_mode() { let mut payload = payload_json(); @@ -1284,19 +1268,14 @@ mod tests { } #[test] - fn payload_accepts_otel_settings() { + fn payload_ignores_legacy_telemetry_settings() { let mut payload = payload_json(); payload["otel"] = json!({ "environment": "prod", }); let payload: Payload = serde_json::from_value(payload).expect("payload"); - assert_eq!( - payload.otel, - Some(StatsigMetricsSettings { - environment: "prod".to_string(), - }) - ); + assert_eq!(payload.offline_username, "CodexSandboxOffline"); } #[test] diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning/service.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/service.rs index f0c5ddcd..5079bbdc 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_provisioning/service.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/service.rs @@ -32,7 +32,6 @@ pub fn provision_sandbox_in_process( deny_write_paths: Vec::new(), proxy_ports: settings.proxy_ports, allow_local_binding: settings.allow_local_binding, - otel: codex_otel::global_statsig_metrics_settings(), real_user: real_user.to_string(), user_profile: None, mode: SetupMode::ProvisionOnly, diff --git a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs index 3cdc7d75..6e142a25 100644 --- a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs +++ b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs @@ -1,30 +1,5 @@ use crate::install_wfp_filters_for_account; -use crate::setup_error::sanitize_setup_metric_tag_value; use anyhow::Result; -use codex_otel::OtelExporter; -use codex_otel::OtelProvider; -use codex_otel::OtelSettings; -use codex_otel::StatsigMetricsSettings; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::Path; - -const WFP_SETUP_SERVICE_NAME: &str = "codex-windows-sandbox-setup"; -const WFP_SETUP_SUCCESS_METRIC: &str = "codex.windows_sandbox.wfp_setup_success"; -const WFP_SETUP_FAILURE_METRIC: &str = "codex.windows_sandbox.wfp_setup_failure"; - -#[derive(Debug, Clone, Copy)] -enum WfpSetupMetricOutcome { - Success, - Failure, -} - -struct WfpSetupMetric { - outcome: WfpSetupMetricOutcome, - target_account: String, - installed_filter_count: usize, - error: Option, -} fn panic_payload_to_string(panic_payload: Box) -> String { match panic_payload.downcast::() { @@ -36,146 +11,35 @@ fn panic_payload_to_string(panic_payload: Box) -> Stri } } -fn build_wfp_metrics_provider( - codex_home: &Path, - otel: Option<&StatsigMetricsSettings>, -) -> Result> { - let Some(otel) = otel else { - return Ok(None); - }; - // The setup helper cannot call codex-core's OTEL builder because core - // depends on this crate, so the parent process passes only the resolved - // Statsig environment in the elevation payload. Other exporters are - // intentionally omitted from this helper path. - OtelProvider::try_new(&OtelSettings { - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: otel.environment.clone(), - service_name: WFP_SETUP_SERVICE_NAME.to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: codex_home.to_path_buf(), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::Statsig, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .map_err(|err| anyhow::anyhow!("failed to initialize WFP setup metrics provider: {err}")) -} - -fn emit_wfp_setup_metric( - codex_home: &Path, - otel: Option<&StatsigMetricsSettings>, - metric: &WfpSetupMetric, -) -> Result<()> { - let Some(provider) = build_wfp_metrics_provider(codex_home, otel)? else { - return Ok(()); - }; - if let Some(metrics) = provider.metrics() { - let target_account = sanitize_setup_metric_tag_value(&metric.target_account); - match metric.outcome { - WfpSetupMetricOutcome::Success => { - let installed_filter_count = metric.installed_filter_count.to_string(); - metrics.counter( - WFP_SETUP_SUCCESS_METRIC, - /*inc*/ 1, - &[ - ("target_account", target_account.as_str()), - ("installed_filter_count", installed_filter_count.as_str()), - ], - )?; - } - WfpSetupMetricOutcome::Failure => { - let mut tags = vec![("target_account", target_account.as_str())]; - let error_tag = metric.error.as_deref().map(sanitize_setup_metric_tag_value); - if let Some(error) = error_tag.as_deref() { - tags.push(("message", error)); - } - metrics.counter(WFP_SETUP_FAILURE_METRIC, /*inc*/ 1, &tags)?; - } - } - } - provider.shutdown(); - Ok(()) -} - -fn emit_wfp_setup_metric_safely( - codex_home: &Path, - otel: Option<&StatsigMetricsSettings>, - offline_username: &str, - metric: &WfpSetupMetric, - log: &mut F, -) where - F: FnMut(&str), -{ - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - emit_wfp_setup_metric(codex_home, otel, metric) - })); - match result { - Ok(Ok(())) => {} - Ok(Err(err)) => log(&format!( - "failed to emit WFP setup metric for {offline_username}: {err}" - )), - Err(panic_payload) => { - let error = panic_payload_to_string(panic_payload); - log(&format!( - "WFP setup metric emission panicked for {offline_username}: {error}" - )); - } - } -} - -pub fn install_wfp_filters( - codex_home: &Path, - offline_username: &str, - otel: Option<&StatsigMetricsSettings>, - mut log: F, -) -> Result<()> +/// Installs WFP filters for the offline sandbox account. Outcomes are logged locally only. +pub fn install_wfp_filters(offline_username: &str, mut log: F) -> Result<()> where F: FnMut(&str), { - let metric = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let outcome = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { install_wfp_filters_for_account(offline_username) })) { Ok(Ok(installed_filter_count)) => { log(&format!( "WFP setup succeeded for {offline_username} with {installed_filter_count} installed filters" )); - WfpSetupMetric { - outcome: WfpSetupMetricOutcome::Success, - target_account: offline_username.to_string(), - installed_filter_count, - error: None, - } + None } Ok(Err(err)) => { let error = err.to_string(); log(&format!("WFP setup failed for {offline_username}: {error}")); - WfpSetupMetric { - outcome: WfpSetupMetricOutcome::Failure, - target_account: offline_username.to_string(), - installed_filter_count: 0, - error: Some(error), - } + Some(error) } Err(panic_payload) => { let error = panic_payload_to_string(panic_payload); log(&format!( "WFP setup panicked for {offline_username}: {error}" )); - WfpSetupMetric { - outcome: WfpSetupMetricOutcome::Failure, - target_account: offline_username.to_string(), - installed_filter_count: 0, - error: Some(format!("panic: {error}")), - } + Some(format!("panic: {error}")) } }; - emit_wfp_setup_metric_safely(codex_home, otel, offline_username, &metric, &mut log); - match metric.error { + match outcome { Some(error) => Err(anyhow::anyhow!(error)), None => Ok(()), } diff --git a/sdk/python/src/openai_codex/generated/v2_all.py b/sdk/python/src/openai_codex/generated/v2_all.py index d6cbadd3..6b02d228 100644 --- a/sdk/python/src/openai_codex/generated/v2_all.py +++ b/sdk/python/src/openai_codex/generated/v2_all.py @@ -202,14 +202,6 @@ class AllowDenyRequirement(Enum): deny = "deny" -class AnalyticsConfig(BaseModel): - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - ) - enabled: bool | None = None - - class AppBranding(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -1457,32 +1449,6 @@ class FeedbackRequirements(BaseModel): enabled: bool | None = None -class FeedbackUploadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - classification: str - extra_log_files: Annotated[list[str] | None, Field(alias="extraLogFiles")] = None - include_logs: Annotated[bool | None, Field(alias="includeLogs")] = None - reason: str | None = None - tags: dict[str, Any] | None = None - thread_id: Annotated[str | None, Field(alias="threadId")] = None - - -class FeedbackUploadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - prompt_hash: Annotated[ - str | None, - Field( - alias="promptHash", - description="Whitespace-normalized SHA-256 of the session base instructions, matching the uploaded `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - - class FileChangeOutputDeltaNotification(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -3172,25 +3138,6 @@ class NullableGetAccountTokenUsageParams(RootModel[GetAccountTokenUsageParams | ] -class OtelExporterValue(Enum): - none = "none" - statsig = "statsig" - - -class OtelHttpProtocol(Enum): - binary = "binary" - json = "json" - - -class OtelTlsConfig(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - ca_certificate: Annotated[str | None, Field(alias="ca-certificate")] = None - client_certificate: Annotated[str | None, Field(alias="client-certificate")] = None - client_private_key: Annotated[str | None, Field(alias="client-private-key")] = None - - class OtelToolResultLogConfig(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -8255,15 +8202,6 @@ class AccountSendAddCreditsNudgeEmailRequest(BaseModel): params: SendAddCreditsNudgeEmailParams -class FeedbackUploadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["feedback/upload"], Field(title="Feedback/uploadRequestMethod")] - params: FeedbackUploadParams - - class CommandExecWriteRequest(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -8829,7 +8767,7 @@ class FeedbackSaveResponse(BaseModel): str | None, Field( alias="promptHash", - description="Same prompt hash as feedback/upload; null when prompt metadata is absent.", + description="Whitespace-normalized SHA-256 of the session base instructions, matching the saved `prompt_hash` tag. Does not include later developer messages. Null when the reported rollout has no prompt metadata.", ), ] = None saved_path: Annotated[LegacyAppPathString, Field(alias="savedPath")] @@ -9568,66 +9506,13 @@ class NewThreadModelDefaults(BaseModel): service_tier: Annotated[str | None, Field(alias="serviceTier")] = None -class OtlpHttp(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - endpoint: str - headers: Annotated[ - dict[str, str], - Field(description="Header names are retained; values are redacted by the server."), - ] - protocol: OtelHttpProtocol - tls: OtelTlsConfig | None = None - - -class OtlpHttpOtelExporter(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - otlp_http: Annotated[OtlpHttp, Field(alias="otlp-http")] - - -class OtlpGrpc(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - endpoint: str - headers: Annotated[ - dict[str, str], - Field(description="Header names are retained; values are redacted by the server."), - ] - tls: OtelTlsConfig | None = None - - -class OtlpGrpcOtelExporter(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - otlp_grpc: Annotated[OtlpGrpc, Field(alias="otlp-grpc")] - - -class OtelExporter(RootModel[OtelExporterValue | OtlpHttpOtelExporter | OtlpGrpcOtelExporter]): - root: OtelExporterValue | OtlpHttpOtelExporter | OtlpGrpcOtelExporter - - class OtelRequirements(BaseModel): model_config = ConfigDict( populate_by_name=True, ) - environment: str | None = None - exporter: OtelExporter | None = None - log_agent_responses: bool | None = None - log_guardian_assessments: bool | None = None log_sse_deltas: bool | None = None log_user_prompt: bool | None = None - metrics_exporter: OtelExporter | None = None - span_attributes: dict[str, Any] | None = None tool_result: OtelToolResultLogConfig | None = None - trace_exporter: OtelExporter | None = None - tracestate: dict[str, Any] | None = None class OverriddenMetadata(BaseModel): @@ -10675,7 +10560,7 @@ class ThreadForkParams(BaseModel): ThreadSource | None, Field( alias="threadSource", - description="Optional client-supplied analytics source classification for this forked thread.", + description="Optional client-supplied source classification for this forked thread.", ), ] = None @@ -11286,7 +11171,7 @@ class ThreadStartParams(BaseModel): ThreadSource | None, Field( alias="threadSource", - description="Optional client-supplied analytics source classification for this thread.", + description="Optional client-supplied source classification for this thread.", ), ] = None @@ -11719,7 +11604,6 @@ class Config(BaseModel): extra="allow", populate_by_name=True, ) - analytics: AnalyticsConfig | None = None approval_policy: AskForApproval | None = None approvals_reviewer: Annotated[ ApprovalsReviewer | None, @@ -12912,7 +12796,7 @@ class ExternalAgentConfigImportParams(BaseModel): str | None, Field( alias="providerId", - description="Opaque provider identifier supplied by the caller for analytics attribution and import history display. This does not select the migration source.", + description="Opaque provider identifier supplied by the caller for attribution and import history display. This does not select the migration source.", ), ] = None source: Annotated[ @@ -13259,10 +13143,7 @@ class Thread(BaseModel): status: Annotated[ThreadStatus, Field(description="Current runtime status for the thread.")] thread_source: Annotated[ ThreadSource | None, - Field( - alias="threadSource", - description="Optional analytics source classification for this thread.", - ), + Field(alias="threadSource", description="Optional source classification for this thread."), ] = None turns: Annotated[ list[Turn], @@ -13756,7 +13637,6 @@ class ClientRequest( | AccountUsageReadRequest | AccountWorkspaceMessagesReadRequest | AccountSendAddCreditsNudgeEmailRequest - | FeedbackUploadRequest | FeedbackSaveRequest | CommandExecRequest | CommandExecWriteRequest @@ -13868,7 +13748,6 @@ class ClientRequest( | AccountUsageReadRequest | AccountWorkspaceMessagesReadRequest | AccountSendAddCreditsNudgeEmailRequest - | FeedbackUploadRequest | FeedbackSaveRequest | CommandExecRequest | CommandExecWriteRequest