Record daemon startup and update telemetry with consent handling (#46126)

## Why

TUI startup metrics report the selected app-server mode before a connection succeeds, which can misrepresent embedded fallback or failed startup. Daemon startup and update actions also need distinct outcome observations.

## What changed

- Record `codex.tui.start` once after the first connection attempt, using the actual mode or `unconfirmed`, and include daemon selection and auto-start tags.
- Add `codex.daemon.start` for TUI auto-start and `codex.daemon.update` for foreground CLI updates and TUI update handoffs, using existing analytics consent and identity handling.
- Report TUI handoffs as `handoff_requested` and suppress duplicate child reporting. Remove the suppression flag when spawning long-lived daemon processes.
- Tag daemon settings by enabled state and explicit presence, without exporting setting values or contents; report invalid or unreadable settings as `unknown`.

## Testing

Add coverage for analytics defaults and explicit consent overrides, unconfirmed CLI updates, settings presence, and exactly-once launch observations. Extend the worktree TUI test to check startup tags and a single update handoff observation.

GitOrigin-RevId: 176d2ee594f930033fa1ece55d4c1c9603dbbc16
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-17 05:26:45 +00:00
1 parent 1bd1bfa7ca
commit b0659c5386
13 files changed
+454 -33

No files matched your search

+19
View File
@@ -5,6 +5,25 @@ use crate::legacy_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn daemon_launch_telemetry_records_once_on_connection_or_early_return() {
for connected in [false, true] {
let observations = std::cell::RefCell::new(Vec::new());
let launch = daemon_telemetry::Launch(Some(|target: &AppServerTarget, actual: bool| {
observations.borrow_mut().push((target.clone(), actual));
}));
if connected {
launch.record(&AppServerTarget::Embedded, connected);
} else {
drop(launch);
}
assert_eq!(
observations.into_inner(),
vec![(AppServerTarget::Embedded, connected)]
);
}
}
#[cfg(windows)]
#[tokio::test]
async fn daemon_connection_rejects_unprotected_socket_before_handshake() -> color_eyre::Result<()> {
+65
View File
@@ -0,0 +1,65 @@
//! Records automatic daemon startup and ensures launch observations survive setup failures.
use super::*;
/// Emit once after connection, or as unconfirmed if startup returns early.
pub(super) struct Launch<F: FnOnce(&AppServerTarget, bool)>(pub(super) Option<F>);
impl<F: FnOnce(&AppServerTarget, bool)> Launch<F> {
pub(super) fn record(mut self, target: &AppServerTarget, connected: bool) {
if let Some(record) = self.0.take() {
record(target, connected);
}
}
}
impl<F: FnOnce(&AppServerTarget, bool)> Drop for Launch<F> {
fn drop(&mut self) {
if let Some(record) = self.0.take() {
record(&AppServerTarget::Embedded, /*connected*/ false);
}
}
}
pub(super) async fn record_start(
config: &Config,
result: &anyhow::Result<codex_app_server_daemon::LifecycleOutput>,
) {
use codex_app_server_daemon::LifecycleStatus;
let outcome = match result {
Ok(output) => match output.status {
LifecycleStatus::Started => "started",
LifecycleStatus::AlreadyRunning => "already_running",
LifecycleStatus::Restarted => "restarted",
LifecycleStatus::Stopped | LifecycleStatus::NotRunning | LifecycleStatus::Running => {
"unconfirmed"
}
},
Err(_) => "failed",
};
// Failure can happen before normal TUI telemetry is initialized. This short-lived
// provider uses exactly the same consent and identity construction as TUI startup.
let Ok(Ok(Some(otel))) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
codex_app_server_client::build_otel_provider(
config,
env!("CARGO_PKG_VERSION"),
/*service_name_override*/ None,
/*default_analytics_enabled*/ true,
)
})) else {
return;
};
if let Some(metrics) = otel.metrics() {
let mut tags = codex_app_server_daemon::telemetry::settings_tags(&config.codex_home)
.await
.to_vec();
tags.extend([
("initiation_source", "tui_auto_start"),
("outcome", outcome),
]);
let _ = metrics.counter("codex.daemon.start", /*inc*/ 1, &tags);
}
let _ = otel
.shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT)
.await;
}
+3
View File
@@ -1061,6 +1061,7 @@ async fn run_ratatui_app(
environment_manager: Arc<EnvironmentManager>,
managed_worktree: Option<ManagedTuiWorktree>,
daemon_startup_warning: Option<String>,
launch_telemetry: daemon_telemetry::Launch<impl FnOnce(&AppServerTarget, bool)>,
startup_draft: startup_draft::StartupDraft,
) -> color_eyre::Result<AppExitInfo> {
let uses_remote_workspace = app_server_target.uses_remote_workspace();
@@ -1126,6 +1127,7 @@ async fn run_ratatui_app(
),
)
.await;
launch_telemetry.record(&app_server_target, matches!(&startup_app_server, Ok(Ok(_))));
let app_server_session = match startup_app_server {
Ok(Ok(app_server)) => {
AppServerSession::new(app_server, app_server_target.thread_params_mode())
@@ -2185,6 +2187,7 @@ fn should_show_bedrock_setup_wizard(
}
mod daemon_startup;
mod daemon_telemetry;
#[cfg(test)]
#[path = "daemon_startup_tests.rs"]
+93 -24
View File
@@ -418,11 +418,13 @@ pub(super) async fn run_main_inner(
.with_restored(|| async {
// Package installation may print progress; keep ordinary Ctrl+C handling.
crossterm::terminal::disable_raw_mode()?;
codex_app_server_daemon::run(codex_app_server_daemon::LifecycleCommand::Start)
.await
.map_err(|err| {
std::io::Error::other(format!("{err:#}\n{}", daemon_startup::FAILURE_HINT))
})
let result =
codex_app_server_daemon::run(codex_app_server_daemon::LifecycleCommand::Start)
.await;
daemon_telemetry::record_start(&config, &result).await;
result.map_err(|err| {
std::io::Error::other(format!("{err:#}\n{}", daemon_startup::FAILURE_HINT))
})
})
.await?;
app_server_target = AppServerTarget::LocalDaemon {
@@ -517,13 +519,52 @@ pub(super) async fn run_main_inner(
None
}
};
if let Some(metrics) = otel.as_ref().and_then(codex_otel::OtelProvider::metrics) {
let metrics = otel
.as_ref()
.and_then(codex_otel::OtelProvider::metrics)
.cloned();
if let Some(metrics) = &metrics {
let _ = codex_otel::record_process_start_once(metrics, otel_originator.as_str());
// Count the selected mode once per TUI launch, independently of reconnects.
let app_server_mode = match &app_server_target {
AppServerTarget::Embedded => "in_process",
AppServerTarget::LocalDaemon { .. } => "local_daemon",
AppServerTarget::Remote { .. } => "remote",
let telemetry =
codex_rollout::sqlite_telemetry_recorder(metrics.clone(), otel_originator.as_str());
let _ = codex_state::install_process_db_telemetry(telemetry);
}
let selection_reason = match (&app_server_target, daemon_exclusion) {
(AppServerTarget::Remote { .. }, _) => "explicit_remote",
_ if cli.agents_overview => "agents",
(_, Some("--no-daemon")) => "explicit_no_daemon",
(_, Some(_)) => "incompatible_option",
_ if auto_start_daemon => "auto_start",
(AppServerTarget::LocalDaemon { .. }, _) => "existing_daemon",
(AppServerTarget::Embedded, None) => "auto_start_disabled",
};
let daemon_settings = if metrics.is_some() {
codex_app_server_daemon::telemetry::settings_tags(&config.codex_home)
.await
.to_vec()
} else {
Vec::new()
};
let mut launch_tags = daemon_settings.to_vec();
launch_tags.extend([
("daemon_selection_reason", selection_reason),
(
"daemon_auto_start",
if config.features.enabled(Feature::DaemonAutoStart) {
"enabled"
} else {
"disabled"
},
),
]);
// Record the first connection attempt's actual mode, including embedded fallback; never reconnects.
let launch_telemetry = move |target: &AppServerTarget, connected: bool| {
let Some(metrics) = metrics else { return };
let app_server_mode = match (connected, target) {
(false, _) => "unconfirmed",
(true, AppServerTarget::Embedded) => "in_process",
(true, AppServerTarget::LocalDaemon { .. }) => "local_daemon",
(true, AppServerTarget::Remote { .. }) => "remote",
};
// Use a fixed category, not the versioned or user-provided terminal identifier.
let terminal_info = codex_terminal_detection::terminal_info();
@@ -548,19 +589,14 @@ pub(super) async fn run_main_inner(
Some(Multiplexer::Zellij { .. }) => "zellij",
None => "none",
};
let _ = metrics.counter(
"codex.tui.start",
/*inc*/ 1,
&[
("app_server_mode", app_server_mode),
("terminal_name", terminal_name),
("multiplexer", multiplexer),
],
);
let telemetry =
codex_rollout::sqlite_telemetry_recorder(metrics.clone(), otel_originator.as_str());
let _ = codex_state::install_process_db_telemetry(telemetry);
}
launch_tags.extend([
("app_server_mode", app_server_mode),
("terminal_name", terminal_name),
("multiplexer", multiplexer),
]);
let _ = metrics.counter("codex.tui.start", /*inc*/ 1, &launch_tags);
};
let launch_telemetry = daemon_telemetry::Launch(Some(launch_telemetry));
let state_db = startup_draft
.run_until(init_state_db_for_app_server_target(
&config,
@@ -592,6 +628,12 @@ pub(super) async fn run_main_inner(
if let Some(worktree) = managed_worktree.as_ref() {
worktree.report_startup_failure();
}
launch_telemetry.record(&app_server_target, /*connected*/ false);
if let Some(otel) = otel {
let _ = otel
.shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT)
.await;
}
std::process::exit(1);
}
}
@@ -607,6 +649,12 @@ pub(super) async fn run_main_inner(
if let Some(worktree) = managed_worktree.as_ref() {
worktree.report_startup_failure();
}
launch_telemetry.record(&app_server_target, /*connected*/ false);
if let Some(otel) = otel {
let _ = otel
.shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT)
.await;
}
std::process::exit(1);
}
}
@@ -715,6 +763,7 @@ pub(super) async fn run_main_inner(
environment_manager,
managed_worktree.clone(),
daemon_startup_warning,
launch_telemetry,
startup_draft,
)
.await
@@ -727,6 +776,26 @@ pub(super) async fn run_main_inner(
worktree.report_startup_failure();
}
// The TUI owns this request's consent. The child is silent; installation remains unconfirmed.
if let Ok(exit) = &app_result
&& let Some(UpdateAction::Daemon(source)) = exit.update_action
&& let Some(metrics) = otel.as_ref().and_then(codex_otel::OtelProvider::metrics)
{
let mut tags = daemon_settings.to_vec();
tags.extend([
("initiation_source", "tui_handoff"),
(
"update_target",
match source {
DaemonUpdateSource::PublicStable => "public_stable",
DaemonUpdateSource::ThisCli => "this_cli",
},
),
("outcome", "handoff_requested"),
]);
let _ = metrics.counter("codex.daemon.update", /*inc*/ 1, &tags);
}
if let Some(otel) = otel
&& let Err(err) = otel
.shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT)