aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -68,19 +68,12 @@ use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_core::config::Config;
|
||||
use codex_otel::OtelProvider;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
use codex_protocol::dynamic_tools::normalize_dynamic_tool_specs;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use tracing::info_span;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
use tungstenite::Message;
|
||||
use tungstenite::WebSocket;
|
||||
use tungstenite::connect;
|
||||
@@ -88,10 +81,6 @@ use tungstenite::stream::MaybeTlsStream;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
mod loopback_responses_server;
|
||||
mod plugin_analytics_capture;
|
||||
mod plugin_analytics_mutation_smoke;
|
||||
mod plugin_analytics_smoke;
|
||||
mod request_user_input;
|
||||
|
||||
const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[
|
||||
@@ -105,10 +94,6 @@ const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[
|
||||
];
|
||||
const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const APP_SERVER_GRACEFUL_SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
const DEFAULT_ANALYTICS_ENABLED: bool = true;
|
||||
const OTEL_SERVICE_NAME: &str = "codex-app-server-test-client";
|
||||
const TRACE_DISABLED_MESSAGE: &str =
|
||||
"Not enabled - enable tracing in $CODEX_HOME/config.toml to get a trace URL!";
|
||||
|
||||
/// Minimal launcher that initializes the Codex app-server and logs the handshake.
|
||||
#[derive(Parser)]
|
||||
@@ -278,39 +263,6 @@ enum CliCommand {
|
||||
#[arg(long, default_value_t = 15)]
|
||||
hold_seconds: u64,
|
||||
},
|
||||
/// Exercise remote plugin analytics through production app-server RPC paths.
|
||||
#[command(name = "plugin-analytics-smoke")]
|
||||
PluginAnalyticsSmoke {
|
||||
/// Installed local plugin id, such as `linear@openai-curated-remote`.
|
||||
#[arg(long)]
|
||||
plugin_id: String,
|
||||
/// JSONL output path. Defaults to a PID-specific file under the system temp directory.
|
||||
#[arg(long)]
|
||||
capture_file: Option<PathBuf>,
|
||||
},
|
||||
/// Install and uninstall one remote plugin while validating analytics capture.
|
||||
#[command(name = "plugin-analytics-mutation-smoke")]
|
||||
PluginAnalyticsMutationSmoke {
|
||||
/// Backend remote plugin id. The plugin must be initially uninstalled.
|
||||
#[arg(long)]
|
||||
remote_plugin_id: String,
|
||||
/// Acknowledge that this command mutates the active account's plugin state.
|
||||
#[arg(long)]
|
||||
confirm_account_mutation: bool,
|
||||
/// JSONL output path. Defaults to a PID-specific file under the system temp directory.
|
||||
#[arg(long)]
|
||||
capture_file: Option<PathBuf>,
|
||||
},
|
||||
/// Best-effort recovery command that uninstalls one remote plugin.
|
||||
#[command(name = "plugin-remote-uninstall")]
|
||||
PluginRemoteUninstall {
|
||||
/// Backend remote plugin id to uninstall.
|
||||
#[arg(long)]
|
||||
remote_plugin_id: String,
|
||||
/// Acknowledge that this command mutates the active account's plugin state.
|
||||
#[arg(long)]
|
||||
confirm_account_mutation: bool,
|
||||
},
|
||||
}
|
||||
|
||||
enum TestLoginMode {
|
||||
@@ -471,58 +423,6 @@ pub async fn run() -> Result<()> {
|
||||
hold_seconds,
|
||||
)
|
||||
}
|
||||
CliCommand::PluginAnalyticsSmoke {
|
||||
plugin_id,
|
||||
capture_file,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-smoke")?;
|
||||
if url.is_some() {
|
||||
bail!("plugin-analytics-smoke requires --codex-bin and does not support --url");
|
||||
}
|
||||
let codex_bin = codex_bin.context("plugin-analytics-smoke requires --codex-bin")?;
|
||||
plugin_analytics_smoke::run(&codex_bin, &config_overrides, &plugin_id, capture_file)
|
||||
}
|
||||
CliCommand::PluginAnalyticsMutationSmoke {
|
||||
remote_plugin_id,
|
||||
confirm_account_mutation,
|
||||
capture_file,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-mutation-smoke")?;
|
||||
if url.is_some() {
|
||||
bail!(
|
||||
"plugin-analytics-mutation-smoke requires --codex-bin and does not support --url"
|
||||
);
|
||||
}
|
||||
let codex_bin =
|
||||
codex_bin.context("plugin-analytics-mutation-smoke requires --codex-bin")?;
|
||||
plugin_analytics_mutation_smoke::run(
|
||||
&codex_bin,
|
||||
&config_overrides,
|
||||
&remote_plugin_id,
|
||||
plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag(
|
||||
confirm_account_mutation,
|
||||
),
|
||||
capture_file,
|
||||
)
|
||||
}
|
||||
CliCommand::PluginRemoteUninstall {
|
||||
remote_plugin_id,
|
||||
confirm_account_mutation,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-remote-uninstall")?;
|
||||
if url.is_some() {
|
||||
bail!("plugin-remote-uninstall requires --codex-bin and does not support --url");
|
||||
}
|
||||
let codex_bin = codex_bin.context("plugin-remote-uninstall requires --codex-bin")?;
|
||||
plugin_analytics_mutation_smoke::run_cleanup(
|
||||
&codex_bin,
|
||||
&config_overrides,
|
||||
&remote_plugin_id,
|
||||
plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag(
|
||||
confirm_account_mutation,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1199,20 +1099,16 @@ async fn with_client<T>(
|
||||
config_overrides: &[String],
|
||||
f: impl FnOnce(&mut CodexClient) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let tracing = TestClientTracing::initialize(config_overrides).await?;
|
||||
let command_span = info_span!(
|
||||
"app_server_test_client.command",
|
||||
otel.kind = "client",
|
||||
otel.name = command_name,
|
||||
app_server_test_client.command = command_name,
|
||||
);
|
||||
let trace_summary = command_span.in_scope(|| TraceSummary::capture(tracing.traces_enabled));
|
||||
let result = command_span.in_scope(|| {
|
||||
command_span.in_scope(|| {
|
||||
let mut client = CodexClient::connect(endpoint, config_overrides)?;
|
||||
f(&mut client)
|
||||
});
|
||||
print_trace_summary(&trace_summary);
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_increment_elicitation(url: &str, thread_id: String) -> Result<()> {
|
||||
@@ -1917,7 +1813,7 @@ impl CodexClient {
|
||||
let request_value = serde_json::to_value(request)?;
|
||||
let mut request: JSONRPCRequest = serde_json::from_value(request_value)
|
||||
.context("client request was not a valid JSON-RPC request")?;
|
||||
request.trace = current_span_w3c_trace_context();
|
||||
request.trace = codex_otel::current_span_w3c_trace_context();
|
||||
let request_json = serde_json::to_string(&request)?;
|
||||
let mut request_for_logging = serde_json::to_value(&request)?;
|
||||
if request.method == "account/login/start"
|
||||
@@ -2205,85 +2101,6 @@ fn print_multiline_with_prefix(prefix: &str, payload: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
struct TestClientTracing {
|
||||
_otel_provider: Option<OtelProvider>,
|
||||
traces_enabled: bool,
|
||||
}
|
||||
|
||||
impl TestClientTracing {
|
||||
async fn initialize(config_overrides: &[String]) -> Result<Self> {
|
||||
let cli_kv_overrides = CliConfigOverrides {
|
||||
raw_overrides: config_overrides.to_vec(),
|
||||
}
|
||||
.parse_overrides()
|
||||
.map_err(|e| anyhow::anyhow!("error parsing -c overrides: {e}"))?;
|
||||
let config = Config::load_with_cli_overrides(cli_kv_overrides)
|
||||
.await
|
||||
.context("error loading config")?;
|
||||
let otel_provider = codex_core::otel_init::build_provider(
|
||||
&config,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Some(OTEL_SERVICE_NAME),
|
||||
DEFAULT_ANALYTICS_ENABLED,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("error loading otel config: {e}"))?;
|
||||
let traces_enabled = otel_provider
|
||||
.as_ref()
|
||||
.and_then(|provider| provider.tracer_provider.as_ref())
|
||||
.is_some();
|
||||
if let Some(provider) = otel_provider.as_ref()
|
||||
&& traces_enabled
|
||||
{
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(provider.tracing_layer())
|
||||
.try_init();
|
||||
}
|
||||
Ok(Self {
|
||||
traces_enabled,
|
||||
_otel_provider: otel_provider,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum TraceSummary {
|
||||
Enabled { url: String },
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl TraceSummary {
|
||||
fn capture(traces_enabled: bool) -> Self {
|
||||
if !traces_enabled {
|
||||
return Self::Disabled;
|
||||
}
|
||||
current_span_w3c_trace_context()
|
||||
.as_ref()
|
||||
.and_then(trace_url_from_context)
|
||||
.map_or(Self::Disabled, |url| Self::Enabled { url })
|
||||
}
|
||||
}
|
||||
|
||||
fn trace_url_from_context(trace: &W3cTraceContext) -> Option<String> {
|
||||
let traceparent = trace.traceparent.as_deref()?;
|
||||
let mut parts = traceparent.split('-');
|
||||
match (parts.next(), parts.next(), parts.next(), parts.next()) {
|
||||
(Some(_version), Some(trace_id), Some(_span_id), Some(_trace_flags))
|
||||
if trace_id.len() == 32 =>
|
||||
{
|
||||
Some(format!("go/trace/{trace_id}"))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn print_trace_summary(trace_summary: &TraceSummary) {
|
||||
println!("\n[Datadog trace]");
|
||||
match trace_summary {
|
||||
TraceSummary::Enabled { url } => println!("{url}\n"),
|
||||
TraceSummary::Disabled => println!("{TRACE_DISABLED_MESSAGE}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CodexClient {
|
||||
fn drop(&mut self) {
|
||||
let ClientTransport::Stdio { child, stdin, .. } = &mut self.transport else {
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::thread;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) struct LoopbackResponsesServer {
|
||||
base_url: String,
|
||||
shutdown: Arc<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()
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn read_events_for_remote_plugin(
|
||||
path: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<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;
|
||||
@@ -1,97 +0,0 @@
|
||||
use super::PluginEventIdentity;
|
||||
use super::read_events_for_remote_plugin;
|
||||
use super::validate_mutation_events;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::time::SystemTime;
|
||||
|
||||
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_test";
|
||||
|
||||
#[test]
|
||||
fn reads_and_validates_remote_plugin_mutation_events() {
|
||||
let path = unique_capture_path("valid");
|
||||
let installed = mutation_event("codex_plugin_installed");
|
||||
let uninstalled = mutation_event("codex_plugin_uninstalled");
|
||||
let unrelated = json!({
|
||||
"event_type": "codex_plugin_installed",
|
||||
"event_params": {
|
||||
"plugin_id": "other@openai-curated-remote",
|
||||
"remote_plugin_id": "plugins~Plugin_other"
|
||||
}
|
||||
});
|
||||
let contents = [
|
||||
json!({"events": [unrelated]}),
|
||||
json!({"events": [installed, uninstalled]}),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|payload| serde_json::to_string(&payload).expect("serialize capture payload"))
|
||||
.collect::<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()
|
||||
))
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
use super::CodexClient;
|
||||
use super::plugin_analytics_capture::PluginEventIdentity;
|
||||
use super::plugin_analytics_capture::read_events_for_remote_plugin;
|
||||
use super::plugin_analytics_capture::validate_mutation_events;
|
||||
use super::plugin_analytics_smoke::ANALYTICS_CAPTURE_ENV_VAR;
|
||||
use super::plugin_analytics_smoke::prepare_capture_file;
|
||||
use super::plugin_analytics_smoke::wait_until_capture_is_ready;
|
||||
use super::shell_quote;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallParams;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
use codex_app_server_protocol::PluginReadParams;
|
||||
use codex_app_server_protocol::PluginReadResponse;
|
||||
use codex_app_server_protocol::PluginUninstallParams;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use serde_json::Value;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
const REMOTE_MARKETPLACE_HINT: &str = "openai-curated-remote";
|
||||
const STATE_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(super) fn run(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
remote_plugin_id: &str,
|
||||
confirmation: AccountMutationConfirmation,
|
||||
capture_file: Option<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}");
|
||||
}
|
||||
@@ -1,504 +0,0 @@
|
||||
use super::CodexClient;
|
||||
use super::loopback_responses_server::LoopbackResponsesServer;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ConfigValueWriteParams;
|
||||
use codex_app_server_protocol::ConfigWriteResponse;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstalledParams;
|
||||
use codex_app_server_protocol::PluginInstalledResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_app_server_protocol::WriteStatus;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
pub(super) const ANALYTICS_CAPTURE_ENV_VAR: &str = "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE";
|
||||
const TEST_USER_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE";
|
||||
const CAPTURE_READY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CAPTURE_POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
const PLUGIN_READY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const PLUGIN_READY_RETRY_INTERVAL: Duration = Duration::from_millis(250);
|
||||
const MOCK_MODEL_SLUG: &str = "plugin-analytics-smoke";
|
||||
const MOCK_PROVIDER_ID: &str = "plugin_analytics_smoke";
|
||||
|
||||
pub(super) fn run(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
plugin_id: &str,
|
||||
capture_file: Option<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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user