Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
[advisories]
# Reviewed 2026-07-02. Keep this list in sync with ../deny.toml.
ignore = [
"RUSTSEC-2024-0388", # derivative 2.2.0 via starlark/starlark_syntax; upstream crate is unmaintained
"RUSTSEC-2024-0449", # unsafe-libyaml via serde_yaml in skills, ext/skills, core-plugins, external-agent-migration; remove when migrated off serde_yaml/unsafe-libyaml
"RUSTSEC-2025-0057", # fxhash 0.2.1 via starlark_map/bm25; upstream crate is unmaintained
"RUSTSEC-2024-0436", # paste 1.0.15 via starlark/v8; upstream crate is unmaintained
"RUSTSEC-2023-0089", # atomic-polyfill via postcard/heapless/pagable; upstream crate is unmaintained
"RUSTSEC-2024-0320", # yaml-rust via syntect; remove when syntect drops or updates it
"RUSTSEC-2025-0141", # bincode via syntect; remove when syntect drops or updates it
"RUSTSEC-2026-0118", # hickory-proto via rama-dns/rama-tcp; remove when rama updates to hickory 0.26.1 or hickory-net
"RUSTSEC-2026-0119", # hickory-proto via rama-dns/rama-tcp; remove when rama updates to hickory 0.26.1 or hickory-net
"RUSTSEC-2026-0194", # quick-xml via plist/syntect and wayland-scanner; trusted inputs only; remove when rust-plist#191 and wayland-rs#938 are released
"RUSTSEC-2026-0195", # quick-xml via plist/syntect and wayland-scanner; trusted inputs only; remove when rust-plist#191 and wayland-rs#938 are released
"RUSTSEC-2026-0370", # zvariant 4.2.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
"RUSTSEC-2026-0371", # zbus_names 3.0.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
"RUSTSEC-2026-0372", # zvariant_derive 4.2.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
# Reviewed 2026-10-20.
"RUSTSEC-2026-0374", # basic-toml 0.1.10 via i18n-config/i18n-embed-fl under age 0.12.1 in codex-secrets; no patched release; remove when age's localization dependencies migrate off basic-toml
"RUSTSEC-2026-0387", # crypto-bigint 0.5.5 via elliptic-curve 0.13.8 is used by age, AWS login, user verification, and WebRTC; timing leakage can affect private-key or session-secret operations; remove when these dependency paths use crypto-bigint >=0.7.6
# Reviewed 2026-10-26.
"RUSTSEC-2026-0391", # Codex, tonic and zip use zstd 0.13.3 without reusing borrowed contexts across streams. Remove when all paths use zstd >=0.14.3.
"RUSTSEC-2026-0398", # zstd 0.13.3 pulls in zstd-safe 7.2.4 with the affected seekable feature disabled. Remove when all paths use zstd-safe >=8.2.0.
"RUSTSEC-2026-0403", # zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0.
"RUSTSEC-2026-0410", # zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2.
# Reviewed 2026-10-29.
"RUSTSEC-2026-0418", # libz-sys 1.1.29 via curl-sys/curl in codex-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0.
# Reviewed 2026-11-05.
"RUSTSEC-2026-0441", # pin-utils 0.1.0 via AWS Smithy and loom under tokio-graceful; unmaintained with no patched release; remove when these paths drop pin-utils
]

View File

@@ -0,0 +1,21 @@
[env]
# Roughly one arena per four CPUs reduces idle RSS after Linux musl conversations unload.
JEMALLOC_SYS_WITH_MALLOC_CONF = "narenas_ratio:0.25"
# curl-sys enables its NTLM sources but does not set the flag required by libcurl 8.21.
CFLAGS_aarch64_pc_windows_gnullvm = "-DCURL_ENABLE_NTLM"
CFLAGS_aarch64_pc_windows_msvc = "-DCURL_ENABLE_NTLM"
CFLAGS_x86_64_pc_windows_gnullvm = "-DCURL_ENABLE_NTLM"
CFLAGS_x86_64_pc_windows_msvc = "-DCURL_ENABLE_NTLM"
[target.'cfg(all(windows, target_env = "msvc"))']
rustflags = ["-C", "link-arg=/STACK:8388608", "-C", "target-feature=+crt-static"]
# MSVC emits a warning about code that may trip "Cortex-A53 MPCore processor bug #843419" (see
# https://developer.arm.com/documentation/epm048406/latest) which is sometimes emitted by LLVM.
# Since Arm64 Windows 10+ isn't supported on that processor, it's safe to disable the warning.
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608", "-C", "link-arg=/arm64hazardfree"]
[target.'cfg(all(windows, target_env = "gnu"))']
rustflags = ["-C", "link-arg=-Wl,--stack,8388608"]

View File

@@ -0,0 +1,120 @@
[profile.default]
# Retry once so one transient failure does not fail full-CI outright.
# Fanout keeps the full-CI shards moving without treating every >30s test as
# stuck. Keep this aligned with the broader timeout budget we give sharded CI.
slow-timeout = { period = "30s", terminate-after = 2 }
retries = 1
[[profile.default.overrides]]
# These cases cold-start a daemon before confirming a second launch with new settings.
filter = 'package(codex-cli) & binary(daemon_startup) & test(requires_confirmation_to_disable_)'
slow-timeout = { period = "1m", terminate-after = 2 }
[[profile.default.overrides]]
# This case validates and copies both the initial and replacement debug package.
filter = 'package(codex-cli) & binary(=app_server_daemon_package) & test(=packaged_daemon_start_and_explicit_replacement)'
slow-timeout = { period = "1m", terminate-after = 3 }
threads-required = "num-test-threads"
[[profile.default.overrides]]
# These copies must not compete with other tests on the same runner.
filter = 'package(codex-cli) & binary(=app_server_daemon_package)'
slow-timeout = { period = "1m", terminate-after = 2 }
threads-required = "num-test-threads"
[profile.default.junit]
path = "junit.xml"
[profile.local]
inherits = "default"
[test-groups.app_server_protocol_codegen]
max-threads = 1
[test-groups.app_server_integration]
max-threads = 1
# Higher concurrency causes integration test timeouts under resource contention
# on common developer machines.
[test-groups.app_server_integration_local]
max-threads = 4
[test-groups.core_apply_patch_cli_integration]
max-threads = 1
[test-groups.windows_sandbox_legacy_sessions]
max-threads = 1
[test-groups.windows_sandbox_accounts]
max-threads = 1
[test-groups.windows_process_heavy]
max-threads = 2
[[profile.default.overrides]]
# Do not add new tests here
filter = 'test(rmcp_client) | test(humanlike_typing_1000_chars_appears_live_no_placeholder)'
slow-timeout = { period = "1m", terminate-after = 4 }
[[profile.default.overrides]]
# This end-to-end case launches several CLI subprocesses and checks cloud policy.
filter = 'package(codex-exec) & test(worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume)'
slow-timeout = { period = "30s", terminate-after = 4 }
[[profile.default.overrides]]
filter = 'test(approval_matrix_covers_all_modes)'
slow-timeout = { period = "30s", terminate-after = 2 }
[[profile.default.overrides]]
filter = 'package(codex-app-server-protocol) & (test(typescript_schema_fixtures_match_generated) | test(json_schema_fixtures_match_generated) | test(generate_ts_with_experimental_api_retains_experimental_entries) | test(generated_ts_optional_nullable_fields_only_in_params) | test(generate_json_filters_experimental_fields_and_methods))'
test-group = 'app_server_protocol_codegen'
[[profile.default.overrides]]
# These integration tests spawn a fresh app-server subprocess per case.
# Keep the library unit tests parallel.
filter = 'package(codex-app-server) & kind(test)'
test-group = 'app_server_integration'
[[profile.local.overrides]]
# Use up to four app-server subprocesses locally. The global nextest pool still
# limits this to the machine's logical CPU count.
filter = 'package(codex-app-server) & kind(test)'
test-group = 'app_server_integration_local'
[[profile.default.overrides]]
# These tests exercise full Codex turns and apply_patch execution, and they are
# sensitive to Windows runner process-startup stalls when many cases launch at once.
filter = 'package(codex-core) & kind(test) & test(apply_patch_cli)'
test-group = 'core_apply_patch_cli_integration'
[[profile.default.overrides]]
# These cases share the runner's elevated sandbox accounts. Queue them before
# starting their timeout; their file lock still coordinates other test processes.
platform = 'cfg(windows)'
filter = '''
(package(codex-core) & binary(windows_sandbox)) |
(package(codex-exec-server) & test(file_system_elevated_relative_read_denial_uses_policy_cwd)) |
(package(codex-windows-sandbox) & test(elevated_non_tty_cmd_forwards_env_output_and_exit))
'''
test-group = 'windows_sandbox_accounts'
[[profile.default.overrides]]
# These tests create restricted-token Windows child processes and private desktops.
# Serialize them to avoid exhausting Windows session/global desktop resources in CI.
filter = 'package(codex-windows-sandbox) & test(legacy_)'
test-group = 'windows_sandbox_legacy_sessions'
[[profile.default.overrides]]
# This Codex-home startup path still exceeded the broader Windows-heavy ceiling
# in both Windows full-CI lanes after contention was reduced.
platform = 'cfg(windows)'
filter = 'test(start_thread_uses_all_default_environments_from_codex_home)'
slow-timeout = { period = "1m", terminate-after = 2 }
[[profile.default.overrides]]
# These Windows-heavy tests spawn subprocesses, session files, or JSON-RPC
# clients and have been the dominant source of 30s full-CI timeouts.
platform = 'cfg(windows)'
filter = 'test(suite::resume::) | test(suite::cli_stream::) | test(suite::auth_env::) | test(start_thread_uses_all_default_environments_from_codex_home) | test(connect_stdio_command_initializes_json_rpc_client_on_windows)'
test-group = 'windows_process_heavy'
slow-timeout = { period = "45s", terminate-after = 2 }

2
codex-rs/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/target/
/target-*/

108
codex-rs/BUILD.bazel Normal file
View File

@@ -0,0 +1,108 @@
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
load("//bazel/rules:runtime_package.bzl", "runtime_archive")
exports_files([
"clippy.toml",
])
filegroup(
name = "workspace-files",
srcs = glob(
[
"*",
".cargo/**",
],
exclude = [
"BUILD.bazel",
],
),
visibility = ["//visibility:public"],
)
test_suite(
name = "e2e-benchmarks",
tags = ["manual"],
tests = [
"//codex-rs/cli:codex-help-bench",
],
visibility = ["//visibility:public"],
)
string_flag(
name = "runtime_package_build_mode",
build_setting_default = "release",
values = [
"release",
"debug",
],
visibility = ["//visibility:public"],
)
alias(
name = "runtime_package",
actual = ":runtime_package_combined",
tags = ["manual"],
visibility = ["//visibility:public"],
)
# These targets produce flat staging archives for the existing signing and
# packaging steps. Release builds retain their binaries and debug symbols.
runtime_archive(
name = "runtime_package_combined",
srcs = [
"//codex-rs/app-server:release_files",
"//codex-rs/cli:release_files",
"//codex-rs/code-mode-host:release_files",
"//codex-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//codex-rs/bwrap:release_files"],
"@platforms//os:windows": [
"//codex-rs/windows-sandbox-rs:command-runner-release_files",
"//codex-rs/windows-sandbox-rs:sandbox-setup-release_files",
],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_primary",
srcs = [
"//codex-rs/cli:release_files",
"//codex-rs/code-mode-host:release_files",
"//codex-rs/exec-server-cli:release_files",
"//codex-rs/responses-api-proxy:release_files",
] + select({
"@platforms//os:linux": ["//codex-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_app-server",
srcs = [
"//codex-rs/app-server:release_files",
"//codex-rs/code-mode-host:release_files",
"//codex-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//codex-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_helpers",
srcs = [
"//codex-rs/windows-sandbox-rs:command-runner-release_files",
"//codex-rs/windows-sandbox-rs:sandbox-setup-release_files",
"//codex-rs/windows-sandbox-service:release_files",
],
tags = ["manual"],
target_compatible_with = ["@platforms//os:windows"],
visibility = ["//visibility:public"],
)

18440
codex-rs/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

691
codex-rs/Cargo.toml Normal file
View File

@@ -0,0 +1,691 @@
[workspace]
members = [
"aws-auth",
"analytics",
"agent-graph-store",
"agent-message-board-client",
"agent-message-board-host",
"agent-identity",
"agent-roles",
"backend-client",
"cloud-client",
"bwrap",
"build-info",
"ansi-escape",
"attachment-store",
"async-utils",
"app-server",
"app-server-transport",
"app-server-daemon",
"app-server-client",
"app-server-protocol",
"app-server-protocol-noop-macros",
"app-server-test-client",
"apply-patch",
"arg0",
"feedback",
"features",
"install-context",
"codex-backend-openapi-models",
"code-mode",
"code-mode-host",
"code-mode-protocol",
"code-mode-runtime",
"plugin-host",
"codex-home",
"cloud-config",
"cloud-tasks",
"cloud-tasks-client",
"cloud-tasks-mock-client",
"cli",
"collaboration-mode-templates",
"connectors",
"config",
"config-schema",
"context-fragments",
"shell-command",
"skills",
"core",
"core-api",
"core-plugin-common",
"core-plugins",
"diagnostics",
"direct-tool-timing",
"guardian-context",
"hooks",
"history",
"http-client",
"secrets",
"exec",
"file-system",
"exec-server-protocol",
"exec-server",
"exec-server-cli",
"exec-server/tests/support",
"execpolicy",
"ext/agent",
"ext/agent-message-board",
"ext/connectors",
"ext/extension-api",
"ext/multi-env-copy-file",
"ext/goal",
"ext/git-attribution",
"ext/guardian-reviewer",
"ext/guardian-v2",
"ext/guardian-v3",
"ext/history-notes",
"ext/image-generation",
"ext/items",
"ext/memories",
"ext/mcp",
"ext/queue",
"ext/skills",
"ext/web-search",
"external-agent-migration",
"keyring-store",
"file-search",
"file-watcher",
"linux-sandbox",
"lmstudio",
"login",
"codex-mcp",
"memories/read",
"memories/write",
"mermaid",
"message-board",
"message-board-mcp",
"model-provider-info",
"mxc-sandbox",
"models-manager",
"network-proxy",
"ollama",
"process-hardening",
"realtime-webrtc",
"voice-host",
"protocol",
"protocol/tests/support",
"prompts",
"rollout",
"rollout-trace",
"rmcp-client",
"responses-api-proxy",
"runtime-agent-instance",
"response-debug-context",
"sandboxing",
"stdio-to-uds",
"otel",
"otel-trace-websocket",
"tcp-tunnel",
"tui",
"user-verification",
"tools",
"v8-poc",
"websocket-auth",
"websocket-client",
"windows-sandbox-rs/tests/support",
"windows-sandbox-service",
"worktree",
"workload-identity",
"utils/absolute-path",
"utils/audio",
"utils/path-uri",
"utils/cargo-bin",
"git-utils",
"utils/cache",
"utils/critical-path",
"utils/git-discovery",
"utils/head-tail-buffer",
"utils/image",
"utils/json-to-toml",
"utils/home-dir",
"utils/process",
"utils/pty",
"utils/readiness",
"utils/redacted-string",
"utils/rustls-provider",
"utils/string",
"utils/cli",
"utils/elapsed",
"utils/sandbox-summary",
"utils/model-facing-id",
"utils/sleep-inhibitor",
"utils/approval-presets",
"utils/oss",
"utils/output-truncation",
"utils/path-utils",
"utils/plugins",
"utils/fuzzy-match",
"utils/stream-parser",
"utils/template",
"codex-client",
"codex-api",
"state",
"terminal-detection",
"test-binary-support",
"thread-manager-sample",
"thread-store",
"uds",
"codex-experimental-api-macros",
"plugin",
"model-provider",
]
resolver = "2"
[workspace.package]
version = "0.0.0"
# Track the edition for all workspace crates in one place. Individual
# crates can still override this value, but keeping it here means new
# crates created with `cargo new -w ...` automatically inherit the 2024
# edition.
edition = "2024"
license = "Apache-2.0"
[workspace.dependencies]
# 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" }
codex-ansi-escape = { path = "ansi-escape" }
codex-api = { path = "codex-api" }
codex-attachment-store = { path = "attachment-store" }
codex-aws-auth = { path = "aws-auth" }
codex-app-server = { path = "app-server" }
codex-app-server-transport = { path = "app-server-transport" }
codex-app-server-daemon = { path = "app-server-daemon" }
codex-app-server-client = { path = "app-server-client" }
codex-app-server-protocol = { path = "app-server-protocol" }
codex-app-server-protocol-noop-macros = { path = "app-server-protocol-noop-macros" }
codex-app-server-test-client = { path = "app-server-test-client" }
codex-apply-patch = { path = "apply-patch" }
codex-arg0 = { path = "arg0" }
codex-async-utils = { path = "async-utils" }
codex-backend-client = { path = "backend-client" }
codex-build-info = { path = "build-info" }
codex-chatgpt = { path = "chatgpt" }
codex-client = { path = "codex-client" }
codex-collaboration-mode-templates = { path = "collaboration-mode-templates" }
codex-cloud-config = { path = "cloud-config" }
codex-cloud-tasks-client = { path = "cloud-tasks-client" }
codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" }
codex-code-mode = { path = "code-mode" }
codex-code-mode-protocol = { path = "code-mode-protocol" }
codex-code-mode-runtime = { path = "code-mode-runtime" }
codex-plugin-host = { path = "plugin-host" }
codex-home = { path = "codex-home" }
codex-http-client = { path = "http-client" }
codex-websocket-auth = { path = "websocket-auth" }
codex-websocket-client = { path = "websocket-client" }
codex-config = { path = "config" }
codex-connectors = { path = "connectors" }
codex-agent-message-board-client = { path = "agent-message-board-client" }
codex-agent-message-board-extension = { path = "ext/agent-message-board" }
codex-agent-message-board-host = { path = "agent-message-board-host" }
codex-message-board = { path = "message-board" }
codex-message-board-mcp = { path = "message-board-mcp" }
codex-connectors-extension = { path = "ext/connectors" }
codex-context-fragments = { path = "context-fragments" }
codex-core = { path = "core" }
codex-core-api = { path = "core-api" }
codex-core-plugin-common = { path = "core-plugin-common" }
codex-core-plugins = { path = "core-plugins" }
codex-diagnostics = { path = "diagnostics" }
codex-direct-tool-timing = { path = "direct-tool-timing" }
codex-exec = { path = "exec" }
codex-file-system = { path = "file-system" }
codex-exec-server-protocol = { path = "exec-server-protocol" }
codex-exec-server = { path = "exec-server" }
codex-exec-server-cli = { path = "exec-server-cli" }
codex-exec-server-test-support = { path = "exec-server/tests/support" }
codex-execpolicy = { path = "execpolicy" }
codex-extension-api = { path = "ext/extension-api" }
codex-extension-items = { path = "ext/items" }
codex-multi-env-copy-file = { path = "ext/multi-env-copy-file" }
codex-goal-extension = { path = "ext/goal" }
codex-git-attribution = { path = "ext/git-attribution" }
codex-guardian-reviewer = { path = "ext/guardian-reviewer" }
codex-guardian-v2 = { path = "ext/guardian-v2" }
codex-guardian-v3 = { path = "ext/guardian-v3" }
codex-history-notes-extension = { path = "ext/history-notes" }
codex-image-generation-extension = { path = "ext/image-generation" }
codex-external-agent-migration = { path = "external-agent-migration" }
codex-experimental-api-macros = { path = "codex-experimental-api-macros" }
codex-features = { path = "features" }
codex-feedback = { path = "feedback" }
codex-install-context = { path = "install-context" }
codex-file-search = { path = "file-search" }
codex-file-watcher = { path = "file-watcher" }
codex-git-utils = { path = "git-utils" }
codex-guardian-context = { path = "guardian-context" }
codex-hooks = { path = "hooks" }
codex-history = { path = "history" }
codex-keyring-store = { path = "keyring-store" }
codex-linux-sandbox = { path = "linux-sandbox" }
codex-lmstudio = { path = "lmstudio" }
codex-login = { path = "login" }
codex-mermaid = { path = "mermaid" }
codex-message-history = { path = "message-history" }
codex-memories-extension = { path = "ext/memories" }
codex-web-search-extension = { path = "ext/web-search" }
codex-memories-read = { path = "memories/read" }
codex-memories-write = { path = "memories/write" }
codex-mcp = { path = "codex-mcp" }
codex-mcp-extension = { path = "ext/mcp" }
codex-model-provider-info = { path = "model-provider-info" }
codex-models-manager = { path = "models-manager" }
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" }
codex-protocol = { path = "protocol" }
codex-protocol-test-support = { path = "protocol/tests/support" }
codex-prompts = { path = "prompts" }
codex-queue-extension = { path = "ext/queue" }
codex-responses-api-proxy = { path = "responses-api-proxy" }
codex-response-debug-context = { path = "response-debug-context" }
codex-rmcp-client = { path = "rmcp-client" }
codex-rollout = { path = "rollout" }
codex-rollout-trace = { path = "rollout-trace" }
codex-runtime-agent-instance = { path = "runtime-agent-instance" }
codex-sandboxing = { path = "sandboxing" }
codex-secrets = { path = "secrets" }
codex-shell-command = { path = "shell-command" }
codex-skills-extension = { path = "ext/skills" }
codex-skills = { path = "skills" }
codex-state = { path = "state" }
codex-stdio-to-uds = { path = "stdio-to-uds" }
codex-terminal-detection = { path = "terminal-detection" }
codex-test-binary-support = { path = "test-binary-support" }
codex-thread-store = { path = "thread-store" }
codex-tools = { path = "tools" }
codex-tcp-tunnel = { path = "tcp-tunnel" }
codex-tui = { path = "tui" }
codex-uds = { path = "uds" }
codex-utils-absolute-path = { path = "utils/absolute-path" }
codex-utils-approval-presets = { path = "utils/approval-presets" }
codex-utils-audio = { path = "utils/audio" }
codex-utils-cache = { path = "utils/cache" }
codex-utils-cargo-bin = { path = "utils/cargo-bin" }
codex-utils-cli = { path = "utils/cli" }
codex-utils-critical-path = { path = "utils/critical-path" }
codex-utils-elapsed = { path = "utils/elapsed" }
codex-utils-fuzzy-match = { path = "utils/fuzzy-match" }
codex-utils-git-discovery = { path = "utils/git-discovery" }
codex-utils-head-tail-buffer = { path = "utils/head-tail-buffer" }
codex-utils-home-dir = { path = "utils/home-dir" }
codex-utils-image = { path = "utils/image" }
codex-utils-json-to-toml = { path = "utils/json-to-toml" }
codex-utils-oss = { path = "utils/oss" }
codex-utils-output-truncation = { path = "utils/output-truncation" }
codex-utils-path = { path = "utils/path-utils" }
codex-utils-path-uri = { path = "utils/path-uri" }
codex-utils-plugins = { path = "utils/plugins" }
codex-utils-process = { path = "utils/process" }
codex-utils-pty = { path = "utils/pty" }
codex-utils-redacted-string = { path = "utils/redacted-string" }
codex-utils-rustls-provider = { path = "utils/rustls-provider" }
codex-utils-sandbox-summary = { path = "utils/sandbox-summary" }
codex-worktree = { path = "worktree" }
codex-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" }
codex-utils-stream-parser = { path = "utils/stream-parser" }
codex-utils-string = { path = "utils/string" }
codex-utils-template = { path = "utils/template" }
codex-user-verification = { path = "user-verification" }
codex-v8-poc = { path = "v8-poc" }
codex-workload-identity = { path = "workload-identity" }
codex-windows-sandbox = { path = "windows-sandbox-rs" }
codex-windows-sandbox-test-support = { path = "windows-sandbox-rs/tests/support" }
core_test_support = { path = "core/tests/common" }
# External
age = "0.12.1"
ansi-to-tui = "8.0.1"
anyhow = "1"
arboard = { version = "3", features = ["wayland-data-control"] }
arc-swap = "1.9.0"
assert_cmd = "2"
assert_matches = "1.5.0"
async-channel = "2.3.1"
async-io = "2.6.0"
async-stream = "0.3.6"
aws-config = "1"
aws-credential-types = "1"
aws-sigv4 = "1"
aws-smithy-runtime-api = { version = "1", features = ["client", "http-1x"] }
aws-smithy-types = { version = "1", features = ["http-body-1-x"] }
aws-types = "1"
axum = { version = "0.8", default-features = false }
base64 = "0.22.1"
bitflags = "2.13.1"
blake3 = "1.8.2"
bm25 = "2.3.2"
bytes = "1.10.1"
caseless = "0.2.2"
chardetng = "0.1.17"
chrono = "0.4.43"
clap = "4"
clap_complete = "4"
clatter = { version = "2.2.0", default-features = false, features = [
"alloc",
"getrandom",
"use-25519",
"use-aes-gcm",
"use-rust-crypto-ml-kem",
"use-sha",
] }
color-eyre = "0.6.3"
constant_time_eq = "0.3.1"
crossbeam-channel = "0.5.15"
crypto_box = { version = "0.9.1", features = ["seal"] }
crossterm = "0.29.0"
ctor = "0.6.3"
deno_core_icudata = "0.78.0"
derive_more = "2"
diffy = "0.4.2"
dirs = "6"
divan = "0.1.21"
dns-lookup = "3.0.1"
dotenvy = "0.15.7"
dunce = "1.0.4"
ed25519-dalek = { version = "2.2.0", features = ["pkcs8"] }
encoding_rs = "0.8.35"
eventsource-stream = "0.2.3"
file-id = "0.2.3"
flatbuffers = "25"
flate2 = "1.1.8"
futures = { version = "0.3", default-features = false }
gethostname = "1.1.0"
gix = { version = "0.89.0", default-features = false, features = ["sha1"] }
gix-url = "0.40.0"
glob = "0.3"
globset = "0.4"
hmac = "0.12.1"
http = "1.3.1"
httpdate = "1.0.3"
hyper-util = { version = "0.1.20", features = ["tokio"] }
iana-time-zone = "0.1.64"
icu_decimal = "2.1"
icu_locale_core = "2.1"
icu_provider = { version = "2.1", features = ["sync"] }
ignore = "0.4.30"
image = { version = "^0.25.9", default-features = false }
include_dir = "0.7.4"
indexmap = "2.12.0"
insta = "1.46.3"
inventory = "0.3.19"
itertools = "0.14.0"
jsonptr = { version = "0.7.1", default-features = false }
jsonwebtoken = "9.3.1"
keyring = { version = "3.6", default-features = false }
landlock = "0.4.4"
lazy_static = "1"
libc = "0.2.182"
# Keep SQLx's bundled SQLite on a version containing the WAL-reset corruption fix:
# https://www.sqlite.org/wal.html#the_wal_reset_bug
libsqlite3-sys = { version = "0.37", default-features = false }
linkify = "0.11"
log = "0.4"
lru = "0.18.2"
maplit = "1.0.2"
memchr = "2.7.6"
mime_guess = "2.0.5"
multimap = "0.10.0"
mxc-sdk = { git = "https://github.com/microsoft/mxc", rev = "b21120168d70befe12356411423266bfef168446" }
notify = "8.2.0"
nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faabb4e5c6d81d946a5e35a90f87347ee" }
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"
owo-colors = "4.3.0"
pathdiff = "0.2"
portable-pty = "0.9.0"
predicates = "3"
pretty_assertions = "1.4.1"
pulldown-cmark = { version = "0.10", default-features = false }
quick-xml = "0.41.0"
rand = "0.9"
rand_regex = "0.18.1"
ratatui = { version = "0.30.2", default-features = false, features = [
"crossterm",
"layout-cache",
"underline-color",
] }
ratatui-macros = "0.7.2"
rcgen = { version = "0.14.7", default-features = false, features = [
"aws_lc_rs",
"pem",
] }
regex = "1.12.3"
regex-automata = { version = "0.4.13", default-features = false, features = ["std", "syntax", "unicode", "nfa-pikevm"] }
regex-lite = "0.1.8"
regex-syntax = "0.8.8"
reqwest = { version = "0.12", features = ["cookies"] }
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", rev = "98a54789b80110ad210495c4ad845c89e1980471", version = "=3.5.1", default-features = false }
runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" }
rustix = { version = "1.1.4", features = ["net"] }
rustls = { version = "0.23.46", default-features = false, features = [
"aws_lc_rs",
"std",
] }
rustls-native-certs = "0.8.3"
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"
serde_path_to_error = "0.1.20"
serde_with = "3.17"
serde_yaml = "0.9"
serial_test = "3.2.0"
sha1 = "0.10.6"
scopeguard = "1.2.0"
sha2 = "0.10"
shlex = "1.3.0"
signal-hook = "0.3.18"
similar = "2.7.0"
symphonia = { version = "0.6.0", default-features = false, features = [
"isomp4",
"mkv",
"mp3",
"ogg",
"wav",
] }
# Keep SQLx versions in sync; when bumping, audit the SQLite constructor deny list in clippy.toml.
sqlx = { version = "=0.9.0", default-features = false, features = [
"chrono",
"json",
"migrate",
"runtime-tokio",
"tls-rustls",
"sqlite-bundled",
"time",
"uuid",
] }
# Derives and migration embedding do not need query macros or a host SQLite driver.
sqlx-macros = { version = "=0.9.0", default-features = false, features = ["derive", "migrate"] }
# Preserve the target driver's query-description support without building it on the host.
sqlx-sqlite = { version = "=0.9.0", default-features = false, features = ["offline"] }
starlark = { version = "0.14.2", default-features = false }
strum = "0.27.2"
strum_macros = "0.28.0"
supports-color = "3.0.2"
syntect = "5"
sys-locale = "0.3.2"
system-configuration = "0.7"
tar = { version = "=0.4.45", default-features = false }
tempfile = "3.23.0"
test-log = "0.2.19"
textwrap = "0.16.2"
thiserror = "2.0.17"
tikv-jemallocator = "=0.7.0"
time = "0.3.47"
tiny_http = "0.12"
tokio = "1"
tokio-rustls = "0.26.4"
tokio-stream = "0.1.18"
tokio-test = "0.4"
tokio-tungstenite = { version = "0.28.0", features = [
"proxy",
"rustls-tls-native-roots",
] }
tokio-util = "0.7.18"
toml = "0.9.5"
toml_edit = "0.24.0"
tracing = "0.1.44"
tracing-appender = "0.2.3"
tracing-opentelemetry = "0.32.0"
tracing-subscriber = "0.3.22"
tracing-test = "0.2.5"
tonic = { version = "0.14.3", default-features = false, features = ["channel", "codegen"] }
tonic-prost = "0.14.3"
tree-sitter = "0.25.10"
tree-sitter-bash = "0.25"
tree-sitter-powershell = "=0.26.4"
ts-rs = "11"
tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }
uds_windows = "1.1.0"
unicode-linebreak = "0.1.5"
unicode-normalization = "0.1.25"
unicode-segmentation = "1.12.0"
unicode-width = "0.2"
url = "2"
urlencoding = "2.1"
uuid = "1"
v8 = "=152.2.0"
vt100 = "0.16.2"
vtparse = "0.6.2"
walkdir = "2.5.0"
webbrowser = "1.2.2"
which = "8"
whoami = "1.6.1"
wildmatch = "2.6.1"
winapi-util = "0.1.11"
windows-sys = "0.61.2"
winreg = "0.55.0"
# Keep the zip 2.x feature set. In zip 9, `bzip2-rs` selects the bzip2-sys
# backend we already build; the default selects libbz2-rs-sys instead.
zip = { version = "9.0.0", default-features = false, features = [
"aes-crypto",
"bzip2-rs",
"deflate",
"deflate64",
"lzma",
"time",
"xz",
"zstd",
] }
zstd = "0.13"
wiremock = "0.6"
zeroize = "1.8.2"
[workspace.lints]
rust = {}
[workspace.lints.clippy]
await_holding_invalid_type = "deny"
await_holding_lock = "deny"
disallowed_methods = "deny"
expect_used = "deny"
identity_op = "deny"
manual_clamp = "deny"
manual_filter = "deny"
manual_find = "deny"
manual_flatten = "deny"
manual_map = "deny"
manual_memcpy = "deny"
manual_non_exhaustive = "deny"
manual_ok_or = "deny"
manual_range_contains = "deny"
manual_retain = "deny"
manual_strip = "deny"
manual_try_fold = "deny"
manual_unwrap_or = "deny"
needless_borrow = "deny"
needless_borrowed_reference = "deny"
needless_collect = "deny"
needless_late_init = "deny"
needless_option_as_deref = "deny"
needless_question_mark = "deny"
needless_update = "deny"
redundant_clone = "deny"
redundant_closure = "deny"
redundant_closure_for_method_calls = "deny"
redundant_static_lifetimes = "deny"
trivially_copy_pass_by_ref = "deny"
uninlined_format_args = "deny"
unnecessary_filter_map = "deny"
unnecessary_lazy_evaluations = "deny"
unnecessary_sort_by = "deny"
unnecessary_to_owned = "deny"
unwrap_used = "deny"
# cargo-shear cannot see the platform-specific openssl-sys usage, so we
# silence the false positive here instead of deleting a real dependency.
[workspace.metadata.cargo-shear]
ignored = [
"icu_provider",
"openssl-sys",
"codex-v8-poc",
]
[profile.dev]
# The test profile inherits dev. Keep source locations in ordinary builds;
# use CARGO_PROFILE_DEV_DEBUG=full (or CARGO_PROFILE_TEST_DEBUG=full) for locals.
debug = "line-tables-only"
[profile.dev-small]
inherits = "dev"
opt-level = 0
debug = "none"
strip = "symbols"
[profile.release]
lto = "thin"
debug = "line-tables-only"
split-debuginfo = "off"
# Keep release binaries symbolicateable until packaging has archived the
# sidecar symbols and stripped the binaries.
strip = false
# Balance parallel release code generation against binary size.
codegen-units = 4
[profile.profiling]
inherits = "release"
debug = "full"
lto = false
strip = false
[profile.ci-test]
# Reduce binary size to reduce disk pressure.
inherits = "test"
opt-level = 0
[patch.crates-io]
# Uncomment to debug local changes.
# ratatui = { path = "../../ratatui" }
crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "ed1cdab335221515706178d68495bba2aed1924f" }
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "02cb49fa827411e9279e3688d19ab9e82661b0e8" }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }
v8 = { git = "https://github.com/openai-oss-forks/rusty_v8.git", rev = "90a65f887a0c0f048f3784afbcb320b373c8a2e0" }
# Uncomment to debug local changes.
# rmcp = { path = "../../rust-sdk/crates/rmcp" }
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }

3
codex-rs/README.md Normal file
View File

@@ -0,0 +1,3 @@
# Codex CLI
[**Codex CLI Documentation**](https://developers.openai.com/codex/cli)

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-graph-store",
crate_name = "codex_agent_graph_store",
)

View File

@@ -0,0 +1,26 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-agent-graph-store"
version.workspace = true
[lib]
name = "codex_agent_graph_store"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
codex-protocol = { workspace = true }
codex-state = { workspace = true }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
[dev-dependencies]
codex-utils-absolute-path = { workspace = true }
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync"] }

View File

@@ -0,0 +1,20 @@
/// Result type returned by agent graph store operations.
pub type AgentGraphStoreResult<T> = Result<T, AgentGraphStoreError>;
/// Error type shared by agent graph store implementations.
#[derive(Debug, thiserror::Error)]
pub enum AgentGraphStoreError {
/// The caller supplied invalid request data.
#[error("invalid agent graph store request: {message}")]
InvalidRequest {
/// User-facing explanation of the invalid request.
message: String,
},
/// Catch-all for implementation failures that do not fit a more specific category.
#[error("agent graph store internal error: {message}")]
Internal {
/// User-facing explanation of the implementation failure.
message: String,
},
}

View File

@@ -0,0 +1,13 @@
//! Storage-neutral parent/child topology for thread-spawned agents.
mod error;
mod local;
mod store;
mod types;
pub use error::AgentGraphStoreError;
pub use error::AgentGraphStoreResult;
pub use local::LocalAgentGraphStore;
pub use store::AgentGraphStore;
pub use store::AgentGraphStoreFuture;
pub use types::ThreadSpawnEdgeStatus;

View File

@@ -0,0 +1,344 @@
use codex_protocol::ThreadId;
use codex_state::StateRuntime;
use std::sync::Arc;
use crate::AgentGraphStore;
use crate::AgentGraphStoreError;
use crate::AgentGraphStoreFuture;
use crate::ThreadSpawnEdgeStatus;
/// SQLite-backed implementation of [`AgentGraphStore`] using an existing state runtime.
#[derive(Clone)]
pub struct LocalAgentGraphStore {
state_db: Arc<StateRuntime>,
}
impl std::fmt::Debug for LocalAgentGraphStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LocalAgentGraphStore")
.field("sqlite", self.state_db.sqlite())
.finish_non_exhaustive()
}
}
impl LocalAgentGraphStore {
/// Create a local graph store from an already-initialized state runtime.
pub fn new(state_db: Arc<StateRuntime>) -> Self {
Self { state_db }
}
}
impl AgentGraphStore for LocalAgentGraphStore {
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error)
})
}
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.set_thread_spawn_edge_status(child_thread_id, to_state_status(status))
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
if let Some(status) = status_filter {
return self
.state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error);
}
self.state_db
.list_thread_spawn_children(parent_thread_id)
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
match status_filter {
Some(status) => self
.state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error),
None => self
.state_db
.list_thread_spawn_descendants(root_thread_id)
.await
.map_err(internal_error),
}
})
}
}
fn to_state_status(status: ThreadSpawnEdgeStatus) -> codex_state::DirectionalThreadSpawnEdgeStatus {
match status {
ThreadSpawnEdgeStatus::Open => codex_state::DirectionalThreadSpawnEdgeStatus::Open,
ThreadSpawnEdgeStatus::Closed => codex_state::DirectionalThreadSpawnEdgeStatus::Closed,
}
}
fn internal_error(err: impl std::fmt::Display) -> AgentGraphStoreError {
AgentGraphStoreError::Internal {
message: err.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use codex_state::DirectionalThreadSpawnEdgeStatus;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
struct TestRuntime {
state_db: Arc<StateRuntime>,
_codex_home: TempDir,
}
fn thread_id(suffix: u128) -> ThreadId {
ThreadId::from_string(&format!("00000000-0000-0000-0000-{suffix:012}"))
.expect("valid thread id")
}
async fn state_runtime() -> TestRuntime {
let codex_home = TempDir::new().expect("tempdir should be created");
let state_db = StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
TestRuntime {
state_db,
_codex_home: codex_home,
}
}
#[tokio::test]
async fn local_store_upserts_and_lists_direct_children_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let parent_thread_id = thread_id(/*suffix*/ 1);
let first_child_thread_id = thread_id(/*suffix*/ 2);
let second_child_thread_id = thread_id(/*suffix*/ 3);
store
.upsert_thread_spawn_edge(
parent_thread_id,
second_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
)
.await
.expect("closed child edge should insert");
store
.upsert_thread_spawn_edge(
parent_thread_id,
first_child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("open child edge should insert");
let all_children = store
.list_thread_spawn_children(parent_thread_id, /*status_filter*/ None)
.await
.expect("all children should load");
assert_eq!(
all_children,
vec![first_child_thread_id, second_child_thread_id]
);
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
let state_open_children = state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open children should load");
assert_eq!(open_children, state_open_children);
assert_eq!(open_children, vec![first_child_thread_id]);
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![second_child_thread_id]);
}
#[tokio::test]
async fn local_store_updates_edge_status() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db);
let parent_thread_id = thread_id(/*suffix*/ 10);
let child_thread_id = thread_id(/*suffix*/ 11);
store
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("child edge should insert");
store
.set_thread_spawn_edge_status(child_thread_id, ThreadSpawnEdgeStatus::Closed)
.await
.expect("child edge should close");
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
assert_eq!(open_children, Vec::<ThreadId>::new());
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![child_thread_id]);
}
#[tokio::test]
async fn local_store_lists_descendants_breadth_first_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let root_thread_id = thread_id(/*suffix*/ 20);
let later_child_thread_id = thread_id(/*suffix*/ 22);
let earlier_child_thread_id = thread_id(/*suffix*/ 21);
let closed_grandchild_thread_id = thread_id(/*suffix*/ 23);
let open_grandchild_thread_id = thread_id(/*suffix*/ 24);
let closed_child_thread_id = thread_id(/*suffix*/ 25);
let closed_great_grandchild_thread_id = thread_id(/*suffix*/ 26);
for (parent_thread_id, child_thread_id, status) in [
(
root_thread_id,
later_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
root_thread_id,
earlier_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
earlier_child_thread_id,
open_grandchild_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
later_child_thread_id,
closed_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
root_thread_id,
closed_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
closed_child_thread_id,
closed_great_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
] {
store
.upsert_thread_spawn_edge(parent_thread_id, child_thread_id, status)
.await
.expect("edge should insert");
}
let all_descendants = store
.list_thread_spawn_descendants(root_thread_id, /*status_filter*/ None)
.await
.expect("all descendants should load");
assert_eq!(
all_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
closed_child_thread_id,
closed_grandchild_thread_id,
open_grandchild_thread_id,
closed_great_grandchild_thread_id,
]
);
let open_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open descendants should load");
let state_open_descendants = state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open descendants should load");
assert_eq!(open_descendants, state_open_descendants);
assert_eq!(
open_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
open_grandchild_thread_id,
]
);
let closed_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed descendants should load");
assert_eq!(
closed_descendants,
vec![closed_child_thread_id, closed_great_grandchild_thread_id]
);
}
}

View File

@@ -0,0 +1,62 @@
use std::future::Future;
use std::pin::Pin;
use codex_protocol::ThreadId;
use crate::AgentGraphStoreResult;
use crate::ThreadSpawnEdgeStatus;
/// Future returned by [`AgentGraphStore`] operations.
pub type AgentGraphStoreFuture<'a, T> =
Pin<Box<dyn Future<Output = AgentGraphStoreResult<T>> + Send + 'a>>;
/// Storage-neutral boundary for persisted thread-spawn parent/child topology.
///
/// Implementations are expected to return stable ordering for list methods so callers can merge
/// persisted graph state with live in-memory state without introducing nondeterministic output.
pub trait AgentGraphStore: Send + Sync {
/// Insert or replace the directional parent/child edge for a spawned thread.
///
/// `child_thread_id` has at most one persisted parent. Re-inserting the same child should
/// update both the parent and status to match the supplied values.
/// The edge may be published before the child's metadata or history exists. A successful
/// write must make the child discoverable through the list methods.
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// Update the persisted lifecycle status of a spawned thread's incoming edge.
///
/// Implementations should treat missing children as a successful no-op.
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// List direct spawned children of a parent thread.
///
/// When `status_filter` is `Some`, only child edges with that exact status are returned. When
/// it is `None`, all direct child edges are returned regardless of status, including statuses
/// that may be added by a future store implementation.
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
/// List spawned descendants breadth-first by depth, then by thread id.
///
/// `status_filter` is applied to every traversed edge, not just to the returned descendants.
/// For example, `Some(Open)` walks only open edges, so descendants under a closed edge are not
/// included even if their own incoming edge is open. `None` walks and returns every persisted
/// edge regardless of status.
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
}

View File

@@ -0,0 +1,42 @@
use serde::Deserialize;
use serde::Serialize;
/// Lifecycle status attached to a directional thread-spawn edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThreadSpawnEdgeStatus {
/// The child thread is still live or resumable as an open spawned agent.
Open,
/// The child thread has been closed from the parent/child graph's perspective.
Closed,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn thread_spawn_edge_status_serializes_as_snake_case() {
assert_eq!(
serde_json::to_string(&ThreadSpawnEdgeStatus::Open)
.expect("open status should serialize"),
"\"open\""
);
assert_eq!(
serde_json::to_string(&ThreadSpawnEdgeStatus::Closed)
.expect("closed status should serialize"),
"\"closed\""
);
assert_eq!(
serde_json::from_str::<ThreadSpawnEdgeStatus>("\"open\"")
.expect("open status should deserialize"),
ThreadSpawnEdgeStatus::Open
);
assert_eq!(
serde_json::from_str::<ThreadSpawnEdgeStatus>("\"closed\"")
.expect("closed status should deserialize"),
ThreadSpawnEdgeStatus::Closed
);
}
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-identity",
crate_name = "codex_agent_identity",
)

View File

@@ -0,0 +1,31 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-agent-identity"
version.workspace = true
[lib]
doctest = false
name = "codex_agent_identity"
path = "src/lib.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
codex-http-client = { workspace = true }
codex-protocol = { workspace = true }
crypto_box = { workspace = true }
ed25519-dalek = { workspace = true }
http = { workspace = true }
jsonwebtoken = { workspace = true }
rand = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sha2 = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-client",
crate_name = "codex_agent_message_board_client",
)

View File

@@ -0,0 +1,34 @@
[package]
name = "codex-agent-message-board-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
codex-message-board = { workspace = true }
codex-extension-api = { workspace = true }
codex-http-client = { workspace = true }
codex-protocol = { workspace = true }
eventsource-stream = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,437 @@
//! Typed remote implementation of the board contract. HTTP policy is supplied
//! by the caller; reads and writes never fall back to a private local board.
//! Live notification frames are bounded before SSE parsing.
use crate::protocol::AccessToken;
use crate::protocol::BoardNotification;
use crate::protocol::Call;
use crate::protocol::Failure;
use crate::protocol::MAX_BODY;
use crate::protocol::MAX_RESPONSE;
use crate::protocol::Operation;
use crate::protocol::PermissionDeniedDetails;
use crate::protocol::Registration;
use crate::protocol::Watch;
use anyhow::Context;
use chrono::DateTime;
use chrono::Utc;
use codex_http_client::HttpClient;
use codex_http_client::HttpResponse;
use codex_message_board::AgentMessageBoard;
use codex_message_board::AppendRequest;
use codex_message_board::ChannelPage;
use codex_message_board::ChannelQuery;
use codex_message_board::ChannelSummary;
use codex_message_board::CreateChannelRequest;
use codex_message_board::Page;
use codex_message_board::PermissionDenied;
use codex_message_board::PostContent;
use codex_message_board::PostMetadata;
use codex_message_board::PostPreview;
use codex_message_board::PostQuery;
use codex_message_board::PostRequest;
use codex_message_board::ReadPostRequest;
use codex_message_board::ReadThreadRequest;
use codex_message_board::SubscriptionRequest;
use codex_message_board::SubscriptionState;
use codex_message_board::ThreadPage;
use codex_message_board::ThreadQuery;
use codex_message_board::ThreadSummary;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::error::Error;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;
use url::Url;
/// A client for one session's board. Use the shared HTTP client's configured
/// proxy and CA policy.
#[derive(Clone)]
pub struct RemoteAgentMessageBoard {
http: HttpClient,
board_url: Url,
board: SessionId,
token: AccessToken,
clock: Arc<dyn Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync>,
}
impl RemoteAgentMessageBoard {
/// Validate the HTTP(S) endpoint and append the board path to its optional path prefix.
pub fn new(
http: HttpClient,
endpoint: &str,
board: SessionId,
token: AccessToken,
) -> anyhow::Result<Self> {
let mut board_url = Url::parse(endpoint).context("invalid message-board endpoint")?;
anyhow::ensure!(
matches!(board_url.scheme(), "http" | "https") && board_url.host_str().is_some(),
"message-board endpoint must be an HTTP(S) URL"
);
anyhow::ensure!(
board_url.query().is_none() && board_url.fragment().is_none(),
"message-board endpoint must not contain a query or fragment"
);
board_url.set_path(&format!(
"{}/v1/boards/{board}",
board_url.path().trim_end_matches('/')
));
Ok(Self {
http,
board_url,
board,
token,
clock: Arc::new(|_| Box::pin(async { Ok(Utc::now()) })),
})
}
/// Supply the runtime's configured clock for research's simulated time.
pub fn with_clock(
mut self,
clock: impl Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync + 'static,
) -> Self {
self.clock = Arc::new(clock);
self
}
pub async fn create_board(&self) -> Result<SessionId> {
let response = self
.http
.request(http::Method::PUT, self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
pub async fn delete_board(&self) -> Result<()> {
let response = self
.http
.delete(self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
if response.status().is_success() {
Ok(())
} else {
decode(response).await
}
}
/// Register the session's agents. The returned session token is stable on retry.
pub async fn register_members(
&self,
members: HashMap<ThreadId, AgentPath>,
) -> Result<AccessToken> {
let response = self
.http
.post(self.url("/members"))
.bearer_auth(&self.token.0)
.json(&Registration { members })
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
/// Opens a live receiver and waits until the service has registered it.
/// Setup, including readiness or an error body, has a 30-second deadline.
/// Drop it when the turn ends. Reopening does not replay earlier previews.
pub async fn notifications(
&self,
caller: ThreadId,
turn_id: String,
) -> Result<BoardNotifications> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
let response = tokio::time::timeout_at(
deadline,
self.http
.post(self.url("/notifications"))
.bearer_auth(&self.token.0)
.json(&Watch {
caller,
turn_id: turn_id.clone(),
})
.send(),
)
.await
.map_err(transport_error)?
.map_err(transport_error)?;
if !response.status().is_success() {
tracing::warn!(
%caller, %turn_id,
http_status = response.status().as_u16(),
"Remote board notification request rejected"
);
tokio::time::timeout_at(deadline, decode::<()>(response))
.await
.map_err(transport_error)??;
return Err(transport_error("unexpected notification response"));
}
// Count wire bytes before the parser buffers them, resetting at blank lines.
// Defer CR handling so CRLF counts as one line ending even across chunks.
let mut frame_bytes = 0;
let mut line_empty = true;
let mut previous_cr = false;
// Validate before the SSE decoder can retain malformed UTF-8 indefinitely.
// Only an incomplete code point (at most three bytes) carries across chunks.
let mut utf8 = [0; 4];
let mut utf8_len = 0;
let mut chunks = Some(response.bytes_stream());
let mut events = futures::stream::poll_fn(move |cx| {
let Some(source) = chunks.as_mut() else {
return Poll::Ready(None);
};
let Some(chunk) = std::task::ready!(source.poll_next_unpin(cx)) else {
chunks = None;
return Poll::Ready(None);
};
let result = chunk.map_err(transport_error).and_then(|chunk| {
for &byte in chunk.iter() {
if !byte.is_ascii() || utf8_len > 0 {
utf8[utf8_len] = byte;
utf8_len += 1;
match std::str::from_utf8(&utf8[..utf8_len]) {
Ok(_) => utf8_len = 0,
Err(error) if error.error_len().is_some() => {
return Err(transport_error(error));
}
Err(_) => {}
}
}
if previous_cr && byte != b'\n' {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
frame_bytes += 1;
if frame_bytes > MAX_BODY {
return Err(transport_error("board SSE frame exceeds the service limit"));
}
match byte {
b'\n' => {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
b'\r' => {}
_ => line_empty = false,
}
previous_cr = byte == b'\r';
}
Ok(chunk)
});
if result.is_err() {
chunks = None;
}
Poll::Ready(Some(result))
})
.eventsource();
let ready = tokio::time::timeout_at(deadline, events.next())
.await
.map_err(transport_error)?
.ok_or_else(|| transport_error("notification stream closed before readiness"))?
.map_err(transport_error)?;
if ready.event != "ready" {
return Err(transport_error(
"notification stream did not acknowledge readiness",
));
}
let stream = events.map(|event| event.map_err(transport_error)).boxed();
Ok(BoardNotifications {
caller,
turn_id,
stream,
})
}
fn url(&self, suffix: &str) -> Url {
let mut url = self.board_url.clone();
url.set_path(&format!("{}{suffix}", url.path()));
url
}
async fn call<T: DeserializeOwned>(&self, caller: ThreadId, operation: Operation) -> Result<T> {
let timestamp = match &operation {
Operation::CreateChannel(_) => Some((self.clock)(caller).await?),
// The service can replay a committed post without a fresh timestamp.
// A new post still requires one; never substitute wall-clock time.
Operation::Post(_) => (self.clock)(caller).await.ok(),
Operation::ListChannels(_)
| Operation::ListThreads(_)
| Operation::SearchPosts(_)
| Operation::ReadThread(_)
| Operation::ReadPost(_)
| Operation::SetSubscription(_) => None,
};
let call = Call {
caller,
timestamp,
operation,
};
let body = serde_json::to_vec(&call)?;
if body.len() > MAX_BODY {
return Err(CodexErr::InvalidRequest(
"board request exceeds the service limit".into(),
));
}
let response = self
.http
.post(self.url("/call"))
.bearer_auth(&self.token.0)
.header("content-type", "application/json")
.body(body)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
}
macro_rules! operation {
($method:ident, $variant:ident, $input:ty, $output:ty) => {
fn $method(&self, caller: ThreadId, request: $input) -> BoxFuture<'_, Result<$output>> {
Box::pin(self.call(caller, Operation::$variant(request)))
}
};
}
impl AgentMessageBoard for RemoteAgentMessageBoard {
fn identity(&self) -> SessionId {
self.board
}
operation!(
create_channel,
CreateChannel,
CreateChannelRequest,
ChannelSummary
);
operation!(list_channels, ListChannels, ChannelQuery, ChannelPage);
fn upsert_channel(
&self,
_caller: ThreadId,
_request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
// The service has no description-update operation; creation has different semantics.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support channel upsert".into(),
))
})
}
operation!(post, Post, PostRequest, PostMetadata);
fn append(
&self,
_caller: ThreadId,
_request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
// The remote protocol has no silent write operation. Posting is not equivalent.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support silent append".into(),
))
})
}
operation!(list_threads, ListThreads, ThreadQuery, Page<ThreadSummary>);
operation!(search_posts, SearchPosts, PostQuery, Page<PostPreview>);
operation!(read_thread, ReadThread, ReadThreadRequest, ThreadPage);
operation!(read_post, ReadPost, ReadPostRequest, PostContent);
operation!(
set_subscription,
SetSubscription,
SubscriptionRequest,
SubscriptionState
);
}
/// One active turn's live receiver. Frames are checked against this receiver's
/// identity before accepted notices enter the host's ordinary message delivery.
pub struct BoardNotifications {
caller: ThreadId,
turn_id: String,
stream: BoxStream<'static, Result<eventsource_stream::Event>>,
}
impl BoardNotifications {
/// Skips invalid individual notices. Transport and framing failures remain errors.
pub async fn next(&mut self) -> Result<Option<BoardNotification>> {
while let Some(event) = self.stream.next().await.transpose()? {
let error_kind = if event.event != "notification" {
"unexpected_event"
} else {
match serde_json::from_str::<BoardNotification>(&event.data) {
Ok(notice) => {
if notice.recipient != self.caller || notice.turn_id != self.turn_id {
"wrong_recipient_or_turn"
} else if notice.post.text_preview.chars().count() > 150 {
"oversized_preview"
} else {
return Ok(Some(notice));
}
}
Err(_) => "invalid_json",
}
};
tracing::warn!(
caller = %self.caller, turn_id = %self.turn_id, error_kind,
"Skipping invalid remote board notification"
);
}
Ok(None)
}
}
async fn decode<T: DeserializeOwned>(mut response: HttpResponse) -> Result<T> {
let status = response.status();
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
if body.len().saturating_add(chunk.len()) > MAX_RESPONSE {
return Err(transport_error("board response exceeds the service limit"));
}
body.extend_from_slice(&chunk);
}
if !status.is_success() {
let failure: Failure = serde_json::from_slice(&body)
.with_context(|| format!("invalid board error response (HTTP {status})"))
.map_err(transport_error)?;
if status == http::StatusCode::FORBIDDEN && failure.code == "permission_denied" {
let details: PermissionDeniedDetails = serde_json::from_slice(&body)?;
return Err(PermissionDenied {
message: failure.message,
action: details.action,
resource: details.resource,
}
.into());
}
let message = format!("{}: {}", failure.code, failure.message);
return Err(if status.is_server_error() {
transport_error(message)
} else {
CodexErr::InvalidRequest(message)
});
}
serde_json::from_slice(&body).map_err(CodexErr::from)
}
fn transport_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> CodexErr {
CodexErr::Io(std::io::Error::other(error))
}

View File

@@ -0,0 +1,12 @@
//! A typed client for a message-board API at a configured endpoint.
//! Runtime credentials are scoped to one session; tools never see them.
mod client;
mod notifications;
mod protocol;
pub use client::BoardNotifications;
pub use client::RemoteAgentMessageBoard;
pub use notifications::install_notifications;
pub use protocol::AccessToken;
pub use protocol::BoardNotification;

View File

@@ -0,0 +1,122 @@
//! Receives live board previews for an active turn using the extension's turn hooks.
//! Provisioning and durable board ownership belong to the research host.
use crate::RemoteAgentMessageBoard;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::TurnAbortInput;
use codex_extension_api::TurnErrorInput;
use codex_extension_api::TurnLifecycleContributor;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStartPhase;
use codex_extension_api::TurnStopInput;
use codex_message_board::MessageBoardHost;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErrKind;
use futures::channel::oneshot;
use std::sync::Arc;
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
type Binding = (Arc<RemoteAgentMessageBoard>, Arc<dyn MessageBoardHost>);
type ResolveBinding = dyn Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync;
struct Notifications(Box<ResolveBinding>);
struct Receiver {
_task: AbortOnDropHandle<()>,
}
impl TurnLifecycleContributor for Notifications {
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
TurnStartPhase::RegularTaskStart
}
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let Some((board, host)) = (self.0)(&input) else {
return;
};
let Ok(caller) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let turn_id = input.turn_id.to_owned();
let (first_attempt_tx, first_attempt_rx) = oneshot::channel();
input.turn_store.insert(Receiver {
_task: AbortOnDropHandle::new(tokio::spawn(async move {
let mut first_attempt_tx = Some(first_attempt_tx);
loop {
let connection = board.notifications(caller, turn_id.clone()).await;
if let Some(first_attempt_tx) = first_attempt_tx.take() {
let _ = first_attempt_tx.send(());
}
match connection {
Ok(mut stream) => loop {
match stream.next().await {
Ok(Some(notice)) => {
if let Err(error) = host.notify(caller, notice.post).await {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification delivery failed"
);
}
}
Ok(None) => break,
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification stream failed"
);
break;
}
}
},
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification connection failed"
);
}
}
// Reopen for future previews; the service does not replay missed ones.
tokio::time::sleep(Duration::from_secs(/*secs*/ 1)).await;
}
})),
});
// A healthy service is listening before inference. A failed first attempt
// releases startup while the same turn-owned receiver keeps retrying.
let _ = first_attempt_rx.await;
})
}
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
}
/// Installs live notification delivery. The host resolves the existing remote
/// client and delivery host. Accepted notices use the host's ordinary message policy.
/// The turn store owns the receiver and cancels it when the turn ends.
pub fn install_notifications<C: Sync>(
registry: &mut ExtensionRegistryBuilder<C>,
resolve: impl Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync + 'static,
) {
registry.turn_lifecycle_contributor(Arc::new(Notifications(Box::new(resolve))));
}

View File

@@ -0,0 +1,107 @@
//! Versioned service requests reuse board operations; only host identity travels separately.
use chrono::DateTime;
use chrono::Utc;
use codex_message_board::ChannelQuery;
use codex_message_board::CreateChannelRequest;
use codex_message_board::PostPreview;
use codex_message_board::PostQuery;
use codex_message_board::PostRequest;
use codex_message_board::ReadPostRequest;
use codex_message_board::ReadThreadRequest;
use codex_message_board::SubscriptionRequest;
use codex_message_board::ThreadQuery;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
pub(crate) const MAX_BODY: usize = 512 * 1024;
pub(crate) const MAX_RESPONSE: usize = 1024 * 1024;
/// A host credential. Debug output must never reveal its contents.
#[derive(Clone, Serialize)]
#[serde(transparent)]
pub struct AccessToken(pub(crate) String);
impl AccessToken {
pub fn new(value: String) -> anyhow::Result<Self> {
anyhow::ensure!(
(32..=4096).contains(&value.len()),
"credentials must contain 32–4096 bytes"
);
anyhow::ensure!(
value.bytes().all(|b| b.is_ascii_graphic()),
"credential must be ASCII without whitespace"
);
Ok(Self(value))
}
}
impl<'de> Deserialize<'de> for AccessToken {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken([REDACTED])")
}
}
#[derive(Serialize)]
pub(crate) struct Registration {
pub(crate) members: HashMap<ThreadId, AgentPath>,
}
#[derive(Serialize)]
pub(crate) struct Call {
pub(crate) caller: ThreadId,
pub(crate) timestamp: Option<DateTime<Utc>>,
#[serde(flatten)]
pub(crate) operation: Operation,
}
#[derive(Serialize)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
pub(crate) enum Operation {
CreateChannel(CreateChannelRequest),
ListChannels(ChannelQuery),
Post(PostRequest),
ListThreads(ThreadQuery),
SearchPosts(PostQuery),
ReadThread(ReadThreadRequest),
ReadPost(ReadPostRequest),
SetSubscription(SubscriptionRequest),
}
#[derive(Serialize)]
pub(crate) struct Watch {
pub(crate) caller: ThreadId,
pub(crate) turn_id: String,
}
/// A best-effort preview bound to the receiving turn. Hosts must atomically check
/// `turn_id` when admitting it; a received preview must never start a new turn.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoardNotification {
pub recipient: ThreadId,
pub turn_id: String,
pub post: PostPreview,
}
#[derive(Deserialize)]
pub(crate) struct Failure {
pub(crate) code: String,
pub(crate) message: String,
}
#[derive(Deserialize)]
pub(crate) struct PermissionDeniedDetails {
pub(crate) action: Option<String>,
pub(crate) resource: Option<String>,
}

View File

@@ -0,0 +1,304 @@
//! Exercise the HTTP adapter's clock, authentication and turn-bound stream.
use chrono::DateTime;
use chrono::Utc;
use codex_agent_message_board_client::AccessToken;
use codex_agent_message_board_client::BoardNotification;
use codex_agent_message_board_client::RemoteAgentMessageBoard;
use codex_http_client::HttpClientBuilder;
use codex_message_board::AgentMessageBoard;
use codex_message_board::AppendRequest;
use codex_message_board::PostContent;
use codex_message_board::PostDestination;
use codex_message_board::PostMetadata;
use codex_message_board::PostPreview;
use codex_message_board::PostRequest;
use codex_message_board::ReadPostRequest;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn remote_board_preserves_the_host_contract() -> anyhow::Result<()> {
let server = MockServer::start().await;
let http = HttpClientBuilder::new().build_direct()?;
let board = SessionId::new();
let caller = ThreadId::new();
let members = HashMap::from([(caller, AgentPath::root())]);
let endpoint = format!("{}/board-service", server.uri());
let base = format!("/board-service/v1/boards/{board}");
let admin_token = AccessToken::new("administrator-credential-for-integration".into())?;
for invalid in [
"not a URL",
"file:///tmp/board",
"https://board.test/?query",
"https://board.test/#fragment",
] {
assert!(
RemoteAgentMessageBoard::new(http.clone(), invalid, board, admin_token.clone())
.is_err()
);
}
let admin =
RemoteAgentMessageBoard::new(http.clone(), &format!("{endpoint}/"), board, admin_token)?;
Mock::given(method("PUT"))
.and(path(&base))
.and(header(
"authorization",
"Bearer administrator-credential-for-integration",
))
.respond_with(ResponseTemplate::new(200).set_body_json(board))
.expect(1)
.mount(&server)
.await;
assert_eq!(admin.create_board().await?, board);
let invalid_registration = Mock::given(method("POST"))
.and(path(format!("{base}/members")))
.respond_with(ResponseTemplate::new(200).set_body_json("too-short"))
.expect(1)
.mount_as_scoped(&server)
.await;
let error = admin.register_members(members.clone()).await.unwrap_err();
assert!(matches!(error.details(), CodexErrorDetails::Json(_)));
drop(invalid_registration);
Mock::given(method("POST"))
.and(path(format!("{base}/members")))
.and(body_json(json!({"members": members})))
.respond_with(
ResponseTemplate::new(200).set_body_json("runtime-credential-for-integration-32"),
)
.expect(1)
.mount(&server)
.await;
let token = admin.register_members(members).await?;
let now: DateTime<Utc> = "2026-09-24T12:00:00Z".parse()?;
let clock_available = Arc::new(AtomicBool::new(true));
let clock = clock_available.clone();
let client =
RemoteAgentMessageBoard::new(http, &endpoint, board, token)?.with_clock(move |_| {
let available = clock.load(Ordering::Relaxed);
Box::pin(async move {
if available {
Ok(now)
} else {
Err(CodexErr::Io(std::io::Error::other("clock unavailable")))
}
})
});
let metadata: PostMetadata = serde_json::from_value(json!({
"message_id": "00000000-0000-4000-8000-000000000001", "thread_id": "00000000-0000-4000-8000-000000000001",
"author": "/root", "channel_name": "results", "created_at": now,
}))?;
let post = PostRequest {
request_id: "call-1".into(),
destination: PostDestination::NewChannel("results".into()),
text: "Straße 🦀".into(),
agents_to_notify: vec![AgentPath::root()],
};
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(header(
"authorization",
"Bearer runtime-credential-for-integration-32",
))
.and(body_json(
json!({"caller": caller, "timestamp": now, "method": "post", "params": post}),
))
// The post committed, but a gateway failed to return its result.
.respond_with(
ResponseTemplate::new(503)
.set_body_json(json!({"code": "unavailable", "message": "response unavailable"})),
)
.expect(1)
.mount(&server)
.await;
let board_handle: &dyn AgentMessageBoard = &client;
assert_eq!(board_handle.identity(), board);
let requests_before = server.received_requests().await.unwrap().len();
let unsupported = board_handle
.append(
caller,
AppendRequest {
request_id: post.request_id.clone(),
destination: post.destination.clone(),
text: post.text.clone(),
},
)
.await
.unwrap_err();
assert!(matches!(
unsupported.details(),
CodexErrorDetails::InvalidRequest(_)
));
let unsupported = board_handle
.upsert_channel(
caller,
UpsertChannelRequest {
channel_name: "results".into(),
description: "Updated purpose".to_owned().try_into()?,
},
)
.await
.unwrap_err();
assert!(matches!(
unsupported.details(),
CodexErrorDetails::InvalidRequest(_)
));
assert_eq!(
server.received_requests().await.unwrap().len(),
requests_before
);
assert!(board_handle.post(caller, post.clone()).await.is_err());
clock_available.store(false, Ordering::Relaxed);
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(body_json(
json!({"caller": caller, "timestamp": null, "method": "post", "params": post}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(&metadata))
.expect(1)
.mount(&server)
.await;
assert_eq!(client.post(caller, post).await?, metadata);
let request = ReadPostRequest {
message_id: metadata.message_id,
offset_chars: 7,
limit_chars: NonZeroU32::MIN,
};
let content = PostContent {
metadata: metadata.clone(),
text: "🦀".into(),
n_chars: 8,
next_offset_chars: 8,
};
Mock::given(method("POST"))
.and(path(format!("{base}/call")))
.and(body_json(
json!({"caller": caller, "timestamp": null, "method": "read_post", "params": request}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(&content))
.expect(1)
.mount(&server)
.await;
assert_eq!(client.read_post(caller, request).await?, content);
let notice = BoardNotification {
recipient: caller,
turn_id: "turn-1".into(),
post: PostPreview {
metadata,
text_preview: "Straße 🦀".into(),
n_chars: 8,
truncated: false,
},
};
let mut stale = notice.clone();
stale.turn_id = "turn-0".into();
let mut oversized = notice.clone();
oversized.post.text_preview = "🦀".repeat(151);
let events = [&notice, &stale, &oversized]
.into_iter()
.map(|event| {
Ok(format!(
"event: notification\ndata: {}\n\n",
serde_json::to_string(event)?
))
})
.collect::<anyhow::Result<String>>()?;
// The limit is per frame, not per connection; support all SSE line endings.
let heartbeats = ": heartbeat\r\n\r\n: heartbeat\r\r: heartbeat\n\n".repeat(16 * 1024);
Mock::given(method("POST"))
.and(path(format!("{base}/notifications")))
.and(body_json(json!({"caller": caller, "turn_id": "turn-1"})))
.respond_with(
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(format!("{heartbeats}event: ready\ndata: {{}}\n\n{events}")),
)
.expect(1)
.mount(&server)
.await;
let mut receiver = client.notifications(caller, "turn-1".into()).await?;
assert_eq!(receiver.next().await?, Some(notice));
assert_eq!(receiver.next().await?, None);
for body in [
format!(
"event: ready\nid: {}\ndata: {{}}\n\n",
"x".repeat(512 * 1024)
),
format!("event: ready\ndata: {{}}\n\nid: {}", "x".repeat(512 * 1024)),
format!(
"event: ready\ndata: {{}}\n\n{}",
"data: x\n".repeat(64 * 1024 + 1)
),
] {
let _response = Mock::given(method("POST"))
.and(path(format!("{base}/notifications")))
.and(body_json(json!({"caller": caller, "turn_id": "limit"})))
.respond_with(
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(body),
)
.expect(1)
.mount_as_scoped(&server)
.await;
let error = match client.notifications(caller, "limit".into()).await {
Ok(mut receiver) => receiver.next().await.unwrap_err(),
Err(error) => error,
};
assert!(
error
.to_string()
.contains("board SSE frame exceeds the service limit")
);
}
let invalid_response = Mock::given(method("DELETE"))
.and(path(&base))
.respond_with(ResponseTemplate::new(502).set_body_string("not JSON"))
.expect(1)
.mount_as_scoped(&server)
.await;
let error = admin.delete_board().await.unwrap_err();
assert!(error.to_string().contains("HTTP 502"));
assert!(
anyhow::Error::new(error)
.chain()
.any(<dyn std::error::Error>::is::<serde_json::Error>)
);
drop(invalid_response);
Mock::given(method("DELETE"))
.and(path(base))
.respond_with(
ResponseTemplate::new(503)
.set_body_json(json!({"code": "unavailable", "message": "storage unavailable"})),
)
.expect(1)
.mount(&server)
.await;
assert!(
admin
.delete_board()
.await
.unwrap_err()
.to_string()
.contains("storage unavailable")
);
Ok(())
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-host",
crate_name = "codex_agent_message_board_host",
)

View File

@@ -0,0 +1,25 @@
[package]
name = "codex-agent-message-board-host"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
chrono = { workspace = true }
codex-agent-message-board-client = { workspace = true }
codex-agent-message-board-extension = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }
codex-message-board = { workspace = true }
codex-protocol = { workspace = true }
codex-state = { workspace = true }
codex-thread-store = { workspace = true }
futures = { workspace = true }

View File

@@ -0,0 +1,261 @@
//! Supplies board host capabilities through the public Core runtime interfaces.
//!
//! The extension owns backend construction, storage and tool registration. This adapter
//! selects configuration and supplies host capabilities. It never starts or restores
//! recipients during lookup. Notifications use ordinary agent-message scheduling.
//! Permanent board deletion uses the thread store's existing host cleanup callback.
#![deny(clippy::print_stdout, clippy::print_stderr)]
use chrono::DateTime;
use chrono::Utc;
use codex_agent_message_board_client::RemoteAgentMessageBoard;
use codex_agent_message_board_extension::BoardBackend;
use codex_agent_message_board_extension::local_board_options;
use codex_core::CodexThread;
use codex_core::MULTI_AGENT_V2_NAMESPACE_DESCRIPTION;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ThreadStartInput;
use codex_features::Feature;
use codex_message_board::LocalAgentMessageBoard;
use codex_message_board::LocalBoardConnection;
use codex_message_board::MessageBoardHost;
use codex_message_board::NotificationDelivery;
use codex_message_board::PostPreview;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::Op;
use codex_state::SqliteConfig;
use codex_thread_store::ThreadStoreError;
use codex_thread_store::ThreadStoreResult;
use futures::future::BoxFuture;
use std::sync::Arc;
use std::sync::Weak;
/// Registers the configured board for opted-in MAv2 runtimes.
/// Training can share an in-memory board per tree, including ephemeral sessions.
pub fn install_agent_message_board(
registry: &mut ExtensionRegistryBuilder<Config>,
manager: Weak<ThreadManager>,
) {
codex_agent_message_board_client::install_notifications(registry, |input| {
let board = input.thread_store.get::<RemoteAgentMessageBoard>()?;
let host = input.thread_store.get::<LocalBoardHost>()?;
Some((
board,
Arc::new(LocalBoardHost {
remote_notifications: true,
..host.as_ref().clone()
}),
))
});
codex_agent_message_board_extension::install(
registry,
MULTI_AGENT_V2_NAMESPACE_DESCRIPTION,
|config: &Config| config.multi_agent_v2.tool_namespace.clone(),
move |input: &ThreadStartInput<'_, Config>, tree, caller| {
let config = input.config;
let connection = input.thread_store.get::<LocalBoardConnection>();
let in_memory = config.multi_agent_v2.message_board_in_memory;
let mcp =
config.features.enabled(Feature::AgentMessageBoardMcp) && connection.is_none();
// Automatic boards need MAv2. In-memory boards and explicit host
// connections also work for isolated, ephemeral runtimes.
if connection.is_none()
&& ((!config.features.enabled(Feature::AgentMessageBoard) && !mcp)
|| !config.features.enabled(Feature::MultiAgentV2)
|| (config.ephemeral
&& !mcp
&& !in_memory
&& config.multi_agent_v2.message_board_remote.is_none()))
{
return None;
}
let backend = if mcp {
BoardBackend::Mcp
} else if let Some(connection) = &connection {
BoardBackend::Connected(connection.clone())
} else if let Some(remote) = config.multi_agent_v2.message_board_remote.clone() {
BoardBackend::Remote {
config: remote,
http: config.http_client_factory(),
}
} else if in_memory {
BoardBackend::InMemory
} else {
BoardBackend::Local(config.sqlite_config().clone())
};
Some((
backend,
LocalBoardHost {
manager: manager.clone(),
tree,
caller,
remote_notifications: false,
connection,
},
))
},
);
}
/// Removes persisted agent-board data through the thread store's deletion callback.
/// Cleanup also applies when the board feature is currently disabled.
pub async fn delete_agent_message_boards(
sqlite: &SqliteConfig,
thread_ids: &[ThreadId],
) -> ThreadStoreResult<()> {
let boards = thread_ids
.iter()
.copied()
.map(Into::into)
.collect::<Vec<_>>();
LocalAgentMessageBoard::delete_boards(sqlite, &local_board_options(), &boards)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to delete agent message boards: {err}"),
})
}
#[derive(Clone)]
struct LocalBoardHost {
manager: Weak<ThreadManager>,
tree: SessionId,
caller: ThreadId,
remote_notifications: bool,
connection: Option<Arc<LocalBoardConnection>>,
}
impl LocalBoardHost {
async fn actor(&self, caller: ThreadId) -> Result<Arc<CodexThread>> {
let manager = self
.manager
.upgrade()
.ok_or_else(|| CodexErr::ThreadNotFound(caller))?;
if let Some(connection) = &self.connection {
return manager
.get_thread_with_extension::<LocalBoardConnection>(caller, |other| {
connection.same_board(other)
})
.await;
}
let actor = manager.get_thread(caller).await?;
if actor.startup_metadata().session_id != self.tree
|| actor
.thread_extension_data()
.get::<LocalBoardConnection>()
.is_some()
{
return Err(CodexErr::InvalidRequest(
"agent belongs to another message board".into(),
));
}
Ok(actor)
}
async fn registered_path(&self, actor: &CodexThread) -> Result<AgentPath> {
let caller = actor.startup_metadata().thread_id;
if let Some(connection) = &self.connection {
return connection.caller_path(caller);
}
let path = actor
.session_source()
.get_agent_path()
.or_else(|| (caller == ThreadId::from(self.tree)).then(AgentPath::root))
.ok_or_else(|| CodexErr::InvalidRequest("agent has no tree path".into()))?;
let resolved = actor.resolve_agent_reference(path.as_str()).await?;
if resolved != caller {
return Err(CodexErr::InvalidRequest(
"agent does not own its tree path".into(),
));
}
Ok(path)
}
}
impl MessageBoardHost for LocalBoardHost {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await
})
}
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
Box::pin(async move {
if self.connection.is_some() {
let caller = path
.as_str()
.strip_prefix("/root/")
.and_then(|id| ThreadId::from_string(id).ok())
.ok_or_else(|| {
CodexErr::InvalidRequest("invalid connected board agent path".into())
})?;
return self
.actor(caller)
.await
.map(|actor| actor.startup_metadata().thread_id);
}
let actor = self.actor(self.caller).await?;
actor.resolve_agent_reference(path.as_str()).await
})
}
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await?;
actor.current_time().await
})
}
fn notify(
&self,
recipient_id: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
Box::pin(async move {
let recipient = match self.actor(recipient_id).await {
Ok(thread) => thread,
Err(error) if matches!(error.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(NotificationDelivery::SkippedInactive);
}
Err(error) => return Err(error),
};
let recipient_path = self.registered_path(&recipient).await?;
let communication = InterAgentCommunication::new(
post.metadata.author.clone(),
recipient_path,
Vec::new(),
post.notification_text(),
/*trigger_turn*/ false,
);
// Remote metadata is untrusted. Skip an oversized notice without closing
// the receiver; the post remains available through the board tools.
if self.remote_notifications
&& communication.content.len()
+ communication.author.as_str().len()
+ communication.recipient.as_str().len()
> 1024
{
return Err(CodexErr::InvalidRequest(
"remote board notice exceeds the context budget".into(),
));
}
recipient
.submit(Op::InterAgentCommunication {
communication,
start_options: Default::default(),
})
.await?;
Ok(NotificationDelivery::Accepted)
})
}
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-roles",
crate_name = "codex_agent_roles",
)

View File

@@ -0,0 +1,23 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-agent-roles"
version.workspace = true
[lib]
doctest = false
name = "codex_agent_roles"
path = "src/lib.rs"
test = false
[lints]
workspace = true
[dependencies]
codex-config = { workspace = true }
codex-file-system = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
serde = { workspace = true, features = ["derive"] }
toml = { workspace = true, features = ["preserve_order"] }
tracing = { workspace = true }

View File

@@ -0,0 +1,209 @@
use codex_config::config_toml::ConfigToml;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use toml::Value as TomlValue;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AgentRoleConfig {
/// Human-facing role documentation used in spawn tool guidance.
/// Required for loaded user-defined roles after deprecated/new metadata precedence resolves.
pub description: Option<String>,
/// Path to a role-specific config layer.
pub config_file: Option<PathBuf>,
/// Candidate nicknames for agents spawned with this role.
pub nickname_candidates: Option<Vec<String>>,
}
#[derive(Deserialize, Debug, Clone, Default, PartialEq)]
#[serde(deny_unknown_fields)]
struct RawAgentRoleFileToml {
name: Option<String>,
description: Option<String>,
nickname_candidates: Option<Vec<String>>,
#[serde(flatten)]
config: ConfigToml,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedAgentRoleFile {
pub role_name: String,
pub description: Option<String>,
pub nickname_candidates: Option<Vec<String>>,
pub config: TomlValue,
}
pub fn parse_agent_role_file_contents(
contents: &str,
role_file_label: &Path,
config_base_dir: &Path,
role_name_hint: Option<&str>,
) -> std::io::Result<ResolvedAgentRoleFile> {
let role_file_toml: TomlValue = toml::from_str(contents).map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"failed to parse agent role file at {}: {err}",
role_file_label.display()
),
)
})?;
let _guard = AbsolutePathBufGuard::new(config_base_dir);
let parsed: RawAgentRoleFileToml = role_file_toml.clone().try_into().map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"failed to deserialize agent role file at {}: {err}",
role_file_label.display()
),
)
})?;
let description = normalize_agent_role_description(
&format!("agent role file {}.description", role_file_label.display()),
parsed.description.as_deref(),
)?;
validate_agent_role_file_developer_instructions(
role_file_label,
parsed.config.developer_instructions.as_deref(),
role_name_hint.is_none(),
)?;
let role_name = parsed
.name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.map(ToOwned::to_owned)
.or_else(|| role_name_hint.map(ToOwned::to_owned))
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agent role file at {} must define a non-empty `name`",
role_file_label.display()
),
)
})?;
let nickname_candidates = normalize_agent_role_nickname_candidates(
&format!(
"agent role file {}.nickname_candidates",
role_file_label.display()
),
parsed.nickname_candidates.as_deref(),
)?;
let mut config = role_file_toml;
let Some(config_table) = config.as_table_mut() else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"agent role file at {} must contain a TOML table",
role_file_label.display()
),
));
};
config_table.remove("name");
config_table.remove("description");
config_table.remove("nickname_candidates");
Ok(ResolvedAgentRoleFile {
role_name,
description,
nickname_candidates,
config,
})
}
pub(crate) fn normalize_agent_role_description(
field_label: &str,
description: Option<&str>,
) -> std::io::Result<Option<String>> {
match description.map(str::trim) {
Some("") => Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{field_label} cannot be blank"),
)),
Some(description) => Ok(Some(description.to_string())),
None => Ok(None),
}
}
fn validate_agent_role_file_developer_instructions(
role_file_label: &Path,
developer_instructions: Option<&str>,
require_present: bool,
) -> std::io::Result<()> {
match developer_instructions.map(str::trim) {
Some("") => Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agent role file at {}.developer_instructions cannot be blank",
role_file_label.display()
),
)),
Some(_) => Ok(()),
None if require_present => Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agent role file at {} must define `developer_instructions`",
role_file_label.display()
),
)),
None => Ok(()),
}
}
pub(crate) fn normalize_agent_role_nickname_candidates(
field_label: &str,
nickname_candidates: Option<&[String]>,
) -> std::io::Result<Option<Vec<String>>> {
let Some(nickname_candidates) = nickname_candidates else {
return Ok(None);
};
if nickname_candidates.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{field_label} must contain at least one name"),
));
}
let mut normalized_candidates = Vec::with_capacity(nickname_candidates.len());
let mut seen_candidates = BTreeSet::new();
for nickname in nickname_candidates {
let normalized_nickname = nickname.trim();
if normalized_nickname.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{field_label} cannot contain blank names"),
));
}
if !seen_candidates.insert(normalized_nickname.to_owned()) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{field_label} cannot contain duplicates"),
));
}
if !normalized_nickname
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_'))
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"{field_label} may only contain ASCII letters, digits, spaces, hyphens, and underscores"
),
));
}
normalized_candidates.push(normalized_nickname.to_owned());
}
Ok(Some(normalized_candidates))
}

View File

@@ -0,0 +1,40 @@
use codex_file_system::ExecutorFileSystem;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::io;
use std::io::ErrorKind;
pub(crate) async fn collect_agent_role_files(
fs: &dyn ExecutorFileSystem,
dir: &AbsolutePathBuf,
) -> io::Result<Vec<AbsolutePathBuf>> {
let mut files = Vec::new();
let mut dirs = vec![dir.clone()];
while let Some(dir) = dirs.pop() {
let dir_uri = PathUri::from_abs_path(&dir);
let entries = match fs.read_directory(&dir_uri, /*sandbox*/ None).await {
Ok(entries) => entries,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
for entry in entries {
let path = dir.join(entry.file_name);
if entry.is_directory {
dirs.push(path);
continue;
}
if entry.is_file
&& path
.as_path()
.extension()
.is_some_and(|extension| extension == "toml")
{
files.push(path);
}
}
}
files.sort();
Ok(files)
}

View File

@@ -0,0 +1,8 @@
mod agent_role_config;
mod discovery;
mod loader;
pub use agent_role_config::AgentRoleConfig;
pub use agent_role_config::ResolvedAgentRoleFile;
pub use agent_role_config::parse_agent_role_file_contents;
pub use loader::load_agent_roles;

View File

@@ -0,0 +1,335 @@
use crate::AgentRoleConfig;
use crate::ResolvedAgentRoleFile;
use crate::agent_role_config::normalize_agent_role_description;
use crate::agent_role_config::normalize_agent_role_nickname_candidates;
use crate::discovery::collect_agent_role_files;
use crate::parse_agent_role_file_contents;
use codex_config::ConfigLayerStack;
use codex_config::config_toml::AgentRoleToml;
use codex_config::config_toml::AgentsToml;
use codex_config::config_toml::ConfigToml;
use codex_file_system::ExecutorFileSystem;
use codex_file_system::GetMetadataOptions;
use codex_file_system::ReadFileOptions;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathUri;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use toml::Value as TomlValue;
pub async fn load_agent_roles(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
config_layer_stack: &ConfigLayerStack,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut layers = config_layer_stack.layers_low_to_high().peekable();
if layers.peek().is_none() {
return load_agent_roles_without_layers(fs, cfg).await;
}
let mut roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
for layer in layers {
let mut layer_roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
let mut declared_role_files = BTreeSet::new();
let config_folder = layer.config_folder();
let agents_toml = match agents_toml_from_layer(&layer.config, config_folder.as_deref()) {
Ok(agents_toml) => agents_toml,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
None
}
};
if let Some(agents_toml) = agents_toml {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) =
match read_declared_role(fs, declared_role_name, role_toml).await {
Ok(role) => role,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
if let Some(config_file) = role.config_file.clone() {
declared_role_files.insert(config_file);
}
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
if let Some(config_folder) = layer.config_folder() {
for (role_name, role) in discover_agent_roles_in_dir(
fs,
&config_folder.join("agents"),
&declared_role_files,
startup_warnings,
)
.await?
{
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
for (role_name, role) in layer_roles {
let mut merged_role = role;
if let Some(existing_role) = roles.get(&role_name) {
merge_missing_role_fields(&mut merged_role, existing_role);
}
if let Err(err) = validate_required_agent_role_description(
&role_name,
merged_role.description.as_deref(),
) {
push_agent_role_warning(startup_warnings, err);
continue;
}
roles.insert(role_name, merged_role);
}
}
Ok(roles)
}
fn push_agent_role_warning(startup_warnings: &mut Vec<String>, err: std::io::Error) {
let message = format!("Ignoring malformed agent role definition: {err}");
tracing::warn!("{message}");
startup_warnings.push(message);
}
async fn load_agent_roles_without_layers(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
if let Some(agents_toml) = cfg.agents.as_ref() {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) = read_declared_role(fs, declared_role_name, role_toml).await?;
validate_required_agent_role_description(&role_name, role.description.as_deref())?;
if roles.insert(role_name.clone(), role).is_some() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("duplicate agent role name `{role_name}` declared in config"),
));
}
}
}
Ok(roles)
}
async fn read_declared_role(
fs: &dyn ExecutorFileSystem,
declared_role_name: &str,
role_toml: &AgentRoleToml,
) -> std::io::Result<(String, AgentRoleConfig)> {
let mut role = agent_role_config_from_toml(fs, declared_role_name, role_toml).await?;
let mut role_name = declared_role_name.to_string();
if let Some(config_file) = role.config_file.as_deref() {
let config_file = AbsolutePathBuf::from_absolute_path(config_file)?;
let parsed_file =
read_resolved_agent_role_file(fs, &config_file, Some(declared_role_name)).await?;
role_name = parsed_file.role_name;
role.description = parsed_file.description.or(role.description);
role.nickname_candidates = parsed_file.nickname_candidates.or(role.nickname_candidates);
}
Ok((role_name, role))
}
fn merge_missing_role_fields(role: &mut AgentRoleConfig, fallback: &AgentRoleConfig) {
role.description = role.description.clone().or(fallback.description.clone());
role.config_file = role.config_file.clone().or(fallback.config_file.clone());
role.nickname_candidates = role
.nickname_candidates
.clone()
.or(fallback.nickname_candidates.clone());
}
fn agents_toml_from_layer(
layer_toml: &TomlValue,
config_base_dir: Option<&Path>,
) -> std::io::Result<Option<AgentsToml>> {
let Some(agents_toml) = layer_toml.get("agents") else {
return Ok(None);
};
// AbsolutePathBufGuard resolves relative paths while it remains in scope.
let _guard = config_base_dir.map(AbsolutePathBufGuard::new);
agents_toml
.clone()
.try_into()
.map(Some)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
async fn agent_role_config_from_toml(
fs: &dyn ExecutorFileSystem,
role_name: &str,
role: &AgentRoleToml,
) -> std::io::Result<AgentRoleConfig> {
let config_file = role
.config_file
.as_ref()
.map(AbsolutePathBuf::from_absolute_path)
.transpose()?;
validate_agent_role_config_file(fs, role_name, config_file.as_ref()).await?;
let description = normalize_agent_role_description(
&format!("agents.{role_name}.description"),
role.description.as_deref(),
)?;
let nickname_candidates = normalize_agent_role_nickname_candidates(
&format!("agents.{role_name}.nickname_candidates"),
role.nickname_candidates.as_deref(),
)?;
Ok(AgentRoleConfig {
description,
config_file: config_file.map(AbsolutePathBuf::into_path_buf),
nickname_candidates,
})
}
async fn read_resolved_agent_role_file(
fs: &dyn ExecutorFileSystem,
path: &AbsolutePathBuf,
role_name_hint: Option<&str>,
) -> std::io::Result<ResolvedAgentRoleFile> {
let path_uri = PathUri::from_abs_path(path);
let contents = fs
.read_file_text(&path_uri, ReadFileOptions::default(), /*sandbox*/ None)
.await?;
let config_base_dir = path.parent().unwrap_or_else(|| path.clone());
parse_agent_role_file_contents(
&contents,
path.as_path(),
config_base_dir.as_path(),
role_name_hint,
)
}
fn validate_required_agent_role_description(
role_name: &str,
description: Option<&str>,
) -> std::io::Result<()> {
if description.is_some() {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("agent role `{role_name}` must define a description"),
))
}
}
async fn validate_agent_role_config_file(
fs: &dyn ExecutorFileSystem,
role_name: &str,
config_file: Option<&AbsolutePathBuf>,
) -> std::io::Result<()> {
let Some(config_file) = config_file else {
return Ok(());
};
let config_file_uri = PathUri::from_abs_path(config_file);
let metadata = fs
.get_metadata(
&config_file_uri,
GetMetadataOptions::default(),
/*sandbox*/ None,
)
.await
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to an existing file at {}: {e}",
config_file.as_path().display()
),
)
})?;
if metadata.is_file {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to a file: {}",
config_file.as_path().display()
),
))
}
}
async fn discover_agent_roles_in_dir(
fs: &dyn ExecutorFileSystem,
agents_dir: &AbsolutePathBuf,
declared_role_files: &BTreeSet<PathBuf>,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
for agent_file in collect_agent_role_files(fs, agents_dir).await? {
if declared_role_files.contains(agent_file.as_path()) {
continue;
}
let parsed_file =
match read_resolved_agent_role_file(fs, &agent_file, /*role_name_hint*/ None).await {
Ok(parsed_file) => parsed_file,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
let role_name = parsed_file.role_name;
if roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` discovered in {}",
agents_dir.as_path().display()
),
),
);
continue;
}
roles.insert(
role_name,
AgentRoleConfig {
description: parsed_file.description,
config_file: Some(agent_file.to_path_buf()),
nickname_candidates: parsed_file.nickname_candidates,
},
);
}
Ok(roles)
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "analytics",
crate_name = "codex_analytics",
)

View File

@@ -0,0 +1,42 @@
[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 }

View File

@@ -0,0 +1,187 @@
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<String>,
pub(crate) model_slug: Option<String>,
pub(crate) completed_at: u64,
pub(crate) repo_hash: Option<String>,
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<TrackEventRequest> {
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<String> {
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,
},
);
}
}

View File

@@ -0,0 +1,34 @@
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<File> {
let mut options = OpenOptions::new();
options.create(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,359 @@
//! 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<String>, 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<_>>(),
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::<Vec<_>>();
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<Vec<CapturedRequest>>,
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::<Vec<_>>();
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::<Vec<_>>();
assert_eq!(
requests
.into_iter()
.map(|(product, body)| (
product,
body["events"][0]["event_type"]
.as_str()
.unwrap()
.to_string(),
))
.collect::<Vec<_>>(),
expected
);
}
}

View File

@@ -0,0 +1,300 @@
//! 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;
}
}
#[tokio::test]
async fn custom_analytics_destination_does_not_initialize_runtime_auth() {
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(1)
.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;
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].headers["authorization"], "Bearer key-a");
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
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;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,776 @@
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<Arc<dyn TurnAnalyticsMetadata>>,
}
#[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<String>,
},
Completed {
thread_id: String,
turn_id: String,
turn_metadata: Arc<dyn TurnAnalyticsMetadata>,
call_id: String,
cell_id: Option<String>,
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<dyn TurnAnalyticsMetadata>,
pub call_id: String,
pub cell_id: Option<String>,
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<Arc<dyn TurnAnalyticsMetadata>>,
) -> 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<String>,
/// 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<String>,
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<dyn TurnAnalyticsMetadata>,
/// Observed active plugin inventory. None is unknown; Some([]) is observed empty.
pub active_plugin_ids_at_turn_start: Option<Vec<String>>,
pub num_input_images: usize,
pub submission_type: Option<TurnSubmissionType>,
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<ReasoningEffort>,
pub reasoning_summary: Option<ReasoningSummary>,
pub service_tier: Option<ServiceTier>,
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<Personality>,
pub workspace_kind: Option<String>,
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<String>;
/// The caller-provided trigger recorded when this turn started.
fn turn_trigger(&self) -> Option<String>;
/// The effective Responses source at event emission, including accepted steers.
fn codex_turn_source(&self) -> Option<String>;
}
#[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<u16>,
pub(crate) usage_limit_window_minutes: Option<u16>,
}
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<String>,
pub accepted_turn_id: Option<String>,
pub num_input_images: usize,
pub result: TurnSteerResult,
pub rejection_reason: Option<TurnSteerRejectionReason>,
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<TurnSteerRequestError> 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<InputError> 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<String>,
pub remote_plugin_id: Option<String>,
pub invocation_type: InvocationType,
}
#[derive(Clone, Debug)]
pub enum SkillInvocationLocation {
Host {
path: PathUri,
scope: SkillScope,
},
Resource {
id: String,
skill_id: Option<String>,
scope: Option<SkillScope>,
},
}
#[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<String>,
pub app_name: Option<String>,
pub invocation_type: Option<InvocationType>,
}
/// 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<String>,
pub forked_from_thread_id: Option<String>,
pub product_client_id: String,
pub client_name: Option<String>,
pub client_version: Option<String>,
pub model: String,
pub ephemeral: bool,
pub thread_source: Option<ThreadSource>,
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<CodexErrKind>,
pub codex_error_http_status_code: Option<u16>,
pub usage_limit_window_minutes: Option<u16>,
pub active_context_tokens_before: i64,
pub active_context_tokens_after: i64,
pub retained_image_count: Option<usize>,
pub compaction_summary_tokens: Option<i64>,
pub cached_input_tokens: Option<i64>,
pub cache_write_input_tokens: Option<i64>,
pub started_at: u64,
pub completed_at: u64,
pub duration_ms: Option<u64>,
}
#[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<String>,
pub goal_id: String,
pub event_kind: GoalEventKind,
pub goal_status: codex_state::ThreadGoalStatus,
pub has_token_budget: bool,
pub cumulative_tokens_accounted: Option<i64>,
pub cumulative_time_accounted_seconds: Option<i64>,
}
#[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<ClientRequest>,
},
ExplicitClientInterruptRequest {
connection_id: u64,
request_id: RequestId,
turn_id: String,
requested_at_ms: u64,
},
ClientResponse {
connection_id: u64,
request_id: RequestId,
response: Box<ClientResponsePayload>,
thread_originator: Option<String>,
},
ErrorResponse {
connection_id: u64,
request_id: RequestId,
error: JSONRPCErrorError,
error_type: Option<AnalyticsJsonRpcError>,
},
ServerRequest {
connection_id: u64,
request: Box<ServerRequest>,
},
ServerResponse {
completed_at_ms: u64,
response: Box<ServerResponse>,
},
EffectivePermissionsApprovalResponse {
completed_at_ms: u64,
request_id: RequestId,
response: Box<RequestPermissionsResponse>,
},
ServerRequestAborted {
completed_at_ms: u64,
request_id: RequestId,
},
RealtimeHandoffRequested {
thread_id: String,
},
RealtimeSessionStarted {
thread_id: String,
realtime_session_id: Option<String>,
started_at: u64,
},
RealtimeSessionUpdated {
thread_id: String,
realtime_session_id: String,
},
RealtimeSessionClosed {
thread_id: String,
closed_at: u64,
},
Notification(Box<ServerNotification>),
// 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<CodexCompactionEvent>),
Goal(Box<CodexGoalEvent>),
ThreadHintStatus(Box<crate::thread_hint::ThreadHintStatusEvent>),
GuardianReview(Box<GuardianReviewEventParams>),
GuardianV2(Box<GuardianV2Event>),
TurnResolvedConfig(Box<TurnResolvedConfigFact>),
TurnTokenUsage(Box<TurnTokenUsageFact>),
TurnProfile(Box<TurnProfileFact>),
TurnCodexError(Box<TurnCodexErrorFact>),
ImagePreparation(Box<ImagePreparationFact>),
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<String, String>,
}
#[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<String>,
pub reasoning_effort: Option<String>,
pub plugin_id: String,
pub execution_id: String,
pub operation: String,
pub rows: Vec<PluginMeasurementRow>,
}
pub(crate) struct SkillInvokedInput {
pub tracking: TrackEventsContext,
pub invocations: Vec<SkillInvocation>,
}
pub(crate) struct AppMentionedInput {
pub tracking: TrackEventsContext,
pub mentions: Vec<AppInvocation>,
}
pub(crate) struct AppUsedInput {
pub tracking: TrackEventsContext,
pub app: AppInvocation,
pub elicitation_type: Option<ElicitationType>,
}
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<PluginInstallRequestedPlugin>,
pub source: PluginInstallRequestSource,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginInstallRequestedPlugin {
pub plugin_id: String,
pub remote_plugin_id: Option<String>,
pub plugin_name: String,
pub connector_ids: Vec<String>,
}
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<String>,
}
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<String>,
}
#[derive(Clone, Copy)]
pub(crate) enum PluginState {
Installed,
Uninstalled,
Enabled,
Disabled,
}

View File

@@ -0,0 +1,50 @@
//! 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<String>,
pub model: Option<String>,
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<ThreadSource>,
pub(crate) subagent_source: Option<String>,
pub(crate) parent_thread_id: Option<String>,
#[serde(flatten)]
pub(crate) guardian_v2: GuardianV2Event,
}

View File

@@ -0,0 +1,121 @@
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<T: serde::Serialize>(value: &T) -> Option<String> {
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<i64>) -> Option<u64> {
value.and_then(|value| u64::try_from(value).ok())
}

View File

@@ -0,0 +1,110 @@
//! 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<String, String>,
pub(crate) registered_threads: VecDeque<String>,
}
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<String>) {
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<TrackEventRequest>,
thread_products: &ThreadProducts,
) -> Vec<(Option<&str>, Vec<TrackEventRequest>)> {
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<TrackEventRequest>)> = 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,
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
mod suite;
mod support;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,181 @@
//! 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)
);
}

View File

@@ -0,0 +1,167 @@
//! 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");
}

View File

@@ -0,0 +1,27 @@
//! 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;

View File

@@ -0,0 +1,131 @@
//! 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,
}
}])
);
}

View File

@@ -0,0 +1,484 @@
//! 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<PluginMeasurementRow>) -> 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
}
}])
);
}

View File

@@ -0,0 +1,806 @@
//! 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<_>>(),
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<_>>(),
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<_>>(),
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());
}

View File

@@ -0,0 +1,204 @@
//! 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"))
);
}

View File

@@ -0,0 +1,915 @@
//! 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<_>>(),
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<_>>(),
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<_>>(),
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");
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,322 @@
//! 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::<Vec<_>>();
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::<Vec<_>>();
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::<serde_json::Value>(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::<Vec<_>>()
})
.collect::<Vec<_>>();
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");
}

View File

@@ -0,0 +1,381 @@
//! 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");
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,728 @@
//! 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<TrackEventRequest>,
error: JSONRPCErrorError,
error_type: Option<AnalyticsJsonRpcError>,
) -> 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)
);
}

View File

@@ -0,0 +1,8 @@
#[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;

View File

@@ -0,0 +1,708 @@
//! 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<Option<String>>,
pub(super) turn_trigger: Option<String>,
}
impl TurnAnalyticsMetadata for TestTurnMetadata {
fn root_turn_id(&self) -> Option<String> {
self.root_turn_id.lock().expect("root turn ID").clone()
}
fn turn_trigger(&self) -> Option<String> {
self.turn_trigger.clone()
}
fn codex_turn_source(&self) -> Option<String> {
None
}
}
pub(super) fn test_turn_metadata(root_turn_id: Option<&str>) -> Arc<TestTurnMetadata> {
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<AppServerThreadSource>,
parent_thread_id: Option<String>,
) -> 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<AppServerThreadSource>,
parent_thread_id: Option<String>,
) -> 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<codex_app_server_protocol::CodexErrorInfo>,
) -> 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<TrackEventRequest>,
) {
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<TrackEventRequest>,
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<TrackEventRequest>,
) {
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<TrackEventRequest>,
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<TrackEventRequest>,
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<i32>,
duration_ms: Option<i64>,
) -> 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<i32>,
duration_ms: Option<i64>,
) -> 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<TrackEventRequest>,
facts: impl IntoIterator<Item = CodeModeToolCallFact>,
) {
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()),
],
}),
}
}

View File

@@ -0,0 +1,38 @@
//! 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<ThreadSource>,
pub(crate) subagent_source: Option<String>,
pub(crate) parent_thread_id: Option<String>,
pub(crate) status: ThreadHintStatus,
pub(crate) occurred_at_ms: u64,
}

View File

@@ -0,0 +1,84 @@
//! 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<u64>,
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<u64>,
critical_path_inference_ms: Option<u64>,
critical_path_sampling_ms: Option<u64>,
critical_path_compaction_ms: Option<u64>,
critical_path_auto_review_ms: Option<u64>,
critical_path_auto_review_overhead_ms: Option<u64>,
critical_path_user_wait_ms: Option<u64>,
critical_path_tools_ms: Option<u64>,
critical_path_overhead_ms: Option<u64>,
critical_path_unknown_ms: Option<u64>,
}
impl From<TurnCriticalPath> 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),
}
}
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "ansi-escape",
crate_name = "codex_ansi_escape",
)

View File

@@ -0,0 +1,22 @@
[package]
name = "codex-ansi-escape"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "codex_ansi_escape"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
ansi-to-tui = { workspace = true }
ratatui = { workspace = true }
tracing = { workspace = true, features = ["log"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tracing-subscriber = { workspace = true }

View File

@@ -0,0 +1,15 @@
# oai-codex-ansi-escape
Small helper functions that wrap functionality from
<https://crates.io/crates/ansi-to-tui>:
```rust
pub fn ansi_escape_line(s: &str) -> Line<'static>
pub fn ansi_escape<'a>(s: &'a str) -> Text<'a>
```
Advantages:
- `ansi_to_tui::IntoText` is not in scope for the entire TUI crate
- we `panic!()` and log if `IntoText` returns an `Err` and log it so that
the caller does not have to deal with it

View File

@@ -0,0 +1,76 @@
//! Check that multiline warnings omit payloads and preserve first-line rendering.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;
use pretty_assertions::assert_eq;
use ratatui::style::Stylize;
use ratatui::text::Line;
use tracing::Event;
use tracing::Level;
use tracing::Subscriber;
use tracing::field::Field;
use tracing::field::Visit;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
use tracing_subscriber::layer::SubscriberExt;
use super::ansi_escape_line;
#[derive(Debug, PartialEq, Eq)]
struct CapturedEvent {
level: Level,
fields: BTreeMap<String, String>,
}
impl Visit for CapturedEvent {
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.fields
.insert(field.name().to_string(), format!("{value:?}"));
}
}
struct CaptureLayer(Arc<Mutex<Vec<CapturedEvent>>>);
impl<S: Subscriber> Layer<S> for CaptureLayer {
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let mut captured = CapturedEvent {
level: *event.metadata().level(),
fields: BTreeMap::new(),
};
event.record(&mut captured);
self.0.lock().expect("capture events").push(captured);
}
}
#[test]
fn multiline_warning_contains_counts_and_preserves_the_styled_first_line() {
let events = Arc::new(Mutex::new(Vec::new()));
let subscriber = tracing_subscriber::registry().with(CaptureLayer(Arc::clone(&events)));
let mut expected_events = Vec::new();
tracing::subscriber::with_default(subscriber, || {
for tail_bytes in [8, 128 * 1024] {
let tail = "x".repeat(tail_bytes);
let input = format!("\x1b[31mfirst\x1b[0m\n{tail}\nlast");
assert_eq!(ansi_escape_line(&input), Line::from("first".red()));
expected_events.push(CapturedEvent {
level: Level::WARN,
fields: BTreeMap::from([
("input_bytes".to_string(), input.len().to_string()),
("line_count".to_string(), "3".to_string()),
(
"message".to_string(),
"ansi_escape_line: expected a single line".to_string(),
),
]),
});
}
});
assert_eq!(
*events.lock().expect("read captured events"),
expected_events
);
}

View File

@@ -0,0 +1,66 @@
use ansi_to_tui::Error;
use ansi_to_tui::IntoText;
use ratatui::text::Line;
use ratatui::text::Text;
// Expand tabs in a best-effort way for transcript rendering.
// Tabs can interact poorly with left-gutter prefixes in our TUI and CLI
// transcript views (e.g., `nl` separates line numbers from content with a tab).
// Replacing tabs with spaces avoids odd visual artifacts without changing
// semantics for our use cases.
fn expand_tabs(s: &str) -> std::borrow::Cow<'_, str> {
if s.contains('\t') {
// Keep it simple: replace each tab with 4 spaces.
// We do not try to align to tab stops since most usages (like `nl`)
// look acceptable with a fixed substitution and this avoids stateful math
// across spans.
std::borrow::Cow::Owned(s.replace('\t', " "))
} else {
std::borrow::Cow::Borrowed(s)
}
}
/// This function should be used when the contents of `s` are expected to match
/// a single line. If multiple lines are found, a warning is logged and only the
/// first line is returned.
pub fn ansi_escape_line(s: &str) -> Line<'static> {
// Normalize tabs to spaces to avoid odd gutter collisions in transcript mode.
let s = expand_tabs(s);
let text = ansi_escape(&s);
match text.lines.as_slice() {
[] => "".into(),
[only] => only.clone(),
[first, rest @ ..] => {
tracing::warn!(
input_bytes = s.len(),
line_count = rest.len() + 1,
"ansi_escape_line: expected a single line"
);
first.clone()
}
}
}
pub fn ansi_escape(s: &str) -> Text<'static> {
// to_text() claims to be faster, but introduces complex lifetime issues
// such that it's not worth it.
match s.into_text() {
Ok(text) => text,
Err(err) => match err {
Error::NomError(message) => {
tracing::error!(
"ansi_to_tui NomError docs claim should never happen when parsing `{s}`: {message}"
);
panic!();
}
Error::Utf8Error(utf8error) => {
tracing::error!("Utf8Error: {utf8error}");
panic!();
}
},
}
}
#[cfg(test)]
#[path = "ansi_escape_tests.rs"]
mod tests;

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "app-server-client",
crate_name = "codex_app_server_client",
)

View File

@@ -0,0 +1,46 @@
[package]
name = "codex-app-server-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "codex_app_server_client"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
codex-app-server = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-app-server-transport = { workspace = true }
codex-arg0 = { workspace = true }
codex-cloud-client = { path = "../cloud-client" }
codex-config = { workspace = true }
codex-login = { workspace = true }
codex-core = { workspace = true }
codex-exec-server = { workspace = true }
codex-feedback = { workspace = true }
codex-protocol = { workspace = true }
codex-uds = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
color-eyre = { workspace = true }
futures = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["sync", "time", "rt"] }
tokio-tungstenite = { workspace = true }
toml = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,66 @@
# codex-app-server-client
Shared in-process app-server client used by conversational CLI surfaces:
- `codex-exec`
- `codex-tui`
## Purpose
This crate centralizes startup and lifecycle management for an in-process
`codex-app-server` runtime, so CLI clients do not need to duplicate:
- app-server bootstrap and initialize handshake
- in-memory request/event transport wiring
- lifecycle orchestration around caller-provided startup identity
- graceful shutdown behavior
## Startup identity
Callers pass both the app-server `SessionSource` and the initialize
`client_info.name` explicitly when starting the facade.
That keeps thread metadata (for example in `thread/list` and `thread/read`)
aligned with the originating runtime without baking TUI/exec-specific policy
into the shared client layer.
## Transport model
The in-process path uses typed channels:
- client -> server: `ClientRequest` / `ClientNotification`
- server -> client: `InProcessServerEvent`
- `ServerRequest`
- `ServerNotification`
- `LegacyNotification`
JSON serialization is still used at external transport boundaries
(stdio/websocket), but the in-process hot path is typed.
Typed requests still receive app-server responses through the JSON-RPC
result envelope internally. That is intentional: the in-process path is
meant to preserve app-server semantics while removing the process
boundary, not to introduce a second response contract.
## Bootstrap behavior
The client facade starts an already-initialized in-process runtime, but
thread bootstrap still follows normal app-server flow:
- caller sends `thread/start` or `thread/resume`
- app-server returns the immediate typed response
- richer session metadata may arrive later as a `SessionConfigured`
legacy event
Surfaces such as TUI and exec may therefore need a short bootstrap
phase where they reconcile startup response data with later events.
## Backpressure and shutdown
- Command queues and the embedded runtime remain bounded, using
`DEFAULT_IN_PROCESS_CHANNEL_CAPACITY` by default.
- The facade's local consumer event queue is unbounded and preserves notification
order. This keeps the worker draining the bounded runtime while a caller waits
for a request, preventing unread notifications from blocking its response.
- `shutdown()` performs a bounded graceful shutdown and then aborts if timeout
is exceeded.

View File

@@ -0,0 +1,269 @@
//! Channel-backed cloud client. Requests and retained replies stay on one owner;
//! events are drained independently so a foreground request cannot block its response.
use crate::AppServerEvent;
use crate::RequestResult;
use crate::TypedRequestError;
use codex_app_server_protocol::ClientNotification;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::Result as JsonRpcResult;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnStartParams;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
/// Operations the cloud worker must handle without forwarding to another backend.
/// Unsupported operations must return an explicit error; they must not claim success.
pub enum CloudOperation {
Request(Box<ClientRequest>),
/// Host project metadata stays on the private transport, outside the app-server wire.
StartProjectThread {
request_id: RequestId,
params: Box<codex_app_server_protocol::ThreadStartParams>,
project: codex_cloud_client::ProjectEnvironment,
},
SubmitUserMessage(Box<TurnStartParams>),
Notify(ClientNotification),
Resolve {
request_id: RequestId,
result: JsonRpcResult,
},
Reject {
request_id: RequestId,
error: JSONRPCErrorError,
},
Shutdown,
}
/// One server-decided admission, not completion. A duplicate carries identity
/// only; read history or observe the reply stream before inferring its status.
#[derive(serde::Serialize, serde::Deserialize)]
pub enum CloudUserMessageReceipt {
Started(Turn),
Steered(Turn),
Duplicate { turn_id: Option<String> },
}
/// An operation and its single response. Dropping a caller does not undo admission;
/// cloud workers must not retry mutations when the receiver has gone away.
pub struct CloudCommand {
pub operation: CloudOperation,
pub response: oneshot::Sender<io::Result<RequestResult>>,
}
#[derive(Clone)]
pub struct CloudRequestHandle {
commands: mpsc::Sender<CloudCommand>,
}
/// Tracks only losses queued for delivery. The worker remains the sole owner
/// of the active attachment. A successful replacement supersedes earlier losses
/// for that conversation, even if the replacement itself later ends.
#[derive(Clone, Default)]
pub(super) struct CloudStreamLosses(Arc<Mutex<HashMap<String, PendingLosses>>>);
#[derive(Default)]
struct PendingLosses {
remaining: usize,
superseded: usize,
}
impl CloudStreamLosses {
fn pending(&self) -> MutexGuard<'_, HashMap<String, PendingLosses>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn record(&self, thread_id: &str) {
self.pending()
.entry(thread_id.to_owned())
.or_default()
.remaining += 1;
}
pub(super) fn supersede(&self, thread_id: &str) {
if let Some(losses) = self.pending().get_mut(thread_id) {
losses.superseded = losses.remaining;
}
}
fn should_deliver(&self, thread_id: &str) -> bool {
let mut pending = self.pending();
let Some(losses) = pending.get_mut(thread_id) else {
return true;
};
// A single worker sends losses in the same order as it records them.
let deliver = losses.superseded == 0;
losses.superseded = losses.superseded.saturating_sub(1);
losses.remaining -= 1;
if losses.remaining == 0 {
pending.remove(thread_id);
}
deliver
}
}
pub struct CloudClient {
pub(super) stream_losses: CloudStreamLosses,
handle: CloudRequestHandle,
events: mpsc::UnboundedReceiver<AppServerEvent>,
}
impl CloudClient {
/// Creates a cloud transport. The owner must drain commands and stop when
/// its receiver closes. Event delivery is independent of request completion,
/// matching conventional transports; cloud workers must bound remote payloads.
pub fn channel(
capacity: usize,
) -> (
Self,
mpsc::Receiver<CloudCommand>,
mpsc::UnboundedSender<AppServerEvent>,
) {
let (commands, receiver) = mpsc::channel(capacity.max(1));
let (events, event_receiver) = mpsc::unbounded_channel();
(
Self {
stream_losses: CloudStreamLosses::default(),
handle: CloudRequestHandle { commands },
events: event_receiver,
},
receiver,
events,
)
}
pub(crate) fn request_handle(&self) -> CloudRequestHandle {
self.handle.clone()
}
pub(crate) async fn next_event(&mut self) -> Option<AppServerEvent> {
while let Some(event) = self.events.recv().await {
if let AppServerEvent::ThreadStreamDisconnected(error) = &event
&& !self.stream_losses.should_deliver(&error.thread_id)
{
continue;
}
return Some(event);
}
None
}
pub(crate) async fn request(&self, request: ClientRequest) -> io::Result<RequestResult> {
self.handle.request(request).await
}
pub(crate) async fn notify(&self, notification: ClientNotification) -> io::Result<()> {
self.handle.unit(CloudOperation::Notify(notification)).await
}
pub(crate) async fn resolve_server_request(
&self,
request_id: RequestId,
result: JsonRpcResult,
) -> io::Result<()> {
self.handle.resolve_server_request(request_id, result).await
}
pub(crate) async fn reject_server_request(
&self,
request_id: RequestId,
error: JSONRPCErrorError,
) -> io::Result<()> {
self.handle.reject_server_request(request_id, error).await
}
pub(crate) async fn shutdown(self) -> io::Result<()> {
tokio::time::timeout(
crate::SHUTDOWN_TIMEOUT,
self.handle.unit(CloudOperation::Shutdown),
)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "cloud backend shutdown timed out"))?
}
}
impl CloudRequestHandle {
pub(crate) async fn start_project_thread(
&self,
request_id: RequestId,
params: codex_app_server_protocol::ThreadStartParams,
project: codex_cloud_client::ProjectEnvironment,
) -> io::Result<RequestResult> {
self.send(CloudOperation::StartProjectThread {
request_id,
params: Box::new(params),
project,
})
.await
}
/// Submit once with a stable message ID and saved thread settings. The server
/// starts or steers; an error can mean admission is unknown. Never auto-resend.
pub async fn submit_user_message(
&self,
params: TurnStartParams,
) -> Result<CloudUserMessageReceipt, TypedRequestError> {
let response = self
.send(CloudOperation::SubmitUserMessage(Box::new(params)))
.await;
crate::decode_typed_response("cloud/submitUserMessage", response)
}
async fn send(&self, operation: CloudOperation) -> io::Result<RequestResult> {
let (response, result) = oneshot::channel();
self.commands
.send(CloudCommand {
operation,
response,
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "cloud backend is closed"))?;
result.await.map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"cloud backend dropped its response",
)
})?
}
async fn unit(&self, operation: CloudOperation) -> io::Result<()> {
self.send(operation)
.await?
.map(|_| ())
.map_err(|error| io::Error::other(error.message))
}
pub(crate) async fn request(&self, request: ClientRequest) -> io::Result<RequestResult> {
self.send(CloudOperation::Request(Box::new(request))).await
}
pub(crate) async fn resolve_server_request(
&self,
request_id: RequestId,
result: JsonRpcResult,
) -> io::Result<()> {
self.unit(CloudOperation::Resolve { request_id, result })
.await
}
pub(crate) async fn reject_server_request(
&self,
request_id: RequestId,
error: JSONRPCErrorError,
) -> io::Result<()> {
self.unit(CloudOperation::Reject { request_id, error })
.await
}
}
#[cfg(test)]
#[path = "cloud_tests.rs"]
mod tests;

View File

@@ -0,0 +1,54 @@
//! Opens the internal Cloud preview with the selected ChatGPT credentials and local transport policy.
use super::start_worker;
use crate::AppServerClient;
use crate::legacy_core::config::Config;
use codex_app_server_protocol as protocol;
use codex_cloud_client as cloud;
use codex_login::token_data::parse_jwt_expiration;
use codex_protocol::account::PlanType;
use color_eyre::eyre::Result;
use color_eyre::eyre::bail;
use color_eyre::eyre::eyre;
const ORIGIN: &str = "https://codex-cloud-backend.chatgpt.com";
pub async fn connect(config: &Config) -> Result<AppServerClient> {
// The preview borrows Local's policy without owning credential updates.
let factory = config.http_client_factory();
let policy = factory.network_policy().clone().for_current_account();
let factory = factory.with_network_policy(policy);
let auth = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await?
.ok_or_else(|| eyre!("Sign in with ChatGPT and reopen Codex to use Cloud."))?;
if !auth.is_chatgpt_auth() || auth.is_fedramp_account() {
bail!("This account is not supported by the cloud conversation preview.");
}
let account_id = auth
.get_account_id()
.ok_or_else(|| eyre!("Cloud requires a selected account."))?;
let token = auth.get_token()?;
if let Ok(Some(expires)) = parse_jwt_expiration(&token)
&& std::time::SystemTime::from(expires) <= std::time::SystemTime::now()
{
bail!("Your ChatGPT credential expired. Reopen Codex to reconnect.");
}
factory.network_policy().acquire(&ORIGIN.parse()?)?;
let credentials = cloud::Credentials::new(&token, &account_id)?;
let client = cloud::Client::new(&factory, ORIGIN, credentials)?;
Ok(start_worker(
client,
protocol::GetAccountResponse {
user_id: auth.get_chatgpt_user_id(),
account: Some(protocol::Account::Chatgpt {
email: auth.get_account_email(),
plan_type: auth.account_plan_type().unwrap_or(PlanType::Unknown),
workspace_name: None,
}),
requires_openai_auth: true,
workspace_routing: None,
},
))
}

View File

@@ -0,0 +1,135 @@
#![cfg(test)]
//! Ensures only a successfully attached thread can receive new turns.
use super::*;
use futures::stream;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn failed_replacement_keeps_old_thread_until_new_attachment_succeeds() -> Result<()> {
let (output, mut notifications) = mpsc::unbounded_channel();
let mut replies = Replies::default();
replies
.replace("old", async { Ok(stream::pending().boxed()) }, &output)
.await?;
for failure in [
Err(cloud::Error::InvalidResponse),
Ok(stream::empty().boxed()),
Ok(stream::iter([Err(cloud::Error::InvalidResponse)]).boxed()),
] {
assert!(
replies
.replace("new", async { failure }, &output)
.await
.is_err()
);
replies.admit_turn("old", &output)?;
assert!(replies.admit_turn("new", &output).is_err());
}
let (close, closed) = tokio::sync::oneshot::channel::<()>();
let stream = stream::once(async move {
let _ = closed.await;
Err(cloud::Error::InvalidResponse)
})
.boxed();
replies
.replace("new", async { Ok(stream) }, &output)
.await?;
replies.detach("old");
assert!(replies.admit_turn("old", &output).is_err());
replies.admit_turn("new", &output)?;
let _ = close.send(());
assert!(replies.admit_turn("new", &output).is_err());
let AppServerEvent::ThreadStreamDisconnected(notification) = notifications.try_recv()? else {
panic!("expected a disconnect notification");
};
assert_eq!(
serde_json::to_value(protocol::ServerNotification::Error(*notification))?,
serde_json::to_value(protocol::ServerNotification::Error(cloud_error(
"new",
"Cloud stream ended. Reopen the conversation to reconnect."
)))?
);
Ok(())
}
#[tokio::test]
async fn successful_reopen_supersedes_only_earlier_losses_for_that_thread() -> Result<()> {
let (mut client, _commands, output) = CloudClient::channel(/*capacity*/ 1);
let mut replies = Replies {
stream_losses: client.stream_losses.clone(),
..Default::default()
};
for id in ["reopened", "different", "reopened"] {
let (sender, stream) = futures::channel::mpsc::unbounded();
replies
.replace(id, async { Ok(stream.boxed()) }, &output)
.await?;
drop(sender);
replies.forward_next(&output).await;
}
assert!(
replies
.replace("reopened", async { Ok(stream::empty().boxed()) }, &output)
.await
.is_err()
);
// The first EOF was followed by a successful reopen. A different thread's
// EOF and the reopened thread's newer EOF must still be delivered, in order.
drop(output);
for expected in ["different", "reopened"] {
let Some(AppServerEvent::ThreadStreamDisconnected(error)) = client.next_event().await
else {
panic!("expected a thread stream disconnect");
};
assert_eq!(
*error,
cloud_error(
expected,
"Cloud stream ended. Reopen the conversation to reconnect."
)
);
}
assert!(client.next_event().await.is_none());
Ok(())
}
#[tokio::test]
async fn attachment_status_follows_its_server_notifications() -> Result<()> {
let (output, _notifications) = mpsc::unbounded_channel();
let mut replies = Replies::default();
let notifications: [&[u8]; 3] = [
b"\x1a\x0d\x12\x0b\x0a\x06\x22\x04\x0a\x02\x08\x01\x12\x01t", // t is waiting
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01x", // x is idle
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01t", // t is idle
];
let stream =
stream::iter(notifications.map(|bytes| Ok(cloud::Event::Notification(bytes.into()))));
replies
.replace("t", async { Ok(stream.boxed()) }, &output)
.await?;
let waiting = cloud::ThreadStatus::Active {
active_flags: vec![cloud::ThreadActiveFlag::WaitingOnApproval],
};
assert_eq!(replies.thread_status("t"), Some(&waiting));
replies.forward_next(&output).await;
assert_eq!(replies.thread_status("t"), Some(&waiting));
replies.forward_next(&output).await;
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
replies.forward_next(&output).await;
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
replies
.replace("t", async { Ok(stream::pending().boxed()) }, &output)
.await?;
assert_eq!(replies.thread_status("t"), None);
Ok(())
}

View File

@@ -0,0 +1,172 @@
//! Converts supported cloud transcript events without interpreting executor paths locally.
use codex_app_server_protocol as protocol;
use codex_cloud_client as cloud;
use codex_protocol::models::ImageDetail;
use color_eyre::eyre::Result;
use color_eyre::eyre::bail;
pub(super) fn turn(summary: cloud::TurnSummary) -> Result<protocol::Turn> {
Ok(protocol::Turn {
id: summary.id,
root_turn_id: None,
items: Vec::new(),
items_view: protocol::TurnItemsView::NotLoaded,
status: match summary.status {
cloud::TurnStatus::Completed => protocol::TurnStatus::Completed,
cloud::TurnStatus::Interrupted => protocol::TurnStatus::Interrupted,
cloud::TurnStatus::Failed => protocol::TurnStatus::Failed,
cloud::TurnStatus::InProgress => protocol::TurnStatus::InProgress,
cloud::TurnStatus::Unknown(_) => {
bail!("The cloud returned an unsupported turn status.");
}
},
error: summary.error.map(|error| protocol::TurnError {
message: error.message,
additional_details: error.additional_details,
codex_error_info: None,
misalignment: None,
}),
started_at: summary.started_at,
completed_at: summary.completed_at,
duration_ms: summary.duration_ms,
})
}
pub(super) fn transcript(
thread_id: String,
update: cloud::TranscriptUpdate,
) -> Result<Option<protocol::ServerNotification>> {
use protocol::ServerNotification as Notification;
Ok(Some(match update {
cloud::TranscriptUpdate::TurnStarted(summary) => {
Notification::TurnStarted(protocol::TurnStartedNotification {
thread_id,
turn: turn(summary)?,
})
}
cloud::TranscriptUpdate::TurnCompleted(summary) => {
Notification::TurnCompleted(protocol::TurnCompletedNotification {
thread_id,
turn: turn(summary)?,
})
}
cloud::TranscriptUpdate::AgentMessageDelta(delta) => {
Notification::AgentMessageDelta(protocol::AgentMessageDeltaNotification {
thread_id,
turn_id: delta.turn_id,
item_id: delta.item_id,
delta: delta.delta,
})
}
cloud::TranscriptUpdate::ItemStarted(item) => {
let Some(content) = item_summary(item.item) else {
return Ok(None);
};
Notification::ItemStarted(protocol::ItemStartedNotification::new(
thread_id,
item.turn_id,
content.payload,
item.at_ms,
))
}
cloud::TranscriptUpdate::ItemCompleted(item) => {
let Some(content) = item_summary(item.item) else {
return Ok(None);
};
Notification::ItemCompleted(protocol::ItemCompletedNotification::new(
thread_id,
item.turn_id,
content.payload,
/*started_at_ms*/ None,
item.at_ms,
))
}
cloud::TranscriptUpdate::CommandOutputDelta(_)
| cloud::TranscriptUpdate::FileChangeOutputDelta(_)
| cloud::TranscriptUpdate::FileChangePatchUpdated(_) => return Ok(None),
}))
}
pub(super) fn item_summary(item: cloud::ItemSummary) -> Option<protocol::ThreadItem> {
let payload = match item {
cloud::ItemSummary::UserMessage {
id,
client_id,
content,
} => protocol::ThreadItemPayload::UserMessage {
id,
client_id,
content: content
.into_iter()
.map(|item| match item {
cloud::UserMessageInput::Text {
text,
text_elements,
} => protocol::UserInput::Text {
text,
text_elements: text_elements
.into_iter()
.map(|element| {
protocol::TextElement::new(
protocol::ByteRange {
start: element.start,
end: element.end,
},
element.placeholder,
)
})
.collect(),
},
cloud::UserMessageInput::Image { image, detail } => {
protocol::UserInput::Image {
image: match image {
cloud::ImageReference::Url(url) => {
protocol::ImageReference::Inline { url }
}
cloud::ImageReference::FileId(file_id) => {
protocol::ImageReference::File { file_id }
}
},
detail: detail.map(|detail| match detail {
cloud::ImageDetail::Auto => ImageDetail::Auto,
cloud::ImageDetail::Low => ImageDetail::Low,
cloud::ImageDetail::High => ImageDetail::High,
cloud::ImageDetail::Original => ImageDetail::Original,
}),
}
}
})
.collect(),
},
cloud::ItemSummary::AgentMessage {
id,
text,
questions,
} => protocol::ThreadItemPayload::AgentMessage {
moderation: None,
id,
text,
phase: None,
memory_citation: None,
delivery: None,
questions: questions.map(|questions| {
questions
.into_iter()
.map(|question| protocol::AsyncUserInputQuestion {
title: question.title,
options: question.options,
})
.collect()
}),
},
cloud::ItemSummary::Reasoning { .. }
| cloud::ItemSummary::CommandExecution(_)
| cloud::ItemSummary::FileChange { .. } => return None,
};
Some(protocol::ThreadItem::untimed(payload))
}
#[cfg(test)]
#[path = "events_tests.rs"]
mod tests;

View File

@@ -0,0 +1,98 @@
#![cfg(test)]
//! Covers the user receipt and final assistant message presented by Cloud.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn image_receipt_preserves_submission_identity_and_attachment() {
let label = "[Image #1]";
let actual = item_summary(cloud::ItemSummary::UserMessage {
id: "item-1".into(),
client_id: Some("submission-1".into()),
content: vec![
cloud::UserMessageInput::Image {
image: cloud::ImageReference::FileId("file-synthetic".into()),
detail: Some(cloud::ImageDetail::High),
},
cloud::UserMessageInput::Text {
text: format!("{label} describe"),
text_elements: vec![cloud::UserMessageTextElement {
start: 0,
end: label.len(),
placeholder: Some(label.into()),
}],
},
],
});
assert_eq!(
actual,
Some(protocol::ThreadItem::untimed(
protocol::ThreadItemPayload::UserMessage {
id: "item-1".into(),
client_id: Some("submission-1".into()),
content: vec![
protocol::UserInput::Image {
image: protocol::ImageReference::File {
file_id: "file-synthetic".into(),
},
detail: Some(ImageDetail::High),
},
protocol::UserInput::Text {
text: format!("{label} describe"),
text_elements: vec![protocol::TextElement::new(
protocol::ByteRange {
start: 0,
end: label.len(),
},
Some(label.into()),
)],
},
],
},
))
);
}
#[test]
fn completed_reply_preserves_the_full_text_questions_and_timestamp() -> Result<()> {
let item = cloud::ItemSummary::AgentMessage {
id: "reply".into(),
text: "Choose one".into(),
questions: Some(vec![cloud::AgentQuestion {
title: "Which?".into(),
options: Some(vec!["One".into(), "Two".into()]),
}]),
};
let update = cloud::TranscriptUpdate::ItemCompleted(cloud::ItemLifecycle {
turn_id: "turn".into(),
at_ms: 45,
item,
});
let Some(protocol::ServerNotification::ItemCompleted(actual)) =
transcript("thread".into(), update)?
else {
panic!("expected a completed message");
};
assert_eq!(
actual,
protocol::ItemCompletedNotification::new(
"thread".into(),
"turn".into(),
protocol::ThreadItemPayload::AgentMessage {
moderation: None,
id: "reply".into(),
text: "Choose one".into(),
phase: None,
memory_citation: None,
delivery: None,
questions: Some(vec![protocol::AsyncUserInputQuestion {
title: "Which?".into(),
options: Some(vec!["One".into(), "Two".into()]),
}]),
},
/*started_at_ms*/ None,
/*completed_at_ms*/ 45
)
);
Ok(())
}

View File

@@ -0,0 +1,348 @@
//! Adapts native Cloud requests and the currently open conversation’s reply stream.
//! A replacement becomes active only after its native attachment opens successfully.
mod auth;
mod events;
mod requests;
use crate::AppServerClient;
use crate::AppServerEvent;
use crate::CloudClient;
use crate::CloudOperation;
use crate::cloud::CloudStreamLosses;
use codex_app_server_protocol as protocol;
use codex_cloud_client as cloud;
use color_eyre::eyre::Result;
use color_eyre::eyre::bail;
use color_eyre::eyre::eyre;
use futures::FutureExt;
use futures::StreamExt;
use futures::stream::BoxStream;
use serde_json::Value;
use tokio::sync::mpsc;
pub use auth::connect;
type ReplyStream = BoxStream<'static, Result<cloud::Event, cloud::Error>>;
/// Rejected locally before an admission request can be sent.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
struct PreflightRejection(&'static str);
#[derive(Debug, thiserror::Error)]
#[error("Cloud stream is not connected. Reopen the conversation before sending.")]
struct MissingReplyAttachment;
struct Attachment {
thread_id: String,
stream: ReplyStream,
}
#[derive(Default)]
struct Replies {
active: Option<Attachment>,
stream_losses: CloudStreamLosses,
// Keep the last observed status through EOF until this conversation is unloaded.
latest_status: Option<(String, cloud::ThreadStatus)>,
}
impl Replies {
async fn forward_next(&mut self, output: &mpsc::UnboundedSender<AppServerEvent>) {
let Some(active) = &mut self.active else {
return std::future::pending().await;
};
match active.stream.next().await {
Some(Ok(event)) => forward(&active.thread_id, event, output, &mut self.latest_status),
Some(Err(_)) | None => {
let error = cloud_error(
&active.thread_id,
"Cloud stream ended. Reopen the conversation to reconnect.",
);
self.active = None;
self.stream_losses.record(&error.thread_id);
let _ = output.send(AppServerEvent::ThreadStreamDisconnected(Box::new(error)));
}
}
}
async fn while_listening<T>(
&mut self,
future: impl Future<Output = T>,
output: &mpsc::UnboundedSender<AppServerEvent>,
) -> T {
tokio::pin!(future);
loop {
tokio::select! {
biased;
result = &mut future => return result,
() = self.forward_next(output) => {}
}
}
}
async fn replace(
&mut self,
id: &str,
open: impl Future<Output = Result<ReplyStream, cloud::Error>>,
output: &mpsc::UnboundedSender<AppServerEvent>,
) -> Result<()> {
let mut stream = self.while_listening(open, output).await?;
// A server can close Attach immediately after returning successful headers.
// A healthy idle stream needs no event to prove that it is ready.
let first_event = match tokio::task::unconstrained(stream.next()).now_or_never() {
Some(None | Some(Err(_))) => bail!(
"Cloud conversation activated but its stream did not connect. Reopen it before sending."
),
Some(Some(Ok(event))) => Some(event),
None => None,
};
self.active = Some(Attachment {
thread_id: id.to_owned(),
stream,
});
self.stream_losses.supersede(id);
self.latest_status = None;
if let Some(event) = first_event {
forward(id, event, output, &mut self.latest_status);
}
Ok(())
}
fn thread_status(&self, id: &str) -> Option<&cloud::ThreadStatus> {
self.latest_status
.as_ref()
.filter(|(thread_id, _)| thread_id == id)
.map(|(_, status)| status)
}
fn detach(&mut self, id: &str) {
if self.thread_status(id).is_some() {
self.latest_status = None;
}
if self
.active
.as_ref()
.is_some_and(|active| active.thread_id == id)
{
self.active = None;
}
}
fn admit_turn(
&mut self,
id: &str,
output: &mpsc::UnboundedSender<AppServerEvent>,
) -> Result<(), MissingReplyAttachment> {
// Notice a ready disconnect before sending. A continuous stream of events
// must still allow commands to make progress.
let _ = tokio::task::unconstrained(self.forward_next(output)).now_or_never();
if self
.active
.as_ref()
.is_none_or(|active| active.thread_id != id)
{
return Err(MissingReplyAttachment);
}
Ok(())
}
}
/// Opens an app-server client backed by the authenticated native Cloud client.
fn start_worker(client: cloud::Client, account: protocol::GetAccountResponse) -> AppServerClient {
let (app_client, commands, output) = CloudClient::channel(/*capacity*/ 32);
let mut requests = requests::Requests {
client,
account,
loaded: None,
warned_partial_history: None,
};
let mut replies = Replies {
stream_losses: app_client.stream_losses.clone(),
..Default::default()
};
tokio::spawn(async move {
run_worker(commands, &mut requests, &mut replies, &output).await;
});
AppServerClient::Cloud(app_client)
}
async fn run_worker(
mut commands: mpsc::Receiver<crate::CloudCommand>,
requests: &mut requests::Requests,
replies: &mut Replies,
output: &mpsc::UnboundedSender<AppServerEvent>,
) {
loop {
let command = tokio::select! {
_ = output.closed() => return,
() = replies.forward_next(output) => continue,
command = commands.recv() => match command { Some(command) => command, None => return },
};
let user_message_submission =
matches!(&command.operation, CloudOperation::SubmitUserMessage(_));
let request = match command.operation {
CloudOperation::Shutdown => {
let _ = command.response.send(Ok(Ok(Value::Null)));
return;
}
CloudOperation::Request(request) => {
Ok((*request, cloud::SubmissionMode::StartIfIdle, None))
}
CloudOperation::StartProjectThread {
request_id,
params,
project,
} => Ok((
protocol::ClientRequest::ThreadStart {
request_id,
params: *params,
},
cloud::SubmissionMode::StartIfIdle,
Some(project),
)),
CloudOperation::SubmitUserMessage(params) => Ok((
protocol::ClientRequest::TurnStart {
// Native admission is keyed by the caller's stable message ID.
request_id: protocol::RequestId::Integer(0),
params: *params,
},
cloud::SubmissionMode::Steer,
None,
)),
CloudOperation::Notify(_) => {
Err(eyre!("Cloud client notifications are not supported yet."))
}
CloudOperation::Resolve { .. } | CloudOperation::Reject { .. } => Err(eyre!(
"Answer this cloud approval in another client; TUI approval replies are not supported yet."
)),
};
let result = match request {
Ok((request, mode, project)) => tokio::select! {
_ = output.closed() => return,
result = handle_request(request, mode, project, requests, replies, output) => result,
},
Err(error) => Err(error),
};
let result = result.map_err(|error| protocol::JSONRPCErrorError {
code: if error
.downcast_ref::<requests::UnsupportedOperation>()
.is_some()
{
-32601
} else if error.is::<PreflightRejection>()
|| user_message_submission && error.is::<MissingReplyAttachment>()
{
-32602
} else {
-32000
},
message: error.to_string(),
data: None,
});
let _ = command.response.send(Ok(result));
}
}
async fn handle_request(
request: protocol::ClientRequest,
mode: cloud::SubmissionMode,
project: Option<cloud::ProjectEnvironment>,
requests: &mut requests::Requests,
replies: &mut Replies,
output: &mpsc::UnboundedSender<AppServerEvent>,
) -> Result<Value> {
if let protocol::ClientRequest::ThreadRead { params, .. } = &request {
return requests.read_thread(params, replies.thread_status(&params.thread_id));
}
if let protocol::ClientRequest::ThreadUnsubscribe { params, .. } = &request {
let status = if requests
.loaded
.as_ref()
.is_some_and(|loaded| loaded.thread.id == params.thread_id)
{
replies.detach(&params.thread_id);
requests.loaded = None;
protocol::ThreadUnsubscribeStatus::Unsubscribed
} else {
protocol::ThreadUnsubscribeStatus::NotSubscribed
};
return Ok(serde_json::json!({ "status": status }));
}
if let protocol::ClientRequest::TurnStart { params, .. } = &request {
replies.admit_turn(&params.thread_id, output)?;
}
match replies
.while_listening(requests.handle(request, mode, project, output), output)
.await?
{
requests::Response::Value(value) => Ok(value),
requests::Response::Attach(settings) => {
let id = &settings.thread.id;
let result = serde_json::to_value(&settings)?;
replies
.replace(id, requests.client.attach(id), output)
.await?;
requests.loaded = Some(settings);
requests.warned_partial_history = None;
Ok(result)
}
}
}
fn forward(
id: &str,
event: cloud::Event,
output: &mpsc::UnboundedSender<AppServerEvent>,
latest_status: &mut Option<(String, cloud::ThreadStatus)>,
) {
if let Some(status) = event.thread_status_for(id) {
*latest_status = Some((id.to_owned(), status));
return;
}
let notification = match event {
cloud::Event::Transcript(event) => match events::transcript(event.thread_id, event.update) {
Ok(Some(notification)) => notification,
Ok(None) => return,
Err(_) => protocol::ServerNotification::Error(cloud_error(
id,
"The cloud sent an unsupported transcript event.",
)),
},
cloud::Event::ServerRequest(_) => protocol::ServerNotification::Warning(protocol::WarningNotification {
thread_id: Some(id.to_owned()),
message: "This cloud turn requested an unsupported interaction. Open it in another client to continue.".into(),
}),
cloud::Event::Notification(_) => return,
};
send_notification(output, notification);
}
fn send_notification(
output: &mpsc::UnboundedSender<AppServerEvent>,
notification: protocol::ServerNotification,
) {
let _ = output.send(AppServerEvent::ServerNotification(Box::new(notification)));
}
fn cloud_error(id: &str, message: &str) -> protocol::ErrorNotification {
protocol::ErrorNotification {
thread_id: id.to_owned(),
turn_id: String::new(),
will_retry: false,
error: protocol::TurnError {
message: message.to_owned(),
additional_details: None,
codex_error_info: None,
misalignment: None,
},
}
}
#[cfg(test)]
#[path = "connection_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "submission_tests.rs"]
mod submission_tests;

View File

@@ -0,0 +1,201 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn ordinary_multi_backend_resume_queries_cloud_interactive_threads_on_every_page() {
// The mixed picker has no shared cwd/provider filter. It sends conventional
// interactive source names, even when the connection belongs to Cloud.
for (cursor, state_db_only) in [(None, true), (Some("page-2"), false)] {
let params = serde_json::from_value(json!({
"currentAccountOnly": true,
"cursor": cursor,
"limit": 25,
"sortKey": "updated_at",
"modelProviders": [],
"sourceKinds": ["cli", "vscode"],
"archived": false,
"useStateDbOnly": state_db_only,
}))
.unwrap();
let query = thread_list_query(params).unwrap();
assert_eq!(query.cursor.as_deref(), cursor);
assert_eq!(query.limit, Some(25));
assert!(matches!(query.sort_key, cloud::ThreadSortKey::UpdatedAt));
assert!(matches!(
query.sort_direction,
cloud::ThreadSortDirection::Desc
));
assert!(query.originators.is_empty());
}
}
#[test]
fn unsupported_filters_do_not_return_unrelated_cloud_rows() {
for filter in [
json!({"archived": true}),
json!({"sourceKinds": ["exec"]}),
json!({"attachedToThreadId": "other"}),
json!({"modelProviders": ["other"]}),
] {
let params = serde_json::from_value(filter).unwrap();
assert!(thread_list_query(params).is_err());
}
}
fn message() -> protocol::TurnStartParams {
let text = |text: &str| protocol::UserInput::Text {
text: text.to_owned(),
text_elements: Vec::new(),
};
protocol::TurnStartParams {
thread_id: "thread-a".into(),
client_user_message_id: Some("submission-a".into()),
turn_trigger: Some("safety_recourse_follow_up".into()),
input: vec![text("one"), text("two")],
..Default::default()
}
}
#[test]
fn user_input_uses_stable_id_and_the_existing_cloud_configuration() {
let request = cloud_message(message()).unwrap();
assert_eq!(request.thread_id, "thread-a");
assert_eq!(request.client_user_message_id, "submission-a");
assert_eq!(
request.input,
vec![cloud::UserMessageInput::Text {
text: "one\ntwo".into(),
text_elements: Vec::new(),
}]
);
assert_eq!(
request.turn_trigger.as_deref(),
Some("safety_recourse_follow_up")
);
assert!(matches!(request.mode, cloud::SubmissionMode::StartIfIdle));
assert!(!request.shared_access);
for tier in ["default", "priority"] {
assert!(
cloud_message(protocol::TurnStartParams {
service_tier_for_turn: Some(tier.into()),
..message()
})
.is_err()
);
}
assert!(
cloud_message(protocol::TurnStartParams {
client_user_message_id: None,
..message()
})
.is_err()
);
}
#[test]
fn image_submission_keeps_attachment_markers_and_input_order() {
let label = "[Image #1]";
let request = cloud_message(protocol::TurnStartParams {
input: vec![
protocol::UserInput::Image {
image: protocol::ImageReference::File {
file_id: "file-synthetic".into(),
},
detail: Some(ImageDetail::High),
},
protocol::UserInput::Text {
text: format!("{label} describe"),
text_elements: vec![protocol::TextElement::new(
protocol::ByteRange {
start: 0,
end: label.len(),
},
Some(label.into()),
)],
},
],
..message()
})
.unwrap();
assert_eq!(
request.input,
vec![
cloud::UserMessageInput::Image {
image: cloud::ImageReference::FileId("file-synthetic".into()),
detail: Some(cloud::ImageDetail::High),
},
cloud::UserMessageInput::Text {
text: format!("{label} describe"),
text_elements: vec![cloud::UserMessageTextElement {
start: 0,
end: label.len(),
placeholder: Some(label.into()),
}],
},
]
);
}
#[test]
fn duplicate_and_queued_admissions_never_invent_a_running_turn() {
for outcome in [
cloud::AdmissionOutcome::Duplicate { turn_id: None },
cloud::AdmissionOutcome::Duplicate {
turn_id: Some("completed-or-running".into()),
},
cloud::AdmissionOutcome::Queued {
submission_id: "queued".into(),
},
] {
assert!(
admitted_turn(outcome)
.unwrap_err()
.to_string()
.contains("already accepted")
);
}
}
#[test]
fn admission_receipts_preserve_server_turns_and_duplicate_identity() -> Result<()> {
let turn = |id: &str, status| cloud::TurnSummary {
id: id.into(),
status,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
};
for (outcome, expected) in [
(
cloud::AdmissionOutcome::Started(turn("u", cloud::TurnStatus::InProgress)),
("started", "u", protocol::TurnStatus::InProgress),
),
(
cloud::AdmissionOutcome::Steered(turn("v", cloud::TurnStatus::Completed)),
("steered", "v", protocol::TurnStatus::Completed),
),
] {
let (kind, turn) = match admitted_message(outcome)? {
CloudUserMessageReceipt::Started(turn) => ("started", turn),
CloudUserMessageReceipt::Steered(turn) => ("steered", turn),
CloudUserMessageReceipt::Duplicate { .. } => panic!("expected a turn"),
};
assert_eq!((kind, turn.id.as_str(), turn.status), expected);
}
for turn_id in [None, Some("original".into())] {
let CloudUserMessageReceipt::Duplicate { turn_id: actual } =
admitted_message(cloud::AdmissionOutcome::Duplicate {
turn_id: turn_id.clone(),
})?
else {
panic!("a duplicate must not become a running turn");
};
assert_eq!(actual, turn_id);
}
Ok(())
}

View File

@@ -0,0 +1,410 @@
//! Maps conversation requests onto native Cloud operations.
use super::PreflightRejection;
use super::events;
use super::send_notification;
use crate::CloudUserMessageReceipt;
use codex_app_server_protocol as protocol;
use codex_cloud_client as cloud;
use codex_protocol::models::ImageDetail;
use color_eyre::eyre::Result;
use color_eyre::eyre::bail;
use color_eyre::eyre::eyre;
use serde_json::Value;
use serde_json::json;
use tokio::sync::mpsc;
#[derive(Debug, thiserror::Error)]
#[error("{0} is not supported by the cloud backend yet.")]
pub(super) struct UnsupportedOperation(pub(super) String);
pub(super) struct Requests {
pub(super) client: cloud::Client,
pub(super) account: protocol::GetAccountResponse,
pub(super) loaded: Option<Box<protocol::ThreadResumeResponse>>,
pub(super) warned_partial_history: Option<String>,
}
pub(super) enum Response {
Value(Value),
Attach(Box<protocol::ThreadResumeResponse>),
}
impl Requests {
pub(super) fn read_thread(
&self,
params: &protocol::ThreadReadParams,
status: Option<&cloud::ThreadStatus>,
) -> Result<Value> {
if params.include_turns {
bail!("Use paginated history for cloud conversations.");
}
let loaded = self
.loaded
.as_deref()
.filter(|loaded| loaded.thread.id == params.thread_id)
.ok_or_else(|| eyre!("Open this cloud conversation before reading its transcript."))?;
let mut thread = serde_json::to_value(&loaded.thread)?;
if let Some(status) = status {
thread["status"] = serde_json::to_value(status)?;
}
Ok(json!({"thread": thread, "readState": null}))
}
pub(super) async fn handle(
&mut self,
request: protocol::ClientRequest,
mode: cloud::SubmissionMode,
project: Option<cloud::ProjectEnvironment>,
output: &mpsc::UnboundedSender<crate::AppServerEvent>,
) -> Result<Response> {
use protocol::ClientRequest as Request;
let value = match request {
Request::GetAccount { .. } => serde_json::to_value(&self.account)?,
Request::ThreadList { params, .. } => {
let query = thread_list_query(params)?;
let mut page = self.client.list_threads(&query).await?;
for thread in &mut page.data {
use_paginated_history(thread);
}
serde_json::to_value(page)?
}
Request::ThreadStart { mut params, .. } => {
let model = params.model.take();
let provider = params.model_provider.take();
if params.ephemeral == Some(false) {
params.ephemeral = None;
}
if params != protocol::ThreadStartParams::default() {
bail!(
"Cloud conversations start with server defaults. Custom settings are not supported yet."
);
}
let settings = self.client.prewarm_thread(model, provider, project).await?;
return attach_response(settings);
}
Request::ThreadResume { params, .. } => {
let supported = protocol::ThreadResumeParams {
thread_id: params.thread_id.clone(),
exclude_turns: true,
..Default::default()
};
if params != supported {
bail!(
"Cloud conversations resume by ID with saved settings. Set excludeTurns to true and load history separately."
);
}
let settings = self.client.activate(&params.thread_id).await?;
return attach_response(settings);
}
Request::ThreadLoadedList { .. } => {
let ids = self
.loaded
.iter()
.map(|loaded| &loaded.thread.id)
.collect::<Vec<_>>();
json!({"data": ids, "nextCursor": null})
}
Request::ThreadTurnsList { params, .. } => {
if params.items_view != Some(protocol::TurnItemsView::NotLoaded) {
bail!("Read cloud turn items separately with thread/items/list.");
}
let page = self
.client
.list_turns(&cloud::ListTurnsRequest {
thread_id: params.thread_id,
page: cloud::HistoryQuery {
cursor: params.cursor,
limit: params.limit,
order: history_order(
params
.sort_direction
.unwrap_or(protocol::SortDirection::Desc),
),
..Default::default()
},
})
.await?;
serde_json::to_value(protocol::ThreadTurnsListResponse {
data: page
.data
.into_iter()
.map(|entry| events::turn(entry.summary))
.collect::<Result<_>>()?,
next_cursor: page.next_cursor,
backwards_cursor: page.backwards_cursor,
})?
}
Request::ThreadItemsList { params, .. } => {
let cursor = match params.cursor {
Some(protocol::ThreadItemsListCursor::Opaque(cursor)) => Some(cursor),
None => None,
Some(protocol::ThreadItemsListCursor::Anchor(_)) => {
bail!("Cloud item anchors are not supported yet.")
}
};
let page = self
.client
.list_items(&cloud::ListItemsRequest {
thread_id: params.thread_id.clone(),
turn_id: params.turn_id,
page: cloud::HistoryQuery {
cursor,
limit: params.limit,
order: history_order(
params
.sort_direction
.unwrap_or(protocol::SortDirection::Asc),
),
..Default::default()
},
})
.await?;
let size = page.data.len();
let data = page
.data
.into_iter()
.filter_map(|entry| {
Some(protocol::ThreadItemEntry {
turn_id: entry.turn_id,
item: events::item_summary(entry.summary?)?,
output_deferred: false,
started_at_ms: entry.started_at_ms,
completed_at_ms: entry.completed_at_ms,
})
})
.collect::<Vec<_>>();
if data.len() != size
&& self.warned_partial_history.as_ref() != Some(&params.thread_id)
{
self.warned_partial_history = Some(params.thread_id.clone());
let warning = protocol::WarningNotification {
thread_id: Some(params.thread_id),
message: "Some Cloud history items cannot be displayed in this preview."
.to_owned(),
};
send_notification(output, protocol::ServerNotification::Warning(warning));
}
serde_json::to_value(protocol::ThreadItemsListResponse {
data,
next_cursor: page.next_cursor,
backwards_cursor: page.backwards_cursor,
})?
}
Request::TurnStart { params, .. } => {
let mut message = cloud_message(params)?;
message.mode = mode;
let admission = match self.client.add_user_message(&message).await {
Err(cloud::MutationError::InvalidRequest) => {
return Err(PreflightRejection(
"The Cloud message is empty, invalid, or too large.",
)
.into());
}
result => result?,
};
if matches!(mode, cloud::SubmissionMode::Steer) {
serde_json::to_value(admitted_message(admission.outcome)?)?
} else {
let turn = admitted_turn(admission.outcome)?;
serde_json::to_value(protocol::TurnStartResponse { turn })?
}
}
Request::TurnInterrupt { params, .. } => {
self.client
.interrupt_turn(&cloud::InterruptTurnRequest {
thread_id: params.thread_id,
turn_id: params.turn_id,
shared_access: false,
})
.await?;
serde_json::to_value(protocol::TurnInterruptResponse {})?
}
other => return Err(UnsupportedOperation(other.method_name().to_owned()).into()),
};
Ok(Response::Value(value))
}
}
fn attach_response(mut settings: cloud::ThreadActivation) -> Result<Response> {
use_paginated_history(&mut settings.thread);
let resolved = serde_json::from_value(serde_json::to_value(settings)?)
.map_err(|_| eyre!("The cloud returned unsupported conversation settings."))?;
Ok(Response::Attach(resolved))
}
// Cloud serves history in pages even when an older thread used the legacy rollout format.
fn use_paginated_history(thread: &mut cloud::ThreadSnapshot) {
thread.history_mode = cloud::ThreadHistoryMode::Paginated;
}
fn thread_list_query(params: protocol::ThreadListParams) -> Result<cloud::ThreadListQuery> {
use protocol::ThreadSourceKind::Cli;
use protocol::ThreadSourceKind::VsCode;
// The resume picker's ordinary interactive list maps to Cloud's own interactive default.
// Its explicit CLI/VS Code defaults are conventional source names.
let sources = params.source_kinds.as_deref().unwrap_or_default();
if !matches!(sources, [] | [Cli, VsCode] | [VsCode, Cli])
|| params.archived == Some(true)
|| params.cwd.is_some()
|| params.search_term.is_some()
|| params.section_id.is_some()
|| params.project_id.is_some()
|| params.parent_thread_id.is_some()
|| params.ancestor_thread_id.is_some()
|| params.attached_to_thread_id.is_some()
|| params
.model_providers
.as_ref()
.is_some_and(|values| !values.is_empty())
|| params
.excluded_thread_ids
.as_ref()
.is_some_and(|values| !values.is_empty())
{
bail!("These cloud conversation filters are not supported yet.");
}
Ok(cloud::ThreadListQuery {
cursor: params.cursor,
limit: params.limit,
originators: params.originators.unwrap_or_default(),
sort_key: match params.sort_key {
Some(protocol::ThreadSortKey::CreatedAt) | None => cloud::ThreadSortKey::CreatedAt,
Some(protocol::ThreadSortKey::UpdatedAt) => cloud::ThreadSortKey::UpdatedAt,
Some(protocol::ThreadSortKey::RecencyAt) => cloud::ThreadSortKey::RecencyAt,
Some(protocol::ThreadSortKey::SectionPosition) => {
bail!("Cloud section ordering is not supported yet.")
}
},
sort_direction: match params.sort_direction {
Some(protocol::SortDirection::Asc) => cloud::ThreadSortDirection::Asc,
Some(protocol::SortDirection::Desc) | None => cloud::ThreadSortDirection::Desc,
},
})
}
fn history_order(direction: protocol::SortDirection) -> cloud::HistoryOrder {
match direction {
protocol::SortDirection::Asc => cloud::HistoryOrder::Ascending,
protocol::SortDirection::Desc => cloud::HistoryOrder::Descending,
}
}
fn cloud_message(
mut params: protocol::TurnStartParams,
) -> Result<cloud::AddUserMessageRequest, PreflightRejection> {
let thread_id = std::mem::take(&mut params.thread_id);
let client_user_message_id = params
.client_user_message_id
.take()
.ok_or(PreflightRejection(
"A cloud message needs a stable submission ID.",
))?;
let input = std::mem::take(&mut params.input);
let turn_trigger = params.turn_trigger.take();
if params != protocol::TurnStartParams::default() {
return Err(PreflightRejection(
"Changing cloud settings or sending structured input is not supported yet.",
));
}
let mut content = Vec::with_capacity(input.len());
for item in input {
let item = match item {
protocol::UserInput::Text {
text,
text_elements,
} => {
// Keep the existing line separation for consecutive plain text parts.
if text_elements.is_empty()
&& let Some(cloud::UserMessageInput::Text {
text: previous,
text_elements: previous_elements,
}) = content.last_mut()
&& previous_elements.is_empty()
{
previous.push('\n');
previous.push_str(&text);
continue;
}
cloud::UserMessageInput::Text {
text,
text_elements: text_elements
.into_iter()
.map(|element| cloud::UserMessageTextElement {
placeholder: element.placeholder().map(str::to_owned),
start: element.byte_range.start,
end: element.byte_range.end,
})
.collect(),
}
}
protocol::UserInput::Image { image, detail } => cloud::UserMessageInput::Image {
image: match image {
protocol::ImageReference::Inline { url } => cloud::ImageReference::Url(url),
protocol::ImageReference::File { file_id } => {
cloud::ImageReference::FileId(file_id)
}
},
detail: detail.map(|detail| match detail {
ImageDetail::Auto => cloud::ImageDetail::Auto,
ImageDetail::Low => cloud::ImageDetail::Low,
ImageDetail::High => cloud::ImageDetail::High,
ImageDetail::Original => cloud::ImageDetail::Original,
}),
},
protocol::UserInput::LocalImage { .. } => {
return Err(PreflightRejection(
"Prepare local images before sending them to Cloud.",
));
}
protocol::UserInput::Audio { .. }
| protocol::UserInput::LocalAudio { .. }
| protocol::UserInput::Skill { .. }
| protocol::UserInput::Mention { .. } => {
return Err(PreflightRejection(
"Cloud conversations currently accept text and images.",
));
}
};
content.push(item);
}
Ok(cloud::AddUserMessageRequest {
thread_id,
client_user_message_id,
input: content,
turn_trigger,
mode: cloud::SubmissionMode::StartIfIdle,
shared_access: false,
})
}
fn admitted_message(outcome: cloud::AdmissionOutcome) -> Result<CloudUserMessageReceipt> {
Ok(match outcome {
cloud::AdmissionOutcome::Started(turn) => {
CloudUserMessageReceipt::Started(events::turn(turn)?)
}
cloud::AdmissionOutcome::Steered(turn) => {
CloudUserMessageReceipt::Steered(events::turn(turn)?)
}
cloud::AdmissionOutcome::Duplicate { turn_id } => {
CloudUserMessageReceipt::Duplicate { turn_id }
}
cloud::AdmissionOutcome::Queued { .. } => bail!(
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
),
})
}
fn admitted_turn(outcome: cloud::AdmissionOutcome) -> Result<protocol::Turn> {
match admitted_message(outcome)? {
CloudUserMessageReceipt::Started(turn) | CloudUserMessageReceipt::Steered(turn) => Ok(turn),
CloudUserMessageReceipt::Duplicate { .. } => bail!(
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
),
}
}
#[cfg(test)]
#[path = "request_tests.rs"]
mod tests;

View File

@@ -0,0 +1,206 @@
#![cfg(test)]
//! Exercises native admission and local validation through the command worker.
use super::*;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn submission(message_id: &str) -> protocol::TurnStartParams {
protocol::TurnStartParams {
thread_id: "t".into(),
client_user_message_id: Some(message_id.into()),
input: vec![protocol::UserInput::Text {
text: "hello".into(),
text_elements: Vec::new(),
}],
..Default::default()
}
}
#[tokio::test]
async fn native_submission_uses_one_admission_and_keeps_preflight_guards() -> Result<()> {
let server = MockServer::start().await;
let home = tempfile::tempdir()?;
let config = crate::legacy_core::config::ConfigBuilder::default()
.codex_home(home.path().to_owned())
.fallback_cwd(Some(home.path().to_owned()))
.without_project_context()
.build()
.await?;
let native = cloud::Client::new(
&config.http_client_factory(),
&server.uri(),
cloud::Credentials::new("synthetic-bearer", "synthetic-account")?,
)?;
let account = protocol::GetAccountResponse {
user_id: None,
account: None,
requires_openai_auth: true,
workspace_routing: None,
};
let (client, commands, output) = crate::CloudClient::channel(/*capacity*/ 4);
let client = crate::AppServerClient::Cloud(client);
let handle = client.request_handle();
let crate::AppServerRequestHandle::Cloud(cloud_handle) = &handle else {
panic!("expected a Cloud handle");
};
let (reply_sender, stream) = futures::channel::mpsc::unbounded();
let mut replies = Replies {
active: Some(Attachment {
thread_id: "t".into(),
stream: stream.boxed(),
}),
..Replies::default()
};
let worker = tokio::spawn(async move {
let mut requests = crate::cloud_backend::requests::Requests {
client: native,
account,
loaded: None,
warned_partial_history: None,
};
crate::cloud_backend::run_worker(commands, &mut requests, &mut replies, &output).await
});
let rpc = "/oaiproto.codex_app_server_backend.ThreadService/AddUserMessage";
Mock::given(method("POST"))
.and(path(rpc))
.and(header("authorization", "Bearer synthetic-bearer"))
.respond_with(ResponseTemplate::new(503))
.expect(2)
.mount(&server)
.await;
let url = "data:image/png;base64,iVBORw0KGgo=";
let image = protocol::UserInput::Image {
image: protocol::ImageReference::Inline { url: url.into() },
detail: None,
};
let Err(crate::TypedRequestError::Server { source, .. }) = cloud_handle
.submit_user_message(protocol::TurnStartParams {
input: vec![image.clone()],
..submission("x")
})
.await
else {
panic!("a lost receipt must remain uncertain");
};
assert_eq!(source.code, -32000);
assert!(source.message.contains("mutation outcome unknown"));
// Existing typed turn/start callers keep StartIfIdle and the same native error.
let Err(crate::TypedRequestError::Server { source, .. }) = handle
.request_typed::<protocol::TurnStartResponse>(protocol::ClientRequest::TurnStart {
request_id: protocol::RequestId::Integer(1),
params: protocol::TurnStartParams {
input: vec![
image,
protocol::UserInput::Text {
text: "describe the image".into(),
text_elements: Vec::new(),
},
],
..submission("m")
},
})
.await
else {
panic!("ordinary turn/start must retain its server error");
};
assert_eq!(source.code, -32000);
assert!(source.message.contains("mutation outcome unknown"));
for params in [
protocol::TurnStartParams {
model: Some("other".into()),
..submission("invalid")
},
protocol::TurnStartParams {
client_user_message_id: None,
..submission("missing")
},
protocol::TurnStartParams {
input: Vec::new(),
..submission("empty")
},
protocol::TurnStartParams {
thread_id: "other".into(),
..submission("foreign")
},
] {
let Err(crate::TypedRequestError::Server { source, .. }) =
cloud_handle.submit_user_message(params).await
else {
panic!("invalid input must fail before admission");
};
assert_eq!(source.code, -32602);
}
let queued = handle
.request(protocol::ClientRequest::TurnStart {
request_id: protocol::RequestId::Integer(3),
params: protocol::TurnStartParams {
input: vec![protocol::UserInput::LocalImage {
path: "queued.png".into(),
detail: None,
}],
..submission("queued-image")
},
})
.await?
.expect_err("a queued attachment must fail before admission");
assert_eq!(queued.code, -32602);
assert_eq!(
queued.message,
"Prepare local images before sending them to Cloud."
);
let invalid_image = handle
.request(protocol::ClientRequest::TurnStart {
request_id: protocol::RequestId::Integer(4),
params: protocol::TurnStartParams {
input: vec![protocol::UserInput::Image {
image: protocol::ImageReference::Inline { url: String::new() },
detail: None,
}],
..submission("invalid-image")
},
})
.await?
.expect_err("an invalid image must fail before admission");
assert_eq!(invalid_image.code, -32602);
drop(reply_sender);
let Err(crate::TypedRequestError::Server { source, .. }) =
cloud_handle.submit_user_message(submission("closed")).await
else {
panic!("a disconnected stream must reject input");
};
assert_eq!(source.code, -32602);
let ordinary = handle
.request(protocol::ClientRequest::TurnStart {
request_id: protocol::RequestId::Integer(2),
params: submission("closed"),
})
.await?
.expect_err("ordinary turn/start keeps its existing disconnected error");
assert_eq!(ordinary.code, -32000);
client.shutdown().await?;
worker.await?;
let calls = server.received_requests().await.unwrap();
assert!(calls.iter().all(|request| {
request
.body
.windows(url.len())
.any(|bytes| bytes == url.as_bytes())
}));
assert_eq!(
calls
.iter()
.map(|request| (request.body[7], *request.body.last().unwrap()))
.collect::<Vec<_>>(),
vec![(b'x', 1), (b'm', 3)]
);
Ok(())
}

View File

@@ -0,0 +1,104 @@
use super::*;
use crate::AppServerClient;
use crate::AppServerEvent;
use codex_app_server_protocol::ThreadReadParams;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn retained_request_and_reply_stay_with_their_cloud_backend() {
let (first, mut first_commands, first_events) = CloudClient::channel(/*capacity*/ 1);
let (second, mut second_commands, _second_events) = CloudClient::channel(/*capacity*/ 1);
let mut first = AppServerClient::Cloud(first);
let second = AppServerClient::Cloud(second);
let handle = first.request_handle();
let reply = handle.server_request_reply_handle(RequestId::Integer(7));
let worker = tokio::spawn(async move {
let command = first_commands.recv().await.unwrap();
let CloudOperation::Request(request) = command.operation else {
panic!("expected thread read");
};
let ClientRequest::ThreadRead { params, .. } = *request else {
panic!("expected thread read");
};
assert_eq!(params.thread_id, "thread-1");
first_events
.send(AppServerEvent::Disconnected {
message: "stream ended".into(),
})
.unwrap();
command
.response
.send(Ok(Ok(serde_json::json!({"owner": "first"}))))
.unwrap();
let command = first_commands.recv().await.unwrap();
let CloudOperation::Resolve { request_id, result } = command.operation else {
panic!("expected retained reply");
};
assert_eq!(
(request_id, result),
(
RequestId::Integer(7),
serde_json::json!({"decision": "accept"})
)
);
command
.response
.send(Ok(Ok(serde_json::Value::Null)))
.unwrap();
});
assert_eq!(
handle
.request(ClientRequest::ThreadRead {
request_id: RequestId::Integer(1),
params: ThreadReadParams {
thread_id: "thread-1".into(),
include_turns: false
},
})
.await
.unwrap()
.unwrap(),
serde_json::json!({"owner": "first"})
);
reply
.resolve(serde_json::json!({"decision": "accept"}))
.await
.unwrap();
assert!(second_commands.try_recv().is_err());
assert!(matches!(
first.next_event().await,
Some(AppServerEvent::Disconnected { .. })
));
worker.await.unwrap();
assert!(
handle
.request(ClientRequest::ThreadRead {
request_id: RequestId::Integer(2),
params: ThreadReadParams {
thread_id: "thread-1".into(),
include_turns: false
},
})
.await
.is_err()
);
drop(second);
}
#[tokio::test(start_paused = true)]
async fn cloud_shutdown_times_out_when_owner_does_not_respond() {
let (client, mut commands, events) = CloudClient::channel(/*capacity*/ 1);
let error = tokio::time::timeout(
crate::SHUTDOWN_TIMEOUT + std::time::Duration::from_secs(1),
AppServerClient::Cloud(client).shutdown(),
)
.await
.expect("shutdown should be bounded")
.expect_err("an unresponsive cloud worker should time out");
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
let command = commands.try_recv().expect("shutdown was admitted");
assert!(matches!(command.operation, CloudOperation::Shutdown));
assert!(command.response.is_closed());
assert!(events.is_closed());
assert!(commands.recv().await.is_none());
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
//! Paths resolved using the app-server host's platform rules.
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppServerPath(String);
impl AppServerPath {
pub fn from_app_server(path: impl Into<String>) -> Self {
Self(path.into())
}
pub fn from_absolute_str(raw: &str) -> Option<Self> {
(raw.starts_with('/') || is_windows_absolute_path(raw)).then(|| Self(raw.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn components(&self) -> Vec<&str> {
let separators = if is_windows_absolute_path(&self.0) {
&['/', '\\'][..]
} else {
&['/'][..]
};
self.0
.split(separators)
.filter(|part| !part.is_empty())
.collect()
}
pub fn join(&self, segment: impl AsRef<str>) -> Self {
let is_windows = is_windows_absolute_path(&self.0);
let (path, separator) = if is_windows {
(self.0.trim_end_matches(['/', '\\']), '\\')
} else {
(self.0.trim_end_matches('/'), '/')
};
Self(format!("{path}{separator}{}", segment.as_ref()))
}
}
impl fmt::Display for AppServerPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
fn is_windows_absolute_path(path: &str) -> bool {
let bytes = path.as_bytes();
(bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& matches!(bytes[2], b'\\' | b'/'))
|| path.starts_with("\\\\")
|| path.starts_with("//")
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,120 @@
//! Negotiated WebSocket compression. Codec history lasts for the connection.
use std::io;
use codex_app_server_transport::CompressionConnection;
use codex_app_server_transport::WEBSOCKET_COMPRESSION_HEADER;
use codex_app_server_transport::WebSocketCompression;
use codex_app_server_transport::ZstdDecoder;
use codex_app_server_transport::ZstdEncoder;
use codex_app_server_transport::zstd_codec_pair;
use futures::SinkExt;
use futures::StreamExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Bytes;
use tokio_tungstenite::tungstenite::Error;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::client::Response;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::frame::Frame;
use tokio_tungstenite::tungstenite::protocol::frame::coding::Data;
use tokio_tungstenite::tungstenite::protocol::frame::coding::OpCode;
// Match the listener's default incoming frame limit when no smaller cap is advertised.
const DEFAULT_MAX_FRAME_BYTES: usize = 16 << 20;
const MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER: &str =
"x-codex-websocket-max-unfragmented-message-bytes";
pub(crate) type WebSocketHandshake<S> = (WebSocketStream<S>, Response);
pub(crate) struct RemoteWebSocket<S> {
stream: WebSocketStream<S>,
codec: Option<(ZstdEncoder, ZstdDecoder)>,
max_frame_bytes: usize,
write_failed: bool,
}
impl<S: AsyncRead + AsyncWrite + Unpin> RemoteWebSocket<S> {
pub(crate) fn from_handshake(
(stream, response): WebSocketHandshake<S>,
max_message_size: usize,
) -> io::Result<Self> {
let headers = response.headers();
let header = headers
.get(WEBSOCKET_COMPRESSION_HEADER)
.map(HeaderValue::to_str)
.transpose()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let codec = match WebSocketCompression::from_response_header(header)? {
WebSocketCompression::Plain => None,
WebSocketCompression::Zstd => Some(zstd_codec_pair(
max_message_size,
CompressionConnection::NativeClient,
)?),
};
let max_frame_bytes = headers
.get(MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
.unwrap_or(DEFAULT_MAX_FRAME_BYTES)
.min(DEFAULT_MAX_FRAME_BYTES);
Ok(Self {
stream,
codec,
max_frame_bytes,
write_failed: false,
})
}
pub(crate) async fn next(&mut self) -> Option<Result<Message, Error>> {
if self.write_failed {
return Some(Err(Error::Io(io::ErrorKind::BrokenPipe.into())));
}
let message = self.stream.next().await?;
Some(match (&mut self.codec, message) {
(Some((_, decoder)), Ok(Message::Binary(bytes))) => decoder
.decode(&bytes)
.map(|text| Message::Text(text.into()))
.map_err(Error::Io),
(Some(_), Ok(Message::Text(_))) => Err(Error::Io(io::Error::new(
io::ErrorKind::InvalidData,
"expected compressed binary app-server message",
))),
(_, message) => message,
})
}
pub(crate) async fn send_text(&mut self, text: String) -> Result<(), Error> {
if self.write_failed {
return Err(Error::Io(io::ErrorKind::BrokenPipe.into()));
}
let result = async {
let Some((encoder, _)) = &mut self.codec else {
return self.stream.send(Message::Text(text.into())).await;
};
let mut bytes = Bytes::from(encoder.encode(&text).map_err(Error::Io)?);
if bytes.len() <= self.max_frame_bytes {
return self.stream.send(Message::Binary(bytes)).await;
}
let mut opcode = OpCode::Data(Data::Binary);
while !bytes.is_empty() {
let chunk = bytes.split_to(bytes.len().min(self.max_frame_bytes));
let frame = Frame::message(chunk, opcode, bytes.is_empty());
self.stream.feed(Message::Frame(frame)).await?;
opcode = OpCode::Data(Data::Continue);
}
self.stream.flush().await
}
.await;
// A failed write may leave the compression history ahead of the receiver.
self.write_failed = result.is_err();
result
}
pub(crate) async fn close(&mut self) -> Result<(), Error> {
self.stream.close(/*msg*/ None).await
}
}

View File

@@ -0,0 +1,68 @@
//! Retained reply capability: a server request ID and the worker that emitted it.
use crate::AppServerRequestHandle;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::Result as JsonRpcResult;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
/// A reply always targets its originating connection, regardless of later UI selection.
/// Clones share a single-use completion state, so only the first resolve or reject is
/// submitted. Dropping a handle sends nothing. It does not keep a shutdown worker alive
/// or reconnect it; a stale connection returns its normal I/O error. No retries occur.
#[derive(Clone)]
pub struct AppServerReplyHandle {
client: AppServerRequestHandle,
request_id: RequestId,
claimed: Arc<AtomicBool>,
}
impl fmt::Debug for AppServerReplyHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AppServerReplyHandle([redacted])")
}
}
impl AppServerRequestHandle {
/// Capture at event ingress, using an ID from this connection's event stream.
/// Request IDs may be reused by other connections and must not select a client.
pub fn server_request_reply_handle(&self, request_id: RequestId) -> AppServerReplyHandle {
AppServerReplyHandle {
client: self.clone(),
request_id,
claimed: Arc::new(AtomicBool::new(false)),
}
}
}
impl AppServerReplyHandle {
fn claim(&self) -> io::Result<()> {
self.claimed
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.map(|_| ())
.map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"app-server reply handle already used",
)
})
}
/// Resolve at the caller's explicit request. Failure can have an unknown outcome.
pub async fn resolve(&self, result: JsonRpcResult) -> io::Result<()> {
self.claim()?;
self.client
.resolve_server_request(self.request_id.clone(), result)
.await
}
/// Reject on the originating connection; never fall back to another connection.
pub async fn reject(&self, error: JSONRPCErrorError) -> io::Result<()> {
self.claim()?;
self.client
.reject_server_request(self.request_id.clone(), error)
.await
}
}
#[cfg(test)]
#[path = "server_request_tests.rs"]
mod tests;

View File

@@ -0,0 +1,105 @@
//! Worker-channel ownership checks, including stale handles and identical request IDs.
use super::*;
use crate::ClientCommand;
use crate::InProcessAppServerRequestHandle;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
#[tokio::test]
async fn in_process_replies_keep_their_worker_and_request_id() {
let (first_tx, mut first_rx) = mpsc::channel(/*buffer*/ 2);
let (second_tx, mut second_rx) = mpsc::channel(/*buffer*/ 2);
let first = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle {
command_tx: first_tx,
});
let second = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle {
command_tx: second_tx,
});
let id = RequestId::String("private-request".into());
let reply = first.server_request_reply_handle(id.clone());
let stale = first.server_request_reply_handle(RequestId::String("stale-request".into()));
let other = second.server_request_reply_handle(id.clone());
drop(first);
assert_eq!(format!("{reply:?}"), "AppServerReplyHandle([redacted])");
assert_eq!(reply.request_id, id);
let (result, ()) = tokio::join!(reply.resolve(serde_json::json!({"first": true})), async {
let ClientCommand::ResolveServerRequest {
request_id,
result,
response_tx,
} = first_rx.recv().await.unwrap()
else {
panic!("wrong command")
};
assert_eq!(
(request_id, result),
(id.clone(), serde_json::json!({"first": true}))
);
response_tx.send(Ok(())).unwrap();
});
result.unwrap();
assert!(second_rx.try_recv().is_err());
let error = JSONRPCErrorError {
code: -32000,
message: "declined".into(),
data: None,
};
let (result, ()) = tokio::join!(other.reject(error.clone()), async {
let ClientCommand::RejectServerRequest {
request_id,
error: received,
response_tx,
} = second_rx.recv().await.unwrap()
else {
panic!("wrong command")
};
assert_eq!((request_id, received), (id, error));
response_tx.send(Ok(())).unwrap();
});
result.unwrap();
assert!(first_rx.try_recv().is_err());
drop(first_rx);
assert_eq!(
stale
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
io::ErrorKind::BrokenPipe
);
drop(other);
assert!(second_rx.try_recv().is_err());
}
#[tokio::test]
async fn cloned_reply_handle_only_submits_once() {
let (command_tx, mut command_rx) = mpsc::channel(/*buffer*/ 2);
let client = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle { command_tx });
let reply = client.server_request_reply_handle(RequestId::Integer(1));
let duplicate = reply.clone();
let error = JSONRPCErrorError {
code: -32000,
message: "declined".into(),
data: None,
};
let (resolved, rejected, ()) = tokio::join!(
reply.resolve(serde_json::json!({"accepted": true})),
duplicate.reject(error),
async {
match command_rx.recv().await.unwrap() {
ClientCommand::ResolveServerRequest { response_tx, .. }
| ClientCommand::RejectServerRequest { response_tx, .. } => {
response_tx.send(Ok(())).unwrap();
}
_ => panic!("wrong command"),
}
}
);
let outcomes = [resolved, rejected].map(|result| result.map_err(|error| error.kind()));
assert!(
outcomes == [Ok(()), Err(io::ErrorKind::InvalidInput)]
|| outcomes == [Err(io::ErrorKind::InvalidInput), Ok(())]
);
assert!(command_rx.try_recv().is_err());
}

View File

@@ -0,0 +1,101 @@
//! Real WebSocket workers retain independent replies even when request IDs collide.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn remote_reply_handles_keep_original_connection() {
let mut clients = Vec::new();
let mut replies = Vec::new();
let mut stale_replies = Vec::new();
let mut observed = Vec::new();
for label in ["first", "second"] {
let (done_tx, done_rx) = oneshot::channel();
let websocket_url = start_test_remote_server(move |mut websocket| async move {
expect_remote_initialize(&mut websocket).await;
write_websocket_message(&mut websocket, JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1), method: "item/tool/requestUserInput".into(),
params: Some(serde_json::json!({"threadId":"same-thread", "turnId":"same-turn", "itemId":"same-item", "questions":[], "isBlocking":true})),
trace: None,
})).await;
let response = read_websocket_message(&mut websocket).await;
done_tx.send((label, response)).unwrap();
while websocket.next().await.is_some() {}
}).await;
let mut client = AppServerClient::Remote(
RemoteAppServerClient::connect(test_remote_connect_args(websocket_url))
.await
.unwrap(),
);
let AppServerEvent::ServerRequest(request) = client.next_event().await.unwrap() else {
panic!("expected request")
};
replies.push(
client
.request_handle()
.server_request_reply_handle(request.id().clone()),
);
stale_replies.push(
client
.request_handle()
.server_request_reply_handle(RequestId::Integer(2)),
);
clients.push(client);
observed.push(done_rx);
}
replies[1]
.reject(JSONRPCErrorError {
code: -32000,
message: "second".into(),
data: None,
})
.await
.unwrap();
replies[0]
.resolve(serde_json::json!({"first": true}))
.await
.unwrap();
for receiver in observed {
let (label, message) = timeout(Duration::from_secs(/*secs*/ 5), receiver)
.await
.unwrap()
.unwrap();
match message {
JSONRPCMessage::Response(response) => assert_eq!(
(label, response.id, response.result),
(
"first",
RequestId::Integer(1),
serde_json::json!({"first": true})
)
),
JSONRPCMessage::Error(error) => assert_eq!(
(label, error.id, error.error.message),
("second", RequestId::Integer(1), "second".into())
),
_ => panic!("expected response or rejection"),
}
}
for client in clients {
client.shutdown().await.unwrap();
}
for reply in replies {
assert_eq!(
reply
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
ErrorKind::InvalidInput
);
}
for reply in stale_replies {
assert_eq!(
reply
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
ErrorKind::BrokenPipe
);
}
}

View File

@@ -0,0 +1,116 @@
//! Exercise a negotiated compressed session through the remote client API.
use std::error::Error;
use codex_app_server_client::AppServerEvent;
use codex_app_server_client::RemoteAppServerClient;
use codex_app_server_client::RemoteAppServerConnectArgs;
use codex_app_server_client::RemoteAppServerEndpoint;
use codex_app_server_protocol::JSONRPCRequest;
use codex_app_server_protocol::RequestId;
use codex_app_server_transport::WEBSOCKET_COMPRESSION_HEADER;
use codex_app_server_transport::ZSTD_STREAM_PROTOCOL;
use codex_app_server_transport::ZstdDecoder;
use codex_app_server_transport::ZstdEncoder;
use codex_uds::UnixListener;
use codex_utils_absolute_path::AbsolutePathBuf;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio_tungstenite::accept_hdr_async_with_config;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
#[tokio::test]
async fn compressed_session_negotiates_fragments_and_retains_history() -> Result<(), Box<dyn Error>>
{
const FRAME_LIMIT: usize = 16;
let dir = TempDir::new()?;
let socket_path = AbsolutePathBuf::from_absolute_path(dir.path().join("codex.sock"))?;
let mut listener = UnixListener::bind(socket_path.as_path()).await?;
let server = async {
let stream = listener.accept().await?;
let mut websocket = accept_hdr_async_with_config(
stream,
|request: &Request, mut response: Response| {
assert_eq!(
request.headers()[WEBSOCKET_COMPRESSION_HEADER],
ZSTD_STREAM_PROTOCOL
);
response.headers_mut().insert(
WEBSOCKET_COMPRESSION_HEADER,
HeaderValue::from_static(ZSTD_STREAM_PROTOCOL),
);
response.headers_mut().insert(
"x-codex-websocket-max-unfragmented-message-bytes",
HeaderValue::from(FRAME_LIMIT),
);
Ok(response)
},
Some(WebSocketConfig::default().max_frame_size(Some(FRAME_LIMIT))),
)
.await?;
let mut decoder = ZstdDecoder::new(/*max_message_size*/ 1024)?;
let mut encoder = ZstdEncoder::new()?;
for expected_method in ["initialize", "initialized", "echo"] {
let Message::Binary(bytes) = websocket.next().await.ok_or("connection closed")?? else {
return Err("expected compressed message".into());
};
if expected_method == "initialize" {
assert!(
bytes.len() > FRAME_LIMIT,
"initialize must require fragmentation"
);
}
let request: Value = serde_json::from_str(&decoder.decode(&bytes)?)?;
assert_eq!(request["method"], expected_method);
if expected_method != "initialized" {
let response = json!({"id": request["id"], "result": {"ok": true}}).to_string();
websocket
.send(Message::Binary(encoder.encode(&response)?.into()))
.await?;
}
}
websocket.send(Message::Text("{}".into())).await?;
Ok::<(), Box<dyn Error>>(())
};
let client = async {
let mut client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
required_human_approval: false,
endpoint: RemoteAppServerEndpoint::UnixSocket { socket_path },
client_name: "compression-test".to_string(),
client_version: "0.0.0".to_string(),
experimental_api: false,
mcp_server_openai_form_elicitation: false,
opt_out_notification_methods: Vec::new(),
channel_capacity: 8,
})
.await?;
assert_eq!(
client
.request_handle()
.request_json_rpc(JSONRPCRequest {
id: RequestId::Integer(1),
method: "echo".to_string(),
params: None,
trace: None,
})
.await?,
Ok(json!({"ok": true}))
);
let Some(AppServerEvent::Disconnected { message }) = client.next_event().await else {
return Err("expected disconnect after uncompressed message".into());
};
assert!(message.contains("expected compressed binary"));
client.shutdown().await?;
Ok::<(), Box<dyn Error>>(())
};
tokio::try_join!(server, client)?;
Ok(())
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "app-server-daemon",
crate_name = "codex_app_server_daemon",
)

View File

@@ -0,0 +1,52 @@
[package]
name = "codex-app-server-daemon"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "codex_app_server_daemon"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-app-server-transport = { workspace = true }
codex-features = { workspace = true }
codex-http-client = { workspace = true }
codex-install-context = { workspace = true }
codex-utils-home-dir = { workspace = true }
codex-utils-process = { workspace = true }
codex-uds = { workspace = true }
futures = { workspace = true }
libc = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
semver = { workspace = true }
blake3 = { workspace = true }
tokio = { workspace = true, features = [
"fs",
"io-util",
"macros",
"process",
"rt-multi-thread",
"signal",
"time",
] }
tempfile = { workspace = true }
tokio-tungstenite = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true }
[dev-dependencies]
codex-utils-cargo-bin = { workspace = true }
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
tracing-subscriber = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_IO", "Win32_System_JobObjects", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] }

View File

@@ -0,0 +1,195 @@
# codex-app-server-daemon
> `codex-app-server-daemon` is experimental and its lifecycle contract may
> change while the remote-management flow is still being developed.
`codex-app-server-daemon` backs the machine-readable `codex app-server`
lifecycle commands used by remote clients such as the desktop and mobile apps.
It is intended for Codex instances launched over SSH, including fresh developer
machines that should expose app-server with `remote_control` enabled.
## Platform support
The daemon supports Linux, macOS, and Windows using platform-specific process
and file-locking primitives. Windows startup requires a non-elevated terminal
whose host permits detached child processes.
Windows automatic attachment requires the canonical socket address to fit the
108-byte AF_UNIX limit (including its terminator). A short junction alias whose
resolved address exceeds that limit falls back to the embedded server. Use a
shorter `CODEX_HOME` to share the daemon; discovery does not trust a mutable alias.
Shared clients use the environment inherited when the daemon started. Opening a
new terminal or clearing variables there does not clear the running daemon's
environment; per-client environment isolation is not provided.
An invocation that sets `CODEX_EXEC_SERVER_URL` skips implicit daemon attachment
so its executor selection is preserved. If an implicitly discovered daemon cannot
initialize the connection, the TUI starts an embedded server instead. Explicit
`--remote` endpoints remain authoritative and report connection failures.
## Commands
```sh
codex app-server daemon start
codex app-server daemon restart
codex app-server daemon update
codex app-server daemon enable-remote-control
codex app-server daemon disable-remote-control
codex app-server daemon stop
codex app-server daemon version
codex app-server daemon bootstrap --remote-control
```
On success, every command writes exactly one JSON object to stdout. Consumers
should parse that JSON rather than relying on human-readable text. Lifecycle
responses report the resolved backend, socket path, local CLI version, and
running app-server version when applicable.
Eligible managed daemons check for updates after five minutes, then hourly by
default. Edit `CODEX_HOME/app-server-daemon/settings.json` to change this:
```json
{
"remoteControlEnabled": false,
"shutdownGraceSeconds": 60,
"updater": { "autoUpdateEnabled": false, "updateIntervalMinutes": 120 }
}
```
Positive minute intervals have no configured cap. `daemon restart` applies the
enabled state; the next updater wait reads a new interval. The preference does
not affect an explicit `codex update` command or `daemon update`.
`daemon update` selects the latest stable release, even with automatic updates
disabled. It also returns pinned or local managed packages to production update
eligibility, preserving the automatic-update preference. Legacy installations
migrate to the dedicated root once the published installer and release support
migration. JSON reports `updated`, `noUpdate`, or `unsupported`, with installed
and running versions. A running daemon restarts, so active or queued work may be
interrupted; a stopped daemon stays stopped. Installer errors return nonzero.
The updater uses saved network settings; CLI `-c` overrides do not reach it.
For all managed app-server shutdowns, including explicit stop and restart and
updater-triggered restarts, `shutdownGraceSeconds` defaults to 60 and accepts
an integer from 0 through 300. Zero forces shutdown immediately after requesting
a graceful exit; the five-minute maximum bounds the wait even if a turn is still
running.
## Bootstrap flow
For a new Linux or macOS machine:
```sh
curl -fsSL https://chatgpt.com/codex/install.sh | sh
$HOME/.codex/packages/standalone/current/codex app-server daemon bootstrap --remote-control
```
On Windows, use a non-elevated PowerShell terminal whose host allows breakaway:
```powershell
irm https://chatgpt.com/codex/install.ps1 | iex
$codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }
& "$codexHome\packages\standalone\current\bin\codex.exe" app-server daemon bootstrap --remote-control
```
`bootstrap` can use any complete CLI package. If no daemon package is installed,
it copies the invoking package into `CODEX_HOME/packages/app-server-daemon` and
prints an installation message without asking for confirmation. Existing daemon
packages are reused, including legacy installations; a broken selection is not
silently replaced. A bare executable cannot supply a new installation.
It records the daemon settings under `CODEX_HOME/app-server-daemon/`, starts app-server as a
pidfile-backed detached process. It launches a detached updater loop when
automatic updates are enabled, the installer selected the stable `latest`
channel, and the managed binary supports the updater command.
## Installation and update cases
New daemons use `CODEX_HOME/packages/app-server-daemon/current/bin/codex`
(`codex.exe` on Windows). The package contains the executable and its helpers.
Daemon-only installer updates leave the user's CLI command and shell setup alone.
Previously launched legacy daemons retain `CODEX_HOME/packages/standalone/current`,
including its flat binary layout when present. Starts and scheduled updates keep
using that location. An explicit production update prepares and validates a
compatible dedicated package before stopping the legacy updater and daemon,
selecting the new package, and restarting only a previously running daemon.
The old CLI package files and selection remain unchanged.
| Situation | What starts | Does this daemon fetch new binaries? | Does a running app-server eventually move to a newer binary on its own? |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Latest-channel installer has run; `start` or `bootstrap` is used with automatic updates enabled | Managed binary and detached updater when supported | When supported, the platform's installer runs on the configured cadence. | When supported, the running server restarts with the new binary before the updater replaces itself. |
| Installer selected an explicit release; `bootstrap` is used | Managed binary only | No; the selected release stays pinned. | No; an explicit restart uses the selected binary. |
| Another tool updates the managed binary | A fresh start or explicit restart uses it; a running server is reused. | Yes, when a latest-channel updater is running, on the configured cadence. | An updater that was running through the change compares binary contents on its next successful installer pass and refreshes the server first. |
### Managed packages
For dedicated and retained legacy daemon installations:
- lifecycle commands use the selected daemon package, regardless of the invoking
CLI version; they do not implicitly replace an existing package
- `bootstrap` is supported
- managed `start`, `restart`, and `bootstrap` ensure a single detached pid-backed
updater loop only when automatic updates are enabled for a stable latest-channel
release whose managed binary supports the updater command
- the installer records the latest-channel selection alongside `current`;
selecting an explicit release clears it, even if that version is currently
latest. The updater checks the selection again while holding the install lock
so an in-flight update cannot override a new pin
- installs made before the installer recorded channel selections need one new
`latest` installation to opt into automatic updates; until then the daemon
continues to serve app-server without updating the selected release
- after a successful refresh, if app-server is running and the managed binary
contents changed, the updater restarts app-server with that binary first and
only then replaces its own process image
- the updater loop is not reboot-persistent; a managed start after reboot
starts it again
### Out-of-band updates
This daemon does not watch arbitrary executable files for replacement. If some
other tool updates the managed binary path:
- an updater that was already running notices a changed managed
binary on its next successful scheduled installer pass; if
app-server is running, it refreshes app-server first and then refreshes itself
once that replacement starts successfully
- if the updater was absent during a same-version binary replacement, a later
managed start recovers it but cannot infer the running server's previous
executable identity; use `codex app-server daemon restart` to refresh the server
## Lifecycle semantics
`start` is idempotent and returns after app-server is ready to answer the normal
JSON-RPC initialize handshake on the Unix control socket.
`restart` stops any managed daemon and starts it again.
`enable-remote-control` and `disable-remote-control` persist the launch setting
for future starts. If a managed app-server is already running, they restart it
so the new setting takes effect immediately.
Top-level `codex remote-control start` enables and persists remote control for
the managed daemon, overriding a saved disabled value. It starts or bootstraps
the daemon as needed. Plain `codex remote-control` uses the managed daemon when
eligible; `codex remote-control --no-daemon` runs a separate foreground server.
`codex remote-control stop` stops the managed daemon without clearing its saved
remote-control preference.
`daemon start` and `daemon restart` use that saved preference. `daemon bootstrap`
sets it according to `--remote-control` (disabled when omitted).
`stop` sends a graceful termination request first, then force-terminates the
process after the configured grace window if it is still alive.
All mutating lifecycle commands are serialized per `CODEX_HOME`, so a concurrent
`start`, `restart`, `enable-remote-control`, `disable-remote-control`, `stop`,
or `bootstrap` does not race another in-flight lifecycle operation.
## State
The daemon stores its local state under `CODEX_HOME/app-server-daemon/`:
- `settings.json` for remote-control launch settings and updater preferences
- `app-server.pid` for the app-server process record
- `app-server-updater.pid` for the pid-backed standalone updater loop
- `daemon.lock` for daemon-wide lifecycle serialization

View File

@@ -0,0 +1,58 @@
mod pid;
pub(crate) mod stderr_log;
#[cfg(windows)]
pub(crate) mod windows;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use serde::Serialize;
pub(crate) use pid::PidBackend;
pub(crate) use pid::wait_for_process_exit;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BackendKind {
Pid,
}
#[derive(Debug, Clone)]
pub(crate) struct BackendPaths {
pub(crate) codex_bin: PathBuf,
pub(crate) pid_file: PathBuf,
pub(crate) update_pid_file: PathBuf,
pub(crate) remote_control_enabled: bool,
pub(crate) feature_overrides: BTreeMap<String, bool>,
}
pub(crate) fn pid_backend(paths: BackendPaths) -> PidBackend {
let mut backend = PidBackend::new(
paths.codex_bin,
paths.pid_file,
paths.remote_control_enabled,
);
backend.feature_overrides = paths.feature_overrides;
backend
}
pub(crate) fn pid_update_loop_backend(paths: BackendPaths) -> PidBackend {
PidBackend::new_update_loop(
paths.codex_bin,
paths.update_pid_file,
/*restore_release*/ None,
)
}
pub(crate) async fn append_stderr_log_tail_context(pid_file: &Path, context: &mut String) {
match pid::read_stderr_log_tail(pid_file).await {
Ok(Some(tail)) => tail.append_to_context(context),
Ok(None) => {}
Err(err) => {
context.push_str(&format!(
"\n\nFailed to read managed app-server stderr log: {err:#}"
));
}
}
}

View File

@@ -0,0 +1,880 @@
//! PID reservations serialize detached launches; process identities protect stale-record cleanup.
//! PID probes explicitly unlock so concurrent forks cannot retain their transient reservations.
#[path = "pid_identity.rs"]
mod identity;
#[cfg(any(unix, windows))]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use crate::managed_install::ExecutableIdentity;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
#[cfg(any(unix, windows))]
use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
use serde::Deserialize;
use serde::Serialize;
use tokio::fs;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncSeekExt;
#[cfg(unix)]
use tokio::process::Command;
use tokio::time::sleep;
use crate::settings::DEFAULT_SHUTDOWN_GRACE_SECONDS;
const STOP_POLL_INTERVAL: Duration = Duration::from_millis(50);
const STOP_FORCE_TIMEOUT: Duration = Duration::from_secs(10);
const START_TIMEOUT: Duration = Duration::from_secs(10);
const STDERR_LOG_TAIL_BYTES: u64 = 4096;
#[derive(Debug)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
pub(crate) struct PidBackend {
pub(super) feature_overrides: BTreeMap<String, bool>,
codex_bin: PathBuf,
pid_file: PathBuf,
lock_file: PathBuf,
command_kind: PidCommandKind,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PidRecord {
pid: u32,
// Keep the legacy timestamp for older CLI/updater versions reading this record.
process_start_time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(alias = "linuxProcessIdentity")]
process_identity: Option<identity::ProcessIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
executable_identity: Option<ExecutableIdentity>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PidLogTail {
pub(crate) path: PathBuf,
pub(crate) contents: String,
}
impl PidLogTail {
pub(crate) fn append_to_context(&self, context: &mut String) {
context.push_str(&format!(
"\n\nManaged app-server stderr ({}):",
self.path.display()
));
for line in self.contents.lines() {
context.push_str("\n ");
context.push_str(line);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum PidFileState {
Missing,
Starting,
Running(PidRecord),
}
#[derive(Debug, Clone)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
enum PidCommandKind {
AppServer { remote_control_enabled: bool },
UpdateLoop { restore_release: Option<String> },
}
impl PidBackend {
pub(crate) async fn running_executable_identity(&self) -> Result<Option<ExecutableIdentity>> {
match self.read_pid_file_state().await? {
PidFileState::Running(record) if self.record_is_active(&record).await? => {
// Updaters can exec a different release without changing PID. Only the
// updater itself can reliably identify its executable after a handoff.
if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. })
&& record.pid == std::process::id()
{
return crate::managed_install::executable_identity(&std::env::current_exe()?)
.await
.map(Some);
}
Ok(record.executable_identity)
}
_ => Ok(None),
}
}
pub(crate) fn new(codex_bin: PathBuf, pid_file: PathBuf, remote_control_enabled: bool) -> Self {
let lock_file = pid_file.with_extension("pid.lock");
Self {
feature_overrides: BTreeMap::new(),
codex_bin,
pid_file,
lock_file,
command_kind: PidCommandKind::AppServer {
remote_control_enabled,
},
}
}
pub(crate) fn new_update_loop(
codex_bin: PathBuf,
pid_file: PathBuf,
restore_release: Option<String>,
) -> Self {
let lock_file = pid_file.with_extension("pid.lock");
Self {
feature_overrides: BTreeMap::new(),
codex_bin,
pid_file,
lock_file,
command_kind: PidCommandKind::UpdateLoop { restore_release },
}
}
pub(crate) async fn is_starting_or_running(&self) -> Result<bool> {
loop {
match self.read_pid_file_state().await? {
PidFileState::Missing => return Ok(false),
PidFileState::Starting => return Ok(true),
PidFileState::Running(record) => {
if self.record_is_active(&record).await? {
return Ok(true);
}
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(false),
PidFileState::Starting | PidFileState::Running(_) => continue,
}
}
}
}
}
#[cfg(any(unix, windows))]
pub(crate) async fn start(&self) -> Result<Option<u32>> {
self.start_inner(/*replacement*/ None).await
}
#[cfg(not(any(unix, windows)))]
pub(crate) async fn start(&self) -> Result<Option<u32>> {
bail!("pid-managed app-server startup is unsupported on this platform")
}
pub(crate) async fn stop(&self) -> Result<()> {
self.stop_with_grace(DEFAULT_SHUTDOWN_GRACE_SECONDS).await
}
pub(crate) async fn stop_with_grace(&self, grace_seconds: u32) -> Result<()> {
loop {
let Some(record) = self.wait_for_pid_start().await? else {
return Ok(());
};
if !self.record_is_active(&record).await? {
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(()),
PidFileState::Starting | PidFileState::Running(_) => continue,
}
}
let pid = record.pid;
crate::diagnostics::event("shutdown_requested", serde_json::json!({ "pid": pid }));
let started_at = tokio::time::Instant::now();
let force_after = Duration::from_secs(grace_seconds.into());
let deadline = started_at + force_after + STOP_FORCE_TIMEOUT;
#[cfg(unix)]
self.terminate_process(pid)?;
#[cfg(windows)]
let process = {
let Some(process) = super::windows::Process::open(pid)? else {
continue;
};
if process.start_time()? != record.process_start_time {
continue;
}
match self.command_kind {
PidCommandKind::AppServer { .. } => {
let codex_home = self
.pid_file
.parent()
.and_then(Path::parent)
.context("daemon pid path has no Codex home")?;
let socket_path =
codex_app_server_transport::app_server_control_socket_path(codex_home)?;
if let Err(err) =
crate::client::request_shutdown(socket_path.as_path(), pid).await
{
tracing::warn!(%pid, %err, "managed app-server shutdown request failed; waiting for force deadline");
}
}
PidCommandKind::UpdateLoop { .. } => {
fs::write(self.pid_file.with_extension("shutdown"), pid.to_string())
.await
.context("failed to request updater shutdown")?;
}
}
process
};
let mut forced = false;
loop {
#[cfg(unix)]
if let Ok(raw_pid) = libc::pid_t::try_from(pid)
&& raw_pid > 0
{
// A previous updater may have started this child; reap it if it has exited.
unsafe { libc::waitpid(raw_pid, std::ptr::null_mut(), libc::WNOHANG) };
}
if !self.record_is_active(&record).await? {
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(()),
PidFileState::Starting | PidFileState::Running(_) => break,
}
}
if tokio::time::Instant::now() >= deadline {
break;
}
if !forced && started_at.elapsed() >= force_after {
crate::diagnostics::event("shutdown_forced", serde_json::json!({ "pid": pid }));
#[cfg(unix)]
self.force_terminate_process(pid)?;
#[cfg(windows)]
process.terminate()?;
forced = true;
}
sleep(STOP_POLL_INTERVAL).await;
}
if self.record_is_active(&record).await? {
bail!("timed out waiting for pid-managed app server {pid} to stop");
}
}
}
async fn wait_for_pid_start(&self) -> Result<Option<PidRecord>> {
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
loop {
match self.read_pid_file_state().await? {
PidFileState::Missing => return Ok(None),
PidFileState::Running(record) => return Ok(Some(record)),
PidFileState::Starting if tokio::time::Instant::now() < deadline => {
sleep(STOP_POLL_INTERVAL).await;
}
PidFileState::Starting => {
bail!(
"timed out waiting for pid reservation in {} to finish initializing",
self.pid_file.display()
);
}
}
}
}
async fn read_pid_file_state(&self) -> Result<PidFileState> {
let contents = match fs::read_to_string(&self.pid_file).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return if reservation_lock_is_active(&self.lock_file).await? {
Ok(PidFileState::Starting)
} else {
Ok(PidFileState::Missing)
};
}
Err(err) => {
return Err(err).with_context(|| {
format!("failed to read pid file {}", self.pid_file.display())
});
}
};
if contents.trim().is_empty() {
match inspect_empty_pid_reservation(&self.pid_file, &self.lock_file).await? {
EmptyPidReservation::Active => {
return Ok(PidFileState::Starting);
}
EmptyPidReservation::Stale => {
return Ok(PidFileState::Missing);
}
EmptyPidReservation::Record(record) => return Ok(PidFileState::Running(record)),
}
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", self.pid_file.display()))?;
Ok(PidFileState::Running(record))
}
async fn read_pid_file_state_with_lock_held(&self) -> Result<PidFileState> {
let contents = match fs::read_to_string(&self.pid_file).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(PidFileState::Missing);
}
Err(err) => {
return Err(err).with_context(|| {
format!("failed to read pid file {}", self.pid_file.display())
});
}
};
if contents.trim().is_empty() {
let _ = fs::remove_file(&self.pid_file).await;
return Ok(PidFileState::Missing);
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", self.pid_file.display()))?;
Ok(PidFileState::Running(record))
}
async fn refresh_after_stale_record(&self, expected: &PidRecord) -> Result<PidFileState> {
let reservation_lock = self.acquire_reservation_lock().await?;
let state = match self.read_pid_file_state_with_lock_held().await? {
PidFileState::Running(record) if record == *expected => {
let _ = fs::remove_file(&self.pid_file).await;
PidFileState::Missing
}
state => state,
};
drop(reservation_lock);
Ok(state)
}
async fn acquire_reservation_lock(&self) -> Result<fs::File> {
let reservation_lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&self.lock_file)
.await
.with_context(|| {
format!("failed to open pid lock file {}", self.lock_file.display())
})?;
let lock_deadline = tokio::time::Instant::now() + START_TIMEOUT;
while !try_lock_file(&reservation_lock)? {
if tokio::time::Instant::now() >= lock_deadline {
bail!(
"timed out waiting for pid lock {}",
self.lock_file.display()
);
}
sleep(STOP_POLL_INTERVAL).await;
}
Ok(reservation_lock)
}
#[cfg(any(unix, windows))]
async fn open_stderr_log(&self) -> Result<fs::File> {
let stderr_log_file = stderr_log_file_for_pid_file(&self.pid_file);
super::stderr_log::preserve(&stderr_log_file).await;
let result = async {
fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&stderr_log_file)
.await?;
// The updater predecessor can still write after a Windows handoff
// truncates this file. Append handles prevent stale offsets and gaps.
fs::OpenOptions::new()
.append(true)
.open(&stderr_log_file)
.await
}
.await;
result.with_context(|| {
format!(
"failed to open stderr log for pid-managed app server {}",
stderr_log_file.display()
)
})
}
#[cfg(any(unix, windows))]
fn command_args(&self) -> Vec<Cow<'_, str>> {
let mut args = match &self.command_kind {
PidCommandKind::AppServer {
remote_control_enabled: true,
} => vec![
"app-server".into(),
"--remote-control".into(),
"--listen".into(),
"unix://".into(),
],
PidCommandKind::AppServer {
remote_control_enabled: false,
} => vec!["app-server".into(), "--listen".into(), "unix://".into()],
PidCommandKind::UpdateLoop { restore_release } => {
let mut args = vec![
"app-server".into(),
"daemon".into(),
"pid-update-loop".into(),
];
if let Some(release) = restore_release {
args.extend(["--restore-release".into(), release.as_str().into()]);
}
args
}
};
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()]);
}
}
args
}
#[cfg(any(unix, windows))]
fn command_env(&self) -> Option<(&'static str, &'static str)> {
match self.command_kind {
PidCommandKind::AppServer {
remote_control_enabled: false,
} => Some((REMOTE_CONTROL_DISABLED_ENV_VAR, "1")),
PidCommandKind::AppServer {
remote_control_enabled: true,
}
| PidCommandKind::UpdateLoop { .. } => None,
}
}
fn terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind {
PidCommandKind::AppServer { .. } => terminate_process(pid),
#[cfg(unix)]
PidCommandKind::UpdateLoop { .. } => terminate_process_group(pid),
#[cfg(not(unix))]
PidCommandKind::UpdateLoop { .. } => terminate_process(pid),
}
}
#[cfg(not(windows))]
fn force_terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind {
PidCommandKind::AppServer { .. } => force_terminate_process(pid),
PidCommandKind::UpdateLoop { .. } => force_terminate_process_group(pid),
}
}
async fn record_is_active(&self, record: &PidRecord) -> Result<bool> {
process_matches_record(record).await
}
}
/// Wait for a published process to exit without modifying its PID reservation.
pub(crate) async fn wait_for_process_exit(pid_file: &Path) {
loop {
// A missing or empty record can belong to a launch still publishing its PID.
if let Ok(contents) = fs::read(pid_file).await
&& let Ok(record) = serde_json::from_slice::<PidRecord>(&contents)
&& matches!(process_matches_record(&record).await, Ok(false))
{
return;
}
sleep(crate::START_POLL_INTERVAL).await;
}
}
pub(crate) async fn read_stderr_log_tail(pid_file: &Path) -> Result<Option<PidLogTail>> {
let path = stderr_log_file_for_pid_file(pid_file);
let Some(contents) = read_log_tail(&path, STDERR_LOG_TAIL_BYTES).await? else {
return Ok(None);
};
Ok(Some(PidLogTail { path, contents }))
}
fn stderr_log_file_for_pid_file(pid_file: &Path) -> PathBuf {
pid_file.with_extension("stderr.log")
}
async fn read_log_tail(path: &Path, byte_limit: u64) -> Result<Option<String>> {
let mut file = match fs::File::open(path).await {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => {
return Err(err)
.with_context(|| format!("failed to open stderr log {}", path.display()));
}
};
let len = file
.metadata()
.await
.with_context(|| format!("failed to inspect stderr log {}", path.display()))?
.len();
if len == 0 {
return Ok(None);
}
let start = len.saturating_sub(byte_limit);
file.seek(SeekFrom::Start(start))
.await
.with_context(|| format!("failed to seek stderr log {}", path.display()))?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)
.await
.with_context(|| format!("failed to read stderr log {}", path.display()))?;
if start > 0
&& let Some(newline_index) = bytes.iter().position(|byte| *byte == b'\n')
{
bytes.drain(..=newline_index);
}
let contents = String::from_utf8_lossy(&bytes).trim_end().to_string();
if contents.is_empty() {
return Ok(None);
}
Ok(Some(contents))
}
#[cfg(unix)]
fn process_exists(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
let result = unsafe { libc::kill(pid, 0) };
result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(unix)]
fn terminate_process(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed app server pid {pid} is out of range"))?;
let result = unsafe { libc::kill(raw_pid, libc::SIGTERM) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to terminate pid-managed app server {pid}"))
}
#[cfg(unix)]
fn force_terminate_process(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed app server pid {pid} is out of range"))?;
let result = unsafe { libc::kill(raw_pid, libc::SIGKILL) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to force terminate pid-managed app server {pid}"))
}
#[cfg(unix)]
fn terminate_process_group(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed updater pid {pid} is out of range"))?;
let result = unsafe { libc::kill(-raw_pid, libc::SIGTERM) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to terminate pid-managed updater group {pid}"))
}
#[cfg(unix)]
fn force_terminate_process_group(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed updater pid {pid} is out of range"))?;
let result = unsafe { libc::kill(-raw_pid, libc::SIGKILL) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to force terminate pid-managed updater group {pid}"))
}
#[cfg(not(any(unix, windows)))]
fn terminate_process(_pid: u32) -> Result<()> {
bail!("pid-managed app-server shutdown is unsupported on this platform")
}
#[cfg(not(any(unix, windows)))]
fn force_terminate_process(_pid: u32) -> Result<()> {
bail!("pid-managed app-server shutdown is unsupported on this platform")
}
#[cfg(not(any(unix, windows)))]
fn force_terminate_process_group(_pid: u32) -> Result<()> {
bail!("pid-managed updater shutdown is unsupported on this platform")
}
#[cfg(unix)]
async fn process_matches_record(record: &PidRecord) -> Result<bool> {
if !process_exists(record.pid) {
return Ok(false);
}
let details = async {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Some(expected) = &record.process_identity {
return expected.matches_process(record.pid).await;
}
let (state, start_time) = read_process_details(record.pid).await?;
let matches = start_time == record.process_start_time;
let is_zombie = state.starts_with('Z');
if !matches && !is_zombie {
bail!(
"cannot verify pid-managed process {}: legacy start time changed; PID record retained. \
Retry with the locale and timezone used to start the daemon. If the system clock \
changed, stop the original process before restarting the daemon",
record.pid
);
}
Ok((is_zombie, matches))
}
.await;
match details {
Ok((is_zombie, matches)) => {
// An unreaped zombie still passes kill(pid, 0) and retains its start
// time, but it can no longer run the app-server or updater.
if is_zombie {
if matches && let Ok(raw_pid) = libc::pid_t::try_from(record.pid) {
// Re-exec can lose the Child handle without changing parenthood.
unsafe { libc::waitpid(raw_pid, std::ptr::null_mut(), libc::WNOHANG) };
}
return Ok(false);
}
Ok(matches)
}
Err(_err) if !process_exists(record.pid) => Ok(false),
Err(err) => Err(err),
}
}
#[cfg(not(any(unix, windows)))]
async fn process_matches_record(_record: &PidRecord) -> Result<bool> {
Ok(false)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
enum EmptyPidReservation {
Active,
Stale,
Record(PidRecord),
}
#[cfg(unix)]
fn try_lock_file(file: &fs::File) -> Result<bool> {
use std::os::fd::AsRawFd;
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if result == 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EWOULDBLOCK) {
return Ok(false);
}
Err(err).context("failed to lock pid reservation")
}
#[cfg(not(any(unix, windows)))]
fn try_lock_file(_file: &fs::File) -> Result<bool> {
bail!("pid-managed app-server startup is unsupported on this platform")
}
#[cfg(any(unix, windows))]
async fn reservation_lock_is_active(path: &Path) -> Result<bool> {
let file = match fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(path)
.await
{
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(false);
}
Err(err) => {
return Err(err)
.with_context(|| format!("failed to inspect pid lock file {}", path.display()));
}
};
probe_reservation_lock(file)
}
#[cfg(any(unix, windows))]
fn probe_reservation_lock(file: fs::File) -> Result<bool> {
if !try_lock_file(&file)? {
return Ok(true);
}
#[cfg(unix)]
{
use std::os::fd::AsRawFd;
// A concurrent fork can inherit this descriptor before it closes. Release the
// probe's lock explicitly so the child cannot look like a live reservation.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) } != 0 {
return Err(std::io::Error::last_os_error())
.context("failed to unlock pid reservation probe");
}
}
Ok(false)
}
#[cfg(not(any(unix, windows)))]
async fn reservation_lock_is_active(_path: &Path) -> Result<bool> {
Ok(false)
}
#[cfg(any(unix, windows))]
async fn inspect_empty_pid_reservation(
pid_path: &Path,
lock_path: &Path,
) -> Result<EmptyPidReservation> {
let file = match fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(lock_path)
.await
{
Ok(file) => file,
Err(err) => {
return Err(err).with_context(|| {
format!("failed to inspect pid lock file {}", lock_path.display())
});
}
};
inspect_empty_pid_reservation_with_file(pid_path, file).await
}
#[cfg(unix)]
struct EmptyPidProbeLock(fs::File);
#[cfg(unix)]
impl Drop for EmptyPidProbeLock {
fn drop(&mut self) {
use std::os::fd::AsRawFd;
// Closing alone leaves the lock held by any concurrent fork. Release it
// on every exit, including errors and cancellation while inspecting the PID.
if unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) } != 0 {
let error = std::io::Error::last_os_error();
tracing::warn!(%error, "failed to unlock empty pid reservation probe");
}
}
}
#[cfg(any(unix, windows))]
async fn inspect_empty_pid_reservation_with_file(
pid_path: &Path,
file: fs::File,
) -> Result<EmptyPidReservation> {
if !try_lock_file(&file)? {
return Ok(EmptyPidReservation::Active);
}
#[cfg(unix)]
let _probe_lock = EmptyPidProbeLock(file);
let contents = match fs::read_to_string(pid_path).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(EmptyPidReservation::Stale);
}
Err(err) => {
return Err(err)
.with_context(|| format!("failed to reread pid file {}", pid_path.display()));
}
};
if contents.trim().is_empty() {
let _ = fs::remove_file(pid_path).await;
return Ok(EmptyPidReservation::Stale);
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", pid_path.display()))?;
Ok(EmptyPidReservation::Record(record))
}
#[cfg(not(any(unix, windows)))]
async fn inspect_empty_pid_reservation(
_pid_path: &Path,
_lock_path: &Path,
) -> Result<EmptyPidReservation> {
Ok(EmptyPidReservation::Stale)
}
#[cfg(unix)]
async fn read_process_start_time(pid: u32) -> Result<String> {
Ok(read_process_details(pid).await?.1)
}
#[cfg(unix)]
async fn read_process_details(pid: u32) -> Result<(String, String)> {
let output = Command::new("ps")
.args(["-p", &pid.to_string(), "-o", "stat=", "-o", "lstart="])
.kill_on_drop(true)
.output()
.await
.context("failed to invoke ps for pid-managed app server")?;
if !output.status.success() {
bail!("failed to read start time for pid-managed app server {pid}");
}
let details = String::from_utf8(output.stdout)
.context("pid-managed app server process details were not utf-8")?;
let Some((state, start_time)) = details.trim().split_once(char::is_whitespace) else {
bail!("pid-managed app server {pid} has no recorded start time");
};
let start_time = start_time.trim();
if start_time.is_empty() {
bail!("pid-managed app server {pid} has no recorded start time");
}
Ok((state.to_string(), start_time.to_string()))
}
#[cfg(all(test, any(unix, windows)))]
#[path = "pid_tests.rs"]
mod tests;
#[cfg(windows)]
use super::windows::try_lock_file;
#[cfg(windows)]
async fn read_process_start_time(pid: u32) -> Result<String> {
super::windows::Process::open(pid)?
.context("daemon process exited during startup")?
.start_time()
}
#[cfg(windows)]
async fn process_matches_record(record: &PidRecord) -> Result<bool> {
let Some(process) = super::windows::Process::open(record.pid)? else {
return Ok(false);
};
Ok(process.is_running()? && process.start_time()? == record.process_start_time)
}
#[cfg(windows)]
fn force_terminate_process(pid: u32) -> Result<()> {
if let Some(process) = super::windows::Process::open(pid)? {
process.terminate()?;
}
Ok(())
}
#[cfg(windows)]
use force_terminate_process as terminate_process;
#[cfg(windows)]
#[path = "pid_windows.rs"]
mod windows;
#[cfg(any(unix, windows))]
#[path = "pid_start.rs"]
mod start;

View File

@@ -0,0 +1,242 @@
//! Native process identities and zombie state, independent of locale and timezone.
//! Boot IDs prevent records surviving reboot from matching reused process identifiers.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
use anyhow::Context;
#[cfg(any(target_os = "linux", target_os = "macos", test))]
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged, rename_all_fields = "camelCase")]
pub(super) enum ProcessIdentity {
Linux {
boot_id: String,
start_ticks: u64,
},
// Untagged decoding must try this before the timestamp-only MacOs variant.
MacOsUnique {
boot_id: String,
unique_id: u64,
start_seconds: u64,
start_microseconds: u64,
},
MacOs {
start_seconds: u64,
start_microseconds: u64,
},
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl ProcessIdentity {
pub(super) async fn matches_process(&self, pid: u32) -> Result<(bool, bool)> {
// A different boot proves staleness even when the reused PID is inaccessible.
if let Self::Linux { boot_id, .. } | Self::MacOsUnique { boot_id, .. } = self
&& *boot_id != read_boot_id().await?
{
return Ok((false, false));
}
#[cfg(target_os = "macos")]
if let Self::MacOsUnique { unique_id, .. } = self
&& *unique_id != read_unique_id(pid)?
{
return Ok((false, false));
}
let (is_zombie, actual) = read_process_details(pid).await?;
let matches = if let (
// Timestamp-only native records predate the cross-user identity check.
Self::MacOs {
start_seconds,
start_microseconds,
},
Self::MacOsUnique {
start_seconds: actual_seconds,
start_microseconds: actual_microseconds,
..
},
) = (self, &actual)
{
start_seconds == actual_seconds && start_microseconds == actual_microseconds
} else {
*self == actual
};
Ok((is_zombie, matches))
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl super::PidBackend {
pub(crate) async fn promote_legacy_identity(&self) -> Result<()> {
let _reservation = self.acquire_reservation_lock().await?;
let super::PidFileState::Running(mut record) =
self.read_pid_file_state_with_lock_held().await?
else {
return Ok(());
};
if matches!(
record.process_identity,
Some(ProcessIdentity::Linux { .. } | ProcessIdentity::MacOsUnique { .. })
) {
return Ok(());
}
// An updater keeps its PID across exec during upgrades. Only promote a
// legacy record while its original check still identifies the process,
// with the native identity unchanged on both sides of that check.
let before = read_process_details(record.pid).await?;
if before.0 || !super::process_matches_record(&record).await? {
return Ok(());
}
if read_process_details(record.pid).await? != before {
return Ok(());
}
record.process_identity = Some(before.1);
let temporary = self.pid_file.with_extension("pid.tmp");
tokio::fs::write(&temporary, serde_json::to_vec(&record)?).await?;
tokio::fs::rename(&temporary, &self.pid_file).await?;
Ok(())
}
}
#[cfg(target_os = "macos")]
pub(super) async fn read_process_details(pid: u32) -> Result<(bool, ProcessIdentity)> {
let boot_id = read_boot_id().await?;
let unique_id = read_unique_id(pid)?;
let pid = libc::pid_t::try_from(pid).context("daemon pid is out of range")?;
let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::uninit();
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
// SAFETY: the buffer has the exact size and alignment required by this flavor.
// arg=1 includes zombies so callers can reap children that have exited.
let read = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
/*arg*/ 1,
info.as_mut_ptr().cast(),
size,
)
};
if read <= 0 {
return Err(std::io::Error::last_os_error())
.context("failed to read daemon process identity");
}
anyhow::ensure!(read == size, "incomplete daemon process identity");
// SAFETY: proc_pidinfo initialized the entire structure on success.
let info = unsafe { info.assume_init() };
anyhow::ensure!(
unique_id == read_unique_id(info.pbi_pid)?,
"daemon process changed while reading its identity"
);
Ok((
info.pbi_status == libc::SZOMB,
ProcessIdentity::MacOsUnique {
boot_id,
unique_id,
start_seconds: info.pbi_start_tvsec,
start_microseconds: info.pbi_start_tvusec,
},
))
}
#[cfg(target_os = "macos")]
fn read_unique_id(pid: u32) -> Result<u64> {
// XNU's proc_uniqidentifierinfo ABI (flavor 17), unchanged in size since 2013.
// Unlike PROC_PIDTBSDINFO, this query does not require matching process ownership.
#[repr(C)]
struct UniqueInfo {
executable_uuid: [u8; 16],
unique_id: u64,
parent_unique_id: u64,
reserved: [u64; 3],
}
let pid = libc::pid_t::try_from(pid).context("daemon pid is out of range")?;
let mut info = std::mem::MaybeUninit::<UniqueInfo>::uninit();
let size = std::mem::size_of::<UniqueInfo>() as libc::c_int;
// SAFETY: the buffer matches proc_uniqidentifierinfo's size and alignment.
let read = unsafe {
libc::proc_pidinfo(
pid,
/*flavor*/ 17,
/*arg*/ 1,
info.as_mut_ptr().cast(),
size,
)
};
if read <= 0 {
return Err(std::io::Error::last_os_error()).context("failed to read daemon unique ID");
}
anyhow::ensure!(read == size, "incomplete daemon unique ID");
// SAFETY: proc_pidinfo initialized the entire structure on success.
Ok(unsafe { info.assume_init() }.unique_id)
}
#[cfg(target_os = "macos")]
async fn read_boot_id() -> Result<String> {
let mut buffer = [0u8; 37];
let mut size = buffer.len();
// SAFETY: the writable buffer has size bytes; the new-value pointer is null.
let result = unsafe {
libc::sysctlbyname(
c"kern.bootsessionuuid".as_ptr(),
buffer.as_mut_ptr().cast(),
&mut size,
std::ptr::null_mut(),
/*newlen*/ 0,
)
};
if result != 0 {
return Err(std::io::Error::last_os_error()).context("failed to read macOS boot ID");
}
anyhow::ensure!(size == buffer.len(), "incomplete macOS boot ID");
Ok(std::ffi::CStr::from_bytes_with_nul(&buffer)?
.to_str()?
.to_owned())
}
#[cfg(target_os = "linux")]
pub(super) async fn read_process_details(pid: u32) -> Result<(bool, ProcessIdentity)> {
let stat = tokio::fs::read(format!("/proc/{pid}/stat"))
.await
.with_context(|| format!("failed to read process stat for pid-managed process {pid}"))?;
let (state, start_ticks) = parse_stat(&stat)?;
Ok((
state == "Z",
ProcessIdentity::Linux {
boot_id: read_boot_id().await?,
start_ticks,
},
))
}
#[cfg(target_os = "linux")]
async fn read_boot_id() -> Result<String> {
let boot_id = tokio::fs::read_to_string("/proc/sys/kernel/random/boot_id")
.await
.context("failed to read Linux boot ID")?;
let boot_id = boot_id.trim();
anyhow::ensure!(!boot_id.is_empty(), "Linux boot ID is empty");
Ok(boot_id.to_owned())
}
#[cfg(any(target_os = "linux", test))]
fn parse_stat(stat: &[u8]) -> Result<(String, u64)> {
// comm (field 2) can contain spaces and closing parentheses. The final ')'
// terminates it; splitting the whole line on whitespace miscounts fields.
let end = stat
.iter()
.rposition(|byte| *byte == b')')
.context("process stat has no comm")?;
let fields = std::str::from_utf8(&stat[end + 1..]).context("invalid process stat fields")?;
let mut fields = fields.split_whitespace();
let state = fields.next().context("process stat has no state")?;
let start_ticks = fields
.nth(/*n*/ 18)
.context("process stat has no start time")?
.parse()
.context("process stat start time is invalid")?;
Ok((state.to_string(), start_ticks))
}
#[cfg(test)]
#[path = "pid_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,89 @@
use super::parse_stat;
use pretty_assertions::assert_eq;
#[test]
fn parses_start_ticks_after_comm_with_spaces_and_parentheses() {
let stat =
b"123 (codex \xff) worker) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 987654321 20";
assert_eq!(parse_stat(stat).unwrap(), ("S".to_string(), 987654321));
}
#[test]
fn reads_earlier_linux_identity_field() {
use crate::backend::pid::PidRecord;
let mut expected = serde_json::json!({
"pid": 42,
"processStartTime": "legacy timestamp",
"linuxProcessIdentity": {"bootId": "boot", "startTicks": 123},
});
let record: PidRecord = serde_json::from_value(expected.clone()).unwrap();
expected["processIdentity"] = expected
.as_object_mut()
.unwrap()
.remove("linuxProcessIdentity")
.unwrap();
assert_eq!(serde_json::to_value(record).unwrap(), expected);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn previous_boot_does_not_require_process_inspection() {
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
let mut record = serde_json::to_value(identity).unwrap();
record["bootId"] = "previous boot".into();
let identity: super::ProcessIdentity = serde_json::from_value(record).unwrap();
// An invalid PID would make process inspection fail if it preceded the boot check.
assert_eq!(
identity.matches_process(u32::MAX).await.unwrap(),
(false, false)
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn reused_pid_can_belong_to_root() {
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
// launchd is root-owned: PROC_PIDTBSDINFO returns EPERM for an ordinary caller.
assert_eq!(
identity.matches_process(/*pid*/ 1).await.unwrap(),
(false, false)
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn promotes_timestamp_only_macos_record() {
use crate::backend::pid::PidBackend;
use crate::backend::pid::PidRecord;
let temp = tempfile::TempDir::new().unwrap();
let path = temp.path().join("server.pid");
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
let mut legacy = serde_json::to_value(&identity).unwrap();
legacy.as_object_mut().unwrap().remove("bootId");
legacy.as_object_mut().unwrap().remove("uniqueId");
let mut record = PidRecord {
pid: std::process::id(),
process_start_time: "unused legacy text".into(),
process_identity: Some(serde_json::from_value(legacy).unwrap()),
executable_identity: None,
};
std::fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap();
let backend = PidBackend::new(
temp.path().join("codex"),
path.clone(),
/*remote_control_enabled*/ false,
);
backend.promote_legacy_identity().await.unwrap();
record.process_identity = Some(identity);
assert_eq!(
serde_json::from_slice::<PidRecord>(&std::fs::read(path).unwrap()).unwrap(),
record,
);
}

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