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,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "app-server-test-client",
crate_name = "codex_app_server_test_client",
)

View File

@@ -0,0 +1,31 @@
[package]
name = "codex-app-server-test-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
codex-app-server-protocol = { workspace = true }
codex-core = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-cli = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tungstenite = { workspace = true }
url = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[lib]
doctest = false
[dev-dependencies]
pretty_assertions = { workspace = true }

View File

@@ -0,0 +1,185 @@
# App Server Test Client
Quickstart for running and hitting `codex app-server`.
## Quickstart
Run from `<reporoot>/codex-rs`.
```bash
# 1) Build debug codex binary
cargo build -p codex-cli --bin codex
# 2) Start websocket app-server in background
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
serve --listen ws://127.0.0.1:4222 --kill
# 3) Call app-server (defaults to ws://127.0.0.1:4222)
cargo run -p codex-app-server-test-client -- model-list
```
`send-message` and `send-message-v2` handle `request_user_input` server requests interactively.
When Codex asks a question, choose a numbered option (or `o` for a free-form answer when offered)
and the client will send the response and continue streaming the same turn.
## Testing Codex-managed Amazon Bedrock login
`test-login --amazon-bedrock` initializes the experimental app-server API, sends an
`account/login/start` request with an Amazon Bedrock API key, and waits for the
`account/login/completed` and `account/updated` notifications. Login replaces the current primary
credential and sets `model_provider = "amazon-bedrock"`, so use an isolated `CODEX_HOME` when
testing.
```bash
export CODEX_HOME="$(mktemp -d)"
printf 'cli_auth_credentials_store = "file"\n' > "$CODEX_HOME/config.toml"
cargo build -p codex-cli --bin codex
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
test-login \
--amazon-bedrock \
--api-key "<BEDROCK_API_KEY>" \
--region us-west-2
```
The test client redacts `apiKey` from its outbound request log. After login, start a fresh Codex
process with the same `CODEX_HOME` to verify that it uses the persisted managed credential.
## Testing logout
`test-logout` initializes the app-server, sends an `account/logout` request, and waits for the
resulting `account/updated` notification. It uses the active `CODEX_HOME`, so point it at an
isolated directory when testing credential cleanup.
```bash
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
test-logout
```
## Testing Plugin Analytics
The `plugin-analytics-smoke` command exercises `plugin/installed`, plugin
enable/disable config writes, and a structured plugin mention through one
app-server connection. Analytics are captured to a local JSONL file and are
not sent to the analytics backend. The model turn uses a loopback Responses
API server.
The selected plugin must already be installed and enabled remotely, and the
active Codex profile must be authenticated. On a fresh local cache, the command
retries ephemeral turns while the installed remote bundle finishes syncing.
```bash
# Build a debug Codex binary; analytics capture is unavailable in release builds.
cargo build -p codex-cli --bin codex
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
plugin-analytics-smoke \
--plugin-id linear@openai-curated-remote
```
Use `--capture-file /tmp/plugin-analytics.jsonl` to select the output path.
The command validates one `codex_plugin_disabled`, `codex_plugin_enabled`, and
`codex_plugin_used` event with the expected local and remote plugin identities
and capability metadata. Each event includes the local ID in `plugin_id` and the
backend ID in `remote_plugin_id`. The enabled and disabled events come from
successful writes to the temporary config; the command does not mutate the
remote enabled state. It prints the events and leaves the JSONL file in place
for inspection. It does not install or uninstall plugins and does not modify
the profile's persistent config.
### Testing remote install and uninstall analytics
`plugin-analytics-mutation-smoke` is a manually invoked live smoke test. It
contacts the configured remote plugin API and temporarily changes the active
account's installed-plugin state. It is not run by `cargo test`, `just test`,
or CI.
Choose a remote plugin that is available to the active account and is not
currently installed. The command refuses to run when the plugin is already
installed, installs it, validates `codex_plugin_installed`, uninstalls it, and
validates `codex_plugin_uninstalled`, and verifies that the original
uninstalled state was restored.
The mutation events include the local Codex ID in `plugin_id` and the backend ID
in `remote_plugin_id`.
`--remote-plugin-id` takes the backend ID, such as `plugins~Plugin_...`, not the
local `<plugin>@<marketplace>` ID.
```bash
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
plugin-analytics-mutation-smoke \
--remote-plugin-id <REMOTE_PLUGIN_ID> \
--confirm-account-mutation \
--capture-file /tmp/plugin-mutation-analytics.jsonl
```
Analytics use the normal queue, reduction, batching, and serialization path,
but the debug capture destination suppresses analytics network delivery. The
command prints one of these final states:
- `PASS`: the install and uninstall events validated and the plugin is uninstalled.
- `FAIL-CLEAN`: validation failed, but the original uninstalled state was
restored.
- `FAIL-LOCAL-CACHE`: the backend is uninstalled, but local cleanup reported
an error.
- `FAIL-DIRTY`: cleanup failed and the plugin still appears installed.
- `FAIL-UNKNOWN`: the command could not verify the final installed state.
For a dirty or uncertain result, retry cleanup with:
```bash
cargo run -p codex-app-server-test-client -- \
--codex-bin ./target/debug/codex \
plugin-remote-uninstall \
--remote-plugin-id <REMOTE_PLUGIN_ID> \
--confirm-account-mutation
```
Cleanup does not require analytics capture or a debug Codex binary. When the
smoke uses global `--config` overrides, its printed recovery command preserves
them so cleanup targets the same backend and account.
## Watching Raw Inbound Traffic
Initialize a connection, then print every inbound JSON-RPC message until you stop it with
`Ctrl+C`:
```bash
cargo run -p codex-app-server-test-client -- watch
```
## Testing Thread Rejoin Behavior
Build and start an app server using commands above. The app-server log is written to `/tmp/codex-app-server-test-client/app-server.log`
### 1) Get a thread id
Create at least one thread, then list threads:
```bash
cargo run -p codex-app-server-test-client -- send-message-v2 "seed thread for rejoin test"
cargo run -p codex-app-server-test-client -- thread-list --limit 5
```
Copy a thread id from the `thread-list` output.
### 2) Rejoin while a turn is in progress (two terminals)
Terminal A:
```bash
cargo run --bin codex-app-server-test-client -- \
resume-message-v2 <THREAD_ID> "respond with thorough docs on the rust core"
```
Terminal B (while Terminal A is still streaming):
```bash
cargo run --bin codex-app-server-test-client -- thread-resume <THREAD_ID>
```

View File

@@ -0,0 +1,46 @@
#!/bin/sh
set -eu
require_env() {
eval "value=\${$1-}"
if [ -z "$value" ]; then
echo "missing required env var: $1" >&2
exit 1
fi
}
require_env APP_SERVER_URL
require_env APP_SERVER_TEST_CLIENT_BIN
thread_id="${CODEX_THREAD_ID:-${THREAD_ID-}}"
if [ -z "$thread_id" ]; then
echo "missing required env var: CODEX_THREAD_ID" >&2
exit 1
fi
hold_seconds="${ELICITATION_HOLD_SECONDS:-15}"
incremented=0
cleanup() {
if [ "$incremented" -eq 1 ]; then
"$APP_SERVER_TEST_CLIENT_BIN" --url "$APP_SERVER_URL" \
thread-decrement-elicitation "$thread_id" >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT INT TERM HUP
echo "[elicitation-hold] increment thread=$thread_id"
"$APP_SERVER_TEST_CLIENT_BIN" --url "$APP_SERVER_URL" \
thread-increment-elicitation "$thread_id"
incremented=1
echo "[elicitation-hold] sleeping ${hold_seconds}s"
sleep "$hold_seconds"
echo "[elicitation-hold] decrement thread=$thread_id"
"$APP_SERVER_TEST_CLIENT_BIN" --url "$APP_SERVER_URL" \
thread-decrement-elicitation "$thread_id"
incremented=0
echo "[elicitation-hold] done"

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,145 @@
use anyhow::Context;
use anyhow::Result;
use std::io;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::net::TcpStream;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;
pub(super) struct LoopbackResponsesServer {
base_url: String,
shutdown: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl LoopbackResponsesServer {
pub(super) fn start() -> Result<Self> {
let listener =
TcpListener::bind("127.0.0.1:0").context("bind loopback Responses API server")?;
listener
.set_nonblocking(true)
.context("set loopback Responses API server nonblocking")?;
let address = listener.local_addr()?;
let shutdown = Arc::new(AtomicBool::new(false));
let thread_shutdown = Arc::clone(&shutdown);
let thread = thread::spawn(move || {
while !thread_shutdown.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
if let Err(err) = handle_model_connection(stream) {
eprintln!("loopback Responses API server error: {err}");
}
}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(err) => {
eprintln!("loopback Responses API accept error: {err}");
break;
}
}
}
});
Ok(Self {
base_url: format!("http://{address}"),
shutdown,
thread: Some(thread),
})
}
pub(super) fn base_url(&self) -> &str {
&self.base_url
}
}
impl Drop for LoopbackResponsesServer {
fn drop(&mut self) {
self.shutdown.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
fn handle_model_connection(mut stream: TcpStream) -> io::Result<()> {
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let request = read_http_request(&mut stream)?;
let request_line = request
.split(|byte| *byte == b'\n')
.next()
.and_then(|line| std::str::from_utf8(line).ok())
.unwrap_or_default();
if request_line.starts_with("POST ") && request_line.contains("/responses ") {
let body = concat!(
"event: response.created\n",
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp-plugin-analytics\"}}\n\n",
"event: response.completed\n",
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp-plugin-analytics\",\"usage\":{\"input_tokens\":0,\"input_tokens_details\":null,\"output_tokens\":0,\"output_tokens_details\":null,\"total_tokens\":0}}}\n\n"
);
write_http_response(&mut stream, "200 OK", "text/event-stream", body)
} else {
write_http_response(
&mut stream,
"404 Not Found",
"application/json",
r#"{"error":"not found"}"#,
)
}
}
fn read_http_request(stream: &mut TcpStream) -> io::Result<Vec<u8>> {
let mut request = Vec::new();
let mut buffer = [0_u8; 4096];
let header_end = loop {
let read = stream.read(&mut buffer)?;
if read == 0 {
return Ok(request);
}
request.extend_from_slice(&buffer[..read]);
if let Some(position) = request.windows(4).position(|window| window == b"\r\n\r\n") {
break position + 4;
}
};
let content_length = parse_content_length(&request[..header_end]);
while request.len() < header_end + content_length {
let read = stream.read(&mut buffer)?;
if read == 0 {
break;
}
request.extend_from_slice(&buffer[..read]);
}
Ok(request)
}
fn parse_content_length(headers: &[u8]) -> usize {
String::from_utf8_lossy(headers)
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().ok())
.flatten()
})
.unwrap_or(0)
}
fn write_http_response(
stream: &mut TcpStream,
status: &str,
content_type: &str,
body: &str,
) -> io::Result<()> {
write!(
stream,
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)?;
stream.flush()
}

View File

@@ -0,0 +1,7 @@
use anyhow::Result;
use tokio::runtime::Builder;
fn main() -> Result<()> {
let runtime = Builder::new_current_thread().enable_all().build()?;
runtime.block_on(codex_app_server_test_client::run())
}

View File

@@ -0,0 +1,107 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde_json::Value;
use std::fs;
use std::io;
use std::path::Path;
pub(super) fn read_events_for_remote_plugin(
path: &Path,
remote_plugin_id: &str,
) -> Result<Vec<Value>> {
let contents = match fs::read_to_string(path) {
Ok(contents) => contents,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => {
return Err(err).with_context(|| format!("read capture file {}", path.display()));
}
};
let mut matching = Vec::new();
for (index, line) in contents.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let payload: Value = serde_json::from_str(line).with_context(|| {
format!(
"parse analytics capture line {} from {}",
index + 1,
path.display()
)
})?;
let events = payload["events"]
.as_array()
.context("analytics capture payload is missing events")?;
matching.extend(
events
.iter()
.filter(|event| event["event_params"]["remote_plugin_id"] == remote_plugin_id)
.cloned(),
);
}
Ok(matching)
}
pub(super) struct PluginEventIdentity<'a> {
pub(super) plugin_id: &'a str,
pub(super) remote_plugin_id: &'a str,
pub(super) plugin_name: &'a str,
pub(super) marketplace_name: &'a str,
}
pub(super) fn validate_mutation_events(
events: Vec<Value>,
expected: PluginEventIdentity<'_>,
) -> Result<Vec<Value>> {
let mut validated = Vec::new();
for event_type in ["codex_plugin_installed", "codex_plugin_uninstalled"] {
let matching = events
.iter()
.filter(|event| event["event_type"] == event_type)
.collect::<Vec<_>>();
let [event] = matching.as_slice() else {
bail!(
"expected exactly one `{event_type}` event for `{}`, found {}",
expected.remote_plugin_id,
matching.len()
);
};
validate_event(event, &expected)?;
validated.push((*event).clone());
}
Ok(validated)
}
fn validate_event(event: &Value, expected: &PluginEventIdentity<'_>) -> Result<()> {
let params = &event["event_params"];
require_string(params, "plugin_id", expected.plugin_id)?;
require_string(params, "remote_plugin_id", expected.remote_plugin_id)?;
require_string(params, "plugin_name", expected.plugin_name)?;
require_string(params, "marketplace_name", expected.marketplace_name)?;
for field in [
"has_skills",
"mcp_server_count",
"connector_ids",
"product_client_id",
] {
if params.get(field).is_none_or(Value::is_null) {
bail!(
"{} event has null or missing `{field}`",
event["event_type"]
);
}
}
Ok(())
}
fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> {
let actual = params.get(field).and_then(Value::as_str);
if actual != Some(expected) {
bail!("expected `{field}` to be `{expected}`, got {actual:?}");
}
Ok(())
}
#[cfg(test)]
#[path = "plugin_analytics_capture_tests.rs"]
mod tests;

View File

@@ -0,0 +1,97 @@
use super::PluginEventIdentity;
use super::read_events_for_remote_plugin;
use super::validate_mutation_events;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::PathBuf;
use std::process;
use std::time::SystemTime;
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_test";
#[test]
fn reads_and_validates_remote_plugin_mutation_events() {
let path = unique_capture_path("valid");
let installed = mutation_event("codex_plugin_installed");
let uninstalled = mutation_event("codex_plugin_uninstalled");
let unrelated = json!({
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "other@openai-curated-remote",
"remote_plugin_id": "plugins~Plugin_other"
}
});
let contents = [
json!({"events": [unrelated]}),
json!({"events": [installed, uninstalled]}),
]
.into_iter()
.map(|payload| serde_json::to_string(&payload).expect("serialize capture payload"))
.collect::<Vec<_>>()
.join("\n");
fs::write(&path, contents).expect("write capture file");
let events = read_events_for_remote_plugin(&path, REMOTE_PLUGIN_ID)
.expect("read matching plugin events");
let validated =
validate_mutation_events(events, expected_identity()).expect("validate mutation events");
assert_eq!(validated, vec![installed, uninstalled]);
fs::remove_file(path).expect("remove capture file");
}
#[test]
fn rejects_duplicate_mutation_events() {
let installed = mutation_event("codex_plugin_installed");
let error = validate_mutation_events(vec![installed.clone(), installed], expected_identity())
.expect_err("duplicate install events should fail validation");
assert!(error.to_string().contains("found 2"));
}
#[test]
fn rejects_missing_capability_metadata() {
let mut installed = mutation_event("codex_plugin_installed");
installed["event_params"]["has_skills"] = Value::Null;
let error = validate_mutation_events(vec![installed], expected_identity())
.expect_err("missing capability metadata should fail validation");
assert!(error.to_string().contains("has_skills"));
}
fn mutation_event(event_type: &str) -> Value {
json!({
"event_type": event_type,
"event_params": {
"plugin_id": "sample@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "sample",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": "test-client"
}
})
}
fn expected_identity() -> PluginEventIdentity<'static> {
PluginEventIdentity {
plugin_id: "sample@openai-curated-remote",
remote_plugin_id: REMOTE_PLUGIN_ID,
plugin_name: "sample",
marketplace_name: "openai-curated-remote",
}
}
fn unique_capture_path(name: &str) -> PathBuf {
let nonce = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("system clock should be after Unix epoch")
.as_nanos();
std::env::temp_dir().join(format!(
"codex-plugin-analytics-capture-{name}-{}-{nonce}.jsonl",
process::id()
))
}

View File

@@ -0,0 +1,488 @@
use super::CodexClient;
use super::plugin_analytics_capture::PluginEventIdentity;
use super::plugin_analytics_capture::read_events_for_remote_plugin;
use super::plugin_analytics_capture::validate_mutation_events;
use super::plugin_analytics_smoke::ANALYTICS_CAPTURE_ENV_VAR;
use super::plugin_analytics_smoke::prepare_capture_file;
use super::plugin_analytics_smoke::wait_until_capture_is_ready;
use super::shell_quote;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::PluginAvailability;
use codex_app_server_protocol::PluginInstallParams;
use codex_app_server_protocol::PluginInstallPolicy;
use codex_app_server_protocol::PluginInstallResponse;
use codex_app_server_protocol::PluginReadParams;
use codex_app_server_protocol::PluginReadResponse;
use codex_app_server_protocol::PluginUninstallParams;
use codex_app_server_protocol::PluginUninstallResponse;
use serde_json::Value;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use std::process;
use std::thread;
use std::time::Duration;
use std::time::Instant;
const REMOTE_MARKETPLACE_HINT: &str = "openai-curated-remote";
const STATE_TIMEOUT: Duration = Duration::from_secs(15);
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
pub(super) fn run(
codex_bin: &Path,
config_overrides: &[String],
remote_plugin_id: &str,
confirmation: AccountMutationConfirmation,
capture_file: Option<PathBuf>,
) -> Result<()> {
require_confirmation(confirmation)?;
let capture_path = capture_file.unwrap_or_else(|| {
std::env::temp_dir().join(format!(
"codex-plugin-analytics-mutation-{}.jsonl",
process::id()
))
});
prepare_capture_file(&capture_path)?;
let mut client = spawn_client(codex_bin, config_overrides, &capture_path)?;
wait_until_capture_is_ready(&capture_path)?;
client.initialize()?;
let initial = read_remote_plugin(&mut client, remote_plugin_id)?;
validate_initial_plugin(&initial, remote_plugin_id)?;
println!(
"remote plugin mutation smoke: local_id={} remote_id={} marketplace={}",
initial.plugin_id, initial.remote_plugin_id, initial.marketplace_name
);
let MutationSequenceResult {
result: sequence_result,
uninstall_rpc_failed,
} = run_mutation_sequence(&mut client, &capture_path, &initial);
let restoration = restore_uninstalled_state(&mut client, remote_plugin_id);
println!("capture file: {}", capture_path.display());
match (sequence_result, restoration) {
(Ok(events), RestorationStatus::Clean) => {
println!(
"\n[plugin analytics mutation smoke validated]\n{}",
serde_json::to_string_pretty(&events)?
);
println!("PASS: analytics validated; original uninstalled state restored");
Ok(())
}
(Err(err), RestorationStatus::Clean) if uninstall_rpc_failed => {
eprintln!(
"FAIL-LOCAL-CACHE: backend state is uninstalled, but the uninstall RPC failed after the backend mutation: {err:#}"
);
Err(err)
}
(Err(err), RestorationStatus::Clean) => {
eprintln!("FAIL-CLEAN: {err:#}");
eprintln!("The original uninstalled account state was restored.");
Err(err)
}
(sequence_result, RestorationStatus::LocalCleanupFailure(cleanup_err)) => {
let sequence_err = sequence_result.err();
eprintln!(
"FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {cleanup_err:#}"
);
Err(sequence_err.unwrap_or(cleanup_err))
}
(sequence_result, RestorationStatus::Dirty(cleanup_err)) => {
if let Err(err) = sequence_result {
eprintln!("mutation smoke failed before cleanup: {err:#}");
}
print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &cleanup_err);
Err(cleanup_err)
}
(sequence_result, RestorationStatus::Unknown(cleanup_err)) => {
if let Err(err) = sequence_result {
eprintln!("mutation smoke failed before final state verification: {err:#}");
}
eprintln!(
"FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {cleanup_err:#}"
);
print_recovery_command(codex_bin, config_overrides, remote_plugin_id);
Err(cleanup_err)
}
}
}
pub(super) fn run_cleanup(
codex_bin: &Path,
config_overrides: &[String],
remote_plugin_id: &str,
confirmation: AccountMutationConfirmation,
) -> Result<()> {
require_confirmation(confirmation)?;
let mut overrides = config_overrides.to_vec();
overrides.extend([
"analytics.enabled=false".to_string(),
"features.plugins=true".to_string(),
]);
let mut client = CodexClient::spawn_stdio(codex_bin, &overrides)?;
client.initialize()?;
match restore_uninstalled_state(&mut client, remote_plugin_id) {
RestorationStatus::Clean => {
println!("PASS: `{remote_plugin_id}` is uninstalled");
Ok(())
}
RestorationStatus::LocalCleanupFailure(err) => {
eprintln!(
"FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {err:#}"
);
Err(err)
}
RestorationStatus::Dirty(err) => {
print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &err);
Err(err)
}
RestorationStatus::Unknown(err) => {
eprintln!(
"FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {err:#}"
);
Err(err)
}
}
}
#[derive(Clone, Copy)]
pub(super) enum AccountMutationConfirmation {
Confirmed,
Missing,
}
impl AccountMutationConfirmation {
pub(super) fn from_flag(confirm_account_mutation: bool) -> Self {
if confirm_account_mutation {
Self::Confirmed
} else {
Self::Missing
}
}
}
fn require_confirmation(confirmation: AccountMutationConfirmation) -> Result<()> {
if matches!(confirmation, AccountMutationConfirmation::Missing) {
bail!(
"this command installs and uninstalls a plugin on the active account; rerun with --confirm-account-mutation"
);
}
Ok(())
}
#[derive(Clone, Copy, Debug)]
enum ExpectedInstalledState {
Installed,
Uninstalled,
}
impl ExpectedInstalledState {
fn is_installed(self) -> bool {
matches!(self, Self::Installed)
}
}
fn spawn_client(
codex_bin: &Path,
config_overrides: &[String],
capture_path: &Path,
) -> Result<CodexClient> {
let mut overrides = config_overrides.to_vec();
overrides.extend([
"analytics.enabled=true".to_string(),
"features.plugins=true".to_string(),
]);
let environment = vec![(
OsString::from(ANALYTICS_CAPTURE_ENV_VAR),
capture_path.as_os_str().to_os_string(),
)];
CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &environment)
}
#[derive(Clone, Debug)]
struct RemotePluginExpectation {
plugin_id: String,
remote_plugin_id: String,
plugin_name: String,
marketplace_name: String,
installed: bool,
install_policy: PluginInstallPolicy,
availability: PluginAvailability,
}
fn read_remote_plugin(
client: &mut CodexClient,
remote_plugin_id: &str,
) -> Result<RemotePluginExpectation> {
let request_id = client.request_id();
let response: PluginReadResponse = client.send_request(
ClientRequest::PluginRead {
request_id: request_id.clone(),
params: PluginReadParams {
marketplace_path: None,
remote_marketplace_name: Some(REMOTE_MARKETPLACE_HINT.to_string()),
plugin_name: remote_plugin_id.to_string(),
},
},
request_id,
"plugin/read",
)?;
let summary = response.plugin.summary;
let actual_remote_plugin_id = summary
.remote_plugin_id
.with_context(|| format!("plugin/read returned no remote id for `{remote_plugin_id}`"))?;
if actual_remote_plugin_id != remote_plugin_id {
bail!(
"plugin/read returned remote id `{actual_remote_plugin_id}` for requested id `{remote_plugin_id}`"
);
}
Ok(RemotePluginExpectation {
plugin_id: summary.id,
remote_plugin_id: actual_remote_plugin_id,
plugin_name: summary.name,
marketplace_name: response.plugin.marketplace_name,
installed: summary.installed,
install_policy: summary.install_policy,
availability: summary.availability,
})
}
fn validate_initial_plugin(plugin: &RemotePluginExpectation, remote_plugin_id: &str) -> Result<()> {
if plugin.installed {
bail!(
"refusing to run: remote plugin `{remote_plugin_id}` is already installed; choose an initially uninstalled plugin"
);
}
if plugin.availability != PluginAvailability::Available {
bail!(
"remote plugin `{remote_plugin_id}` is not available: {:?}",
plugin.availability
);
}
if plugin.install_policy == PluginInstallPolicy::NotAvailable {
bail!("remote plugin `{remote_plugin_id}` is not available for install");
}
Ok(())
}
struct MutationSequenceResult {
result: Result<Vec<Value>>,
uninstall_rpc_failed: bool,
}
fn run_mutation_sequence(
client: &mut CodexClient,
capture_path: &Path,
expected: &RemotePluginExpectation,
) -> MutationSequenceResult {
let mut uninstall_rpc_failed = false;
let result = (|| {
install_remote_plugin(client, expected)?;
wait_for_installed_state(
client,
&expected.remote_plugin_id,
ExpectedInstalledState::Installed,
)?;
wait_for_remote_plugin_event(
capture_path,
&expected.remote_plugin_id,
"codex_plugin_installed",
)?;
let uninstall_error = uninstall_remote_plugin(client, &expected.remote_plugin_id).err();
uninstall_rpc_failed = uninstall_error.is_some();
wait_for_installed_state(
client,
&expected.remote_plugin_id,
ExpectedInstalledState::Uninstalled,
)
.map_err(|state_err| {
if let Some(err) = uninstall_error.as_ref() {
anyhow!("plugin/uninstall failed: {err:#}; final state check failed: {state_err:#}")
} else {
state_err
}
})?;
wait_for_remote_plugin_event(
capture_path,
&expected.remote_plugin_id,
"codex_plugin_uninstalled",
)?;
let captured_events =
read_events_for_remote_plugin(capture_path, &expected.remote_plugin_id)?;
let events = validate_mutation_events(
captured_events,
PluginEventIdentity {
plugin_id: &expected.plugin_id,
remote_plugin_id: &expected.remote_plugin_id,
plugin_name: &expected.plugin_name,
marketplace_name: &expected.marketplace_name,
},
)?;
if let Some(err) = uninstall_error {
return Err(err.context(
"plugin/uninstall reported an error after the backend became uninstalled",
));
}
Ok(events)
})();
MutationSequenceResult {
result,
uninstall_rpc_failed,
}
}
fn install_remote_plugin(client: &mut CodexClient, plugin: &RemotePluginExpectation) -> Result<()> {
let request_id = client.request_id();
let _: PluginInstallResponse = client.send_request(
ClientRequest::PluginInstall {
request_id: request_id.clone(),
params: PluginInstallParams {
marketplace_path: None,
remote_marketplace_name: Some(plugin.marketplace_name.clone()),
install_attempt_id: None,
plugin_name: plugin.remote_plugin_id.clone(),
},
},
request_id,
"plugin/install",
)?;
Ok(())
}
fn uninstall_remote_plugin(client: &mut CodexClient, remote_plugin_id: &str) -> Result<()> {
let request_id = client.request_id();
let _: PluginUninstallResponse = client.send_request(
ClientRequest::PluginUninstall {
request_id: request_id.clone(),
params: PluginUninstallParams {
plugin_id: remote_plugin_id.to_string(),
},
},
request_id,
"plugin/uninstall",
)?;
Ok(())
}
fn wait_for_installed_state(
client: &mut CodexClient,
remote_plugin_id: &str,
expected_state: ExpectedInstalledState,
) -> Result<RemotePluginExpectation> {
let deadline = Instant::now() + STATE_TIMEOUT;
loop {
match read_remote_plugin(client, remote_plugin_id) {
Ok(plugin) if plugin.installed == expected_state.is_installed() => return Ok(plugin),
Ok(_) => {}
Err(err) if Instant::now() >= deadline => return Err(err),
Err(_) => {}
}
if Instant::now() >= deadline {
bail!(
"timed out waiting for remote plugin `{remote_plugin_id}` to become {expected_state:?}"
);
}
thread::sleep(POLL_INTERVAL);
}
}
enum RestorationStatus {
Clean,
LocalCleanupFailure(anyhow::Error),
Dirty(anyhow::Error),
Unknown(anyhow::Error),
}
fn restore_uninstalled_state(
client: &mut CodexClient,
remote_plugin_id: &str,
) -> RestorationStatus {
let current = match read_remote_plugin(client, remote_plugin_id) {
Ok(current) => current,
Err(err) => return RestorationStatus::Unknown(err),
};
if !current.installed {
return RestorationStatus::Clean;
}
let uninstall_result = uninstall_remote_plugin(client, remote_plugin_id);
match wait_for_installed_state(
client,
remote_plugin_id,
ExpectedInstalledState::Uninstalled,
) {
Ok(_) => match uninstall_result {
Ok(()) => RestorationStatus::Clean,
Err(err) => RestorationStatus::LocalCleanupFailure(err),
},
Err(state_err) => {
let error = match uninstall_result {
Ok(()) => state_err,
Err(uninstall_err) => anyhow!(
"cleanup uninstall failed: {uninstall_err:#}; state verification failed: {state_err:#}"
),
};
RestorationStatus::Dirty(error)
}
}
}
fn wait_for_remote_plugin_event(
path: &Path,
remote_plugin_id: &str,
event_type: &str,
) -> Result<()> {
let deadline = Instant::now() + CAPTURE_TIMEOUT;
loop {
let events = read_events_for_remote_plugin(path, remote_plugin_id)?;
if events.iter().any(|event| event["event_type"] == event_type) {
return Ok(());
}
if Instant::now() >= deadline {
bail!("timed out waiting for `{event_type}` for remote plugin `{remote_plugin_id}`");
}
thread::sleep(POLL_INTERVAL);
}
}
fn print_dirty_recovery(
codex_bin: &Path,
config_overrides: &[String],
remote_plugin_id: &str,
err: &anyhow::Error,
) {
eprintln!(
"FAIL-DIRTY: remote plugin `{remote_plugin_id}` still appears installed after cleanup: {err:#}"
);
print_recovery_command(codex_bin, config_overrides, remote_plugin_id);
}
fn print_recovery_command(codex_bin: &Path, config_overrides: &[String], remote_plugin_id: &str) {
let test_client = std::env::current_exe()
.map(|path| path.display().to_string())
.unwrap_or_else(|_| "codex-app-server-test-client".to_string());
let mut command = format!(
"{} --codex-bin {}",
shell_quote(&test_client),
shell_quote(&codex_bin.display().to_string())
);
for override_kv in config_overrides {
command.push_str(&format!(" --config {}", shell_quote(override_kv)));
}
command.push_str(&format!(
" plugin-remote-uninstall --remote-plugin-id {} --confirm-account-mutation",
shell_quote(remote_plugin_id)
));
eprintln!("Recovery command:");
eprintln!(" {command}");
}

View File

@@ -0,0 +1,504 @@
use super::CodexClient;
use super::loopback_responses_server::LoopbackResponsesServer;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::ConfigValueWriteParams;
use codex_app_server_protocol::ConfigWriteResponse;
use codex_app_server_protocol::MergeStrategy;
use codex_app_server_protocol::PluginAvailability;
use codex_app_server_protocol::PluginInstalledParams;
use codex_app_server_protocol::PluginInstalledResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_app_server_protocol::WriteStatus;
use serde_json::Value;
use serde_json::json;
use std::ffi::OsString;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::process;
use std::thread;
use std::time::Duration;
use std::time::Instant;
pub(super) const ANALYTICS_CAPTURE_ENV_VAR: &str = "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE";
const TEST_USER_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE";
const CAPTURE_READY_TIMEOUT: Duration = Duration::from_secs(5);
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
const CAPTURE_POLL_INTERVAL: Duration = Duration::from_millis(50);
const PLUGIN_READY_TIMEOUT: Duration = Duration::from_secs(30);
const PLUGIN_READY_RETRY_INTERVAL: Duration = Duration::from_millis(250);
const MOCK_MODEL_SLUG: &str = "plugin-analytics-smoke";
const MOCK_PROVIDER_ID: &str = "plugin_analytics_smoke";
pub(super) fn run(
codex_bin: &Path,
config_overrides: &[String],
plugin_id: &str,
capture_file: Option<PathBuf>,
) -> Result<()> {
let capture_path = capture_file.unwrap_or_else(|| {
std::env::temp_dir().join(format!("codex-plugin-analytics-{}.jsonl", process::id()))
});
prepare_capture_file(&capture_path)?;
let temporary_config = TemporaryConfigFile::create()?;
let responses_server = LoopbackResponsesServer::start()?;
let mut overrides = config_overrides.to_vec();
overrides.extend(smoke_config_overrides(responses_server.base_url())?);
let child_environment = vec![
(
OsString::from(ANALYTICS_CAPTURE_ENV_VAR),
capture_path.as_os_str().to_os_string(),
),
(
OsString::from(TEST_USER_CONFIG_ENV_VAR),
temporary_config.path().as_os_str().to_os_string(),
),
];
let mut client = CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &child_environment)?;
wait_until_capture_is_ready(&capture_path)?;
client.initialize()?;
let installed = plugin_installed(&mut client)?;
let expected = expected_plugin(&installed, plugin_id)?;
write_plugin_enabled(
&mut client,
temporary_config.path(),
plugin_id,
/*enabled*/ false,
)?;
write_plugin_enabled(
&mut client,
temporary_config.path(),
plugin_id,
/*enabled*/ true,
)?;
wait_for_plugin_usage(&mut client, &capture_path, &expected)?;
let events = wait_for_plugin_events(&capture_path, plugin_id)?;
let validated = validate_plugin_events(events, &expected)?;
println!(
"\n[plugin analytics smoke validated]\n{}",
serde_json::to_string_pretty(&validated)?
);
println!("capture file: {}", capture_path.display());
Ok(())
}
fn run_plugin_turn(client: &mut CodexClient, expected: &ExpectedPlugin) -> Result<String> {
let thread = client.thread_start(ThreadStartParams {
model: Some(MOCK_MODEL_SLUG.to_string()),
model_provider: Some(MOCK_PROVIDER_ID.to_string()),
base_instructions: Some(String::new()),
developer_instructions: Some(String::new()),
ephemeral: Some(true),
..Default::default()
})?;
let turn = client.turn_start(TurnStartParams {
thread_id: thread.thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Mention {
name: expected.plugin_name.clone(),
path: format!("plugin://{}", expected.plugin_id),
}],
..Default::default()
})?;
client.stream_turn(&thread.thread.id, &turn.turn.id)?;
if client.last_turn_status != Some(TurnStatus::Completed) {
bail!(
"plugin analytics smoke turn did not complete: status={:?}, error={:?}",
client.last_turn_status,
client.last_turn_error_message
);
}
Ok(turn.turn.id)
}
fn wait_for_plugin_usage(
client: &mut CodexClient,
capture_path: &Path,
expected: &ExpectedPlugin,
) -> Result<()> {
let deadline = Instant::now() + PLUGIN_READY_TIMEOUT;
let mut attempts = 0;
loop {
attempts += 1;
let turn_id = run_plugin_turn(client, expected)?;
// Turn completion is queued after plugin usage, so its captured event is the
// barrier that tells us whether this attempt resolved the plugin.
let events = wait_for_turn_analytics(capture_path, &turn_id)?;
if events.iter().any(|event| {
event["event_type"] == "codex_plugin_used"
&& event["event_params"]["turn_id"].as_str() == Some(turn_id.as_str())
&& event["event_params"]["plugin_id"].as_str() == Some(expected.plugin_id.as_str())
}) {
if attempts > 1 {
println!("remote plugin bundle became ready after {attempts} turn attempts");
}
return Ok(());
}
if Instant::now() >= deadline {
bail!(
"timed out waiting for remote plugin bundle `{}` to become usable after {attempts} turn attempts",
expected.plugin_id
);
}
thread::sleep(PLUGIN_READY_RETRY_INTERVAL);
}
}
#[derive(Debug)]
struct ExpectedPlugin {
plugin_id: String,
remote_plugin_id: String,
plugin_name: String,
marketplace_name: String,
}
fn plugin_installed(client: &mut CodexClient) -> Result<PluginInstalledResponse> {
let request_id = client.request_id();
client.send_request(
ClientRequest::PluginInstalled {
request_id: request_id.clone(),
params: PluginInstalledParams {
cwds: None,
install_suggestion_plugin_names: None,
},
},
request_id,
"plugin/installed",
)
}
fn expected_plugin(response: &PluginInstalledResponse, plugin_id: &str) -> Result<ExpectedPlugin> {
let matches = response
.marketplaces
.iter()
.flat_map(|marketplace| {
marketplace
.plugins
.iter()
.filter(move |plugin| plugin.id == plugin_id)
.map(move |plugin| (marketplace, plugin))
})
.collect::<Vec<_>>();
let [(marketplace, plugin)] = matches.as_slice() else {
bail!(
"expected exactly one installed plugin with local id `{plugin_id}`, found {}",
matches.len()
);
};
if !plugin.installed {
bail!("plugin `{plugin_id}` is not installed");
}
if !plugin.enabled {
bail!("plugin `{plugin_id}` is installed remotely but disabled");
}
if plugin.availability != PluginAvailability::Available {
bail!(
"plugin `{plugin_id}` is not available: {:?}",
plugin.availability
);
}
let remote_plugin_id = plugin
.remote_plugin_id
.as_ref()
.with_context(|| format!("plugin `{plugin_id}` does not have a remote plugin id"))?
.clone();
Ok(ExpectedPlugin {
plugin_id: plugin.id.clone(),
remote_plugin_id,
plugin_name: plugin.name.clone(),
marketplace_name: marketplace.name.clone(),
})
}
fn write_plugin_enabled(
client: &mut CodexClient,
config_path: &Path,
plugin_id: &str,
enabled: bool,
) -> Result<()> {
let request_id = client.request_id();
let response: ConfigWriteResponse = client.send_request(
ClientRequest::ConfigValueWrite {
request_id: request_id.clone(),
params: ConfigValueWriteParams {
key_path: format!("plugins.{plugin_id}.enabled"),
value: json!(enabled),
merge_strategy: MergeStrategy::Replace,
file_path: Some(config_path.display().to_string()),
expected_version: None,
},
},
request_id,
"config/value/write",
)?;
println!(
"< config/value/write plugin={plugin_id} enabled={enabled} status={:?}",
response.status
);
if response.status != WriteStatus::Ok {
bail!(
"config/value/write for plugin `{plugin_id}` enabled={enabled} was overridden: {:?}",
response.overridden_metadata
);
}
Ok(())
}
fn smoke_config_overrides(responses_base_url: &str) -> Result<Vec<String>> {
let provider_base_url = serde_json::to_string(&format!("{responses_base_url}/v1"))
.context("serialize mock provider base URL")?;
Ok(vec![
"analytics.enabled=true".to_string(),
"features.plugins=true".to_string(),
format!("model={}", quoted(MOCK_MODEL_SLUG)?),
format!("model_provider={}", quoted(MOCK_PROVIDER_ID)?),
format!(
"model_providers.{MOCK_PROVIDER_ID}.name={}",
quoted("Plugin analytics smoke mock provider")?
),
format!("model_providers.{MOCK_PROVIDER_ID}.base_url={provider_base_url}"),
format!(
"model_providers.{MOCK_PROVIDER_ID}.wire_api={}",
quoted("responses")?
),
format!("model_providers.{MOCK_PROVIDER_ID}.requires_openai_auth=false"),
format!("model_providers.{MOCK_PROVIDER_ID}.request_max_retries=0"),
format!("model_providers.{MOCK_PROVIDER_ID}.stream_max_retries=0"),
])
}
fn quoted(value: &str) -> Result<String> {
serde_json::to_string(value).context("serialize config string")
}
pub(super) fn prepare_capture_file(path: &Path) -> Result<()> {
let parent = path
.parent()
.context("capture file must have a parent directory")?;
if !parent.is_dir() {
bail!(
"capture file parent directory does not exist: {}",
parent.display()
);
}
match fs::remove_file(path) {
Ok(()) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => {
return Err(err)
.with_context(|| format!("remove previous capture file {}", path.display()));
}
}
Ok(())
}
pub(super) fn wait_until_capture_is_ready(path: &Path) -> Result<()> {
let deadline = Instant::now() + CAPTURE_READY_TIMEOUT;
loop {
match fs::metadata(path) {
Ok(_) => return Ok(()),
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => {
return Err(err)
.with_context(|| format!("inspect capture file {}", path.display()));
}
}
if Instant::now() >= deadline {
bail!(
"analytics capture did not become ready at {}; use a debug Codex binary",
path.display()
);
}
thread::sleep(CAPTURE_POLL_INTERVAL);
}
}
fn wait_for_plugin_events(path: &Path, plugin_id: &str) -> Result<Vec<Value>> {
let deadline = Instant::now() + CAPTURE_TIMEOUT;
loop {
let events = read_plugin_events(path, plugin_id)?;
if required_event_types()
.iter()
.all(|event_type| event_count(&events, event_type) >= 1)
{
return Ok(events);
}
if Instant::now() >= deadline {
bail!(
"timed out waiting for plugin analytics events in {}: found {:?}",
path.display(),
events
.iter()
.filter_map(|event| event["event_type"].as_str())
.collect::<Vec<_>>()
);
}
thread::sleep(CAPTURE_POLL_INTERVAL);
}
}
fn wait_for_turn_analytics(path: &Path, turn_id: &str) -> Result<Vec<Value>> {
let deadline = Instant::now() + CAPTURE_TIMEOUT;
loop {
let events = read_capture_events(path)?;
if events.iter().any(|event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"].as_str() == Some(turn_id)
}) {
return Ok(events);
}
if Instant::now() >= deadline {
bail!(
"timed out waiting for turn analytics for `{turn_id}` in {}",
path.display()
);
}
thread::sleep(CAPTURE_POLL_INTERVAL);
}
}
fn read_plugin_events(path: &Path, plugin_id: &str) -> Result<Vec<Value>> {
Ok(read_capture_events(path)?
.into_iter()
.filter(|event| event["event_params"]["plugin_id"] == plugin_id)
.collect())
}
fn read_capture_events(path: &Path) -> Result<Vec<Value>> {
let contents = match fs::read_to_string(path) {
Ok(contents) => contents,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => {
return Err(err).with_context(|| format!("read capture file {}", path.display()));
}
};
let mut captured = Vec::new();
for (index, line) in contents.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let payload: Value = serde_json::from_str(line).with_context(|| {
format!(
"parse analytics capture line {} from {}",
index + 1,
path.display()
)
})?;
let events = payload["events"]
.as_array()
.context("analytics capture payload is missing events")?;
captured.extend(events.iter().cloned());
}
Ok(captured)
}
fn validate_plugin_events(events: Vec<Value>, expected: &ExpectedPlugin) -> Result<Vec<Value>> {
let mut validated = Vec::new();
for event_type in required_event_types() {
let matching = events
.iter()
.filter(|event| event["event_type"] == event_type)
.collect::<Vec<_>>();
let [event] = matching.as_slice() else {
bail!(
"expected exactly one `{event_type}` event for `{}`, found {}",
expected.plugin_id,
matching.len()
);
};
validate_identity(event, expected)?;
if event_type == "codex_plugin_used" {
validate_used_metadata(event)?;
}
validated.push((*event).clone());
}
Ok(validated)
}
fn required_event_types() -> [&'static str; 3] {
[
"codex_plugin_disabled",
"codex_plugin_enabled",
"codex_plugin_used",
]
}
fn event_count(events: &[Value], event_type: &str) -> usize {
events
.iter()
.filter(|event| event["event_type"] == event_type)
.count()
}
fn validate_identity(event: &Value, expected: &ExpectedPlugin) -> Result<()> {
let params = &event["event_params"];
require_string(params, "plugin_id", &expected.plugin_id)?;
require_string(params, "remote_plugin_id", &expected.remote_plugin_id)?;
require_string(params, "plugin_name", &expected.plugin_name)?;
require_string(params, "marketplace_name", &expected.marketplace_name)
}
fn validate_used_metadata(event: &Value) -> Result<()> {
let params = &event["event_params"];
for field in [
"has_skills",
"mcp_server_count",
"connector_ids",
"mcp_server_names",
"thread_id",
"turn_id",
"model_slug",
] {
if params.get(field).is_none_or(Value::is_null) {
bail!("codex_plugin_used event has null or missing `{field}`");
}
}
require_string(params, "model_slug", MOCK_MODEL_SLUG)
}
fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> {
let actual = params.get(field).and_then(Value::as_str);
if actual != Some(expected) {
bail!("expected `{field}` to be `{expected}`, got {actual:?}");
}
Ok(())
}
struct TemporaryConfigFile {
path: PathBuf,
}
impl TemporaryConfigFile {
fn create() -> Result<Self> {
let path = std::env::temp_dir().join(format!(
"codex-plugin-analytics-config-{}.toml",
process::id()
));
fs::write(&path, "")
.with_context(|| format!("create temporary config file {}", path.display()))?;
Ok(Self { path })
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TemporaryConfigFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}

View File

@@ -0,0 +1,145 @@
use std::collections::HashMap;
use std::io;
use std::io::BufRead;
use std::io::IsTerminal;
use std::io::Write;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_app_server_protocol::ToolRequestUserInputAnswer;
use codex_app_server_protocol::ToolRequestUserInputParams;
use codex_app_server_protocol::ToolRequestUserInputResponse;
pub(super) fn prompt_for_answers(
params: &ToolRequestUserInputParams,
) -> Result<ToolRequestUserInputResponse> {
let stdin = io::stdin();
if !stdin.is_terminal() {
bail!("request_user_input requires an interactive stdin terminal");
}
let stdout = io::stdout();
prompt_for_answers_with(&mut stdin.lock(), &mut stdout.lock(), params)
}
fn prompt_for_answers_with(
input: &mut impl BufRead,
output: &mut impl Write,
params: &ToolRequestUserInputParams,
) -> Result<ToolRequestUserInputResponse> {
writeln!(
output,
"\n[request_user_input for thread {}, turn {}]",
params.thread_id, params.turn_id
)?;
if !params.is_blocking {
writeln!(output, "This request is non-blocking.")?;
}
let mut answers = HashMap::new();
for question in &params.questions {
writeln!(output, "\n{}: {}", question.header, question.question)?;
let options = question
.options
.as_deref()
.filter(|options| !options.is_empty());
let answer_values = if let Some(options) = options {
for (index, option) in options.iter().enumerate() {
writeln!(
output,
" {}. {} - {}",
index + 1,
option.label,
option.description
)?;
}
if question.is_other {
writeln!(output, " o. Other (free-form)")?;
}
loop {
if question.is_other {
write!(output, "Choose 1-{} or o: ", options.len())?;
} else {
write!(output, "Choose 1-{}: ", options.len())?;
}
output.flush()?;
let mut line = String::new();
if input
.read_line(&mut line)
.context("failed to read request_user_input selection")?
== 0
{
bail!("stdin closed while waiting for request_user_input selection");
}
let selection = line.trim();
if let Ok(index) = selection.parse::<usize>()
&& let Some(option) = index.checked_sub(1).and_then(|index| options.get(index))
{
break vec![option.label.clone()];
}
if let Some(option) = options
.iter()
.find(|option| option.label.eq_ignore_ascii_case(selection))
{
break vec![option.label.clone()];
}
if question.is_other && selection.eq_ignore_ascii_case("o") {
write!(output, "Other: ")?;
output.flush()?;
line.clear();
if input
.read_line(&mut line)
.context("failed to read request_user_input free-form answer")?
== 0
{
bail!("stdin closed while waiting for request_user_input free-form answer");
}
let answer = line.trim();
if !answer.is_empty() {
break vec![format!("user_note: {answer}")];
}
}
writeln!(output, "Invalid selection; try again.")?;
}
} else {
loop {
write!(output, "Answer: ")?;
output.flush()?;
let mut line = String::new();
if input
.read_line(&mut line)
.context("failed to read request_user_input answer")?
== 0
{
bail!("stdin closed while waiting for request_user_input answer");
}
let answer = line.trim();
if !answer.is_empty() {
break vec![format!("user_note: {answer}")];
}
writeln!(output, "Answer cannot be empty; try again.")?;
}
};
answers.insert(
question.id.clone(),
ToolRequestUserInputAnswer {
answers: answer_values,
},
);
}
Ok(ToolRequestUserInputResponse { answers })
}
#[cfg(test)]
#[path = "request_user_input_tests.rs"]
mod tests;

View File

@@ -0,0 +1,127 @@
use std::collections::HashMap;
use std::io::Cursor;
use codex_app_server_protocol::ToolRequestUserInputAnswer;
use codex_app_server_protocol::ToolRequestUserInputOption;
use codex_app_server_protocol::ToolRequestUserInputParams;
use codex_app_server_protocol::ToolRequestUserInputQuestion;
use codex_app_server_protocol::ToolRequestUserInputResponse;
use pretty_assertions::assert_eq;
use super::prompt_for_answers_with;
#[test]
fn collects_option_and_free_form_answers() {
let params = ToolRequestUserInputParams {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
item_id: "item-1".to_string(),
questions: vec![
ToolRequestUserInputQuestion {
id: "target".to_string(),
header: "Target".to_string(),
question: "Which target?".to_string(),
is_other: true,
is_secret: false,
options: Some(vec![
ToolRequestUserInputOption {
label: "Core".to_string(),
description: "Inspect core".to_string(),
},
ToolRequestUserInputOption {
label: "TUI".to_string(),
description: "Inspect TUI".to_string(),
},
]),
},
ToolRequestUserInputQuestion {
id: "details".to_string(),
header: "Details".to_string(),
question: "Anything else?".to_string(),
is_other: true,
is_secret: false,
options: None,
},
],
is_blocking: false,
auto_resolution_ms: Some(60_000),
};
let mut input = Cursor::new(b"2\ninclude snapshots\n");
let mut output = Vec::new();
let response = prompt_for_answers_with(&mut input, &mut output, &params).unwrap();
assert_eq!(
response,
ToolRequestUserInputResponse {
answers: HashMap::from([
(
"target".to_string(),
ToolRequestUserInputAnswer {
answers: vec!["TUI".to_string()],
},
),
(
"details".to_string(),
ToolRequestUserInputAnswer {
answers: vec!["user_note: include snapshots".to_string()],
},
),
]),
}
);
assert_eq!(
String::from_utf8(output).unwrap(),
concat!(
"\n[request_user_input for thread thread-1, turn turn-1]\n",
"This request is non-blocking.\n",
"\nTarget: Which target?\n",
" 1. Core - Inspect core\n",
" 2. TUI - Inspect TUI\n",
" o. Other (free-form)\n",
"Choose 1-2 or o: ",
"\nDetails: Anything else?\n",
"Answer: ",
)
);
}
#[test]
fn retries_invalid_selection_and_collects_other_answer() {
let params = ToolRequestUserInputParams {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
item_id: "item-1".to_string(),
questions: vec![ToolRequestUserInputQuestion {
id: "target".to_string(),
header: "Target".to_string(),
question: "Which target?".to_string(),
is_other: true,
is_secret: false,
options: Some(vec![ToolRequestUserInputOption {
label: "Core".to_string(),
description: "Inspect core".to_string(),
}]),
}],
is_blocking: true,
auto_resolution_ms: None,
};
let mut input = Cursor::new(b"9\no\nSDK wrapper\n");
let mut output = Vec::new();
let response = prompt_for_answers_with(&mut input, &mut output, &params).unwrap();
assert_eq!(
response,
ToolRequestUserInputResponse {
answers: HashMap::from([(
"target".to_string(),
ToolRequestUserInputAnswer {
answers: vec!["user_note: SDK wrapper".to_string()],
},
)]),
}
);
let output = String::from_utf8(output).unwrap();
assert!(output.contains("Invalid selection; try again."));
}