feat(cli): add codex doctor diagnostics (#22336)

## Why

Users and support need a single command that captures the local Codex
runtime, configuration, auth, terminal, network, and state shape without
asking the user to know which diagnostic depth to choose first. `codex
doctor` now runs the useful checks by default and makes the detailed
human output the default because the command is usually run when someone
already needs context.

The command also targets concrete support failure modes we have seen
while iterating on the design:

- update-target mismatches like #21956, where the installed package
manager target can differ from the running executable
- terminal and multiplexer issues that depend on `TERM`, tmux/zellij
state, color handling, and TTY metadata
- provider-specific HTTP/WebSocket connectivity, including ChatGPT
WebSocket handshakes and API-key/provider endpoint reachability
- local state/log SQLite integrity problems and large rollout
directories
- feedback reports that need an attached, redacted diagnostic snapshot
without asking the user to run a second command

## What Changed

- Adds `codex doctor` as a grouped CLI diagnostic report with default
detailed output and `--summary` for the compact view.
- Adds stable report sections for Environment, Configuration, Updates,
Connectivity, and Background Server, plus a top Notes block that
promotes anomalies such as available updates, large rollout directories,
optional MCP issues, and mixed auth signals.
- Adds runtime provenance, install consistency, bundled/system search
readiness, terminal/multiplexer metadata, `config.toml` parse status,
auth mode details, sandbox details, feature flag summaries, update
cache/latest-version state, app-server daemon state, SQLite integrity
checks, rollout statistics, and provider-aware network diagnostics.
- Adds ChatGPT WebSocket diagnostics that report the negotiated HTTP
upgrade as `HTTP 101 Switching Protocols` and include timeout, DNS,
auth, and provider context in detailed output.
- Makes reachability provider-aware: API-key OpenAI setups check the API
endpoint, ChatGPT auth checks the ChatGPT path, and custom/AWS/local
providers check configured HTTP endpoints when available.
- Adds structured, redacted JSON output where `checks` is keyed by check
id and `details` is a key/value object for support tooling.
- Integrates doctor with feedback uploads by attaching a best-effort
`codex-doctor-report.json` report and adding derived Sentry tags for
overall status and failing/warning checks.
- Updates the TUI feedback consent copy so users can see that the doctor
report is included when logs/diagnostics are uploaded.
- Updates the CLI bug issue template to ask reporters for `codex doctor
--json` and render pasted reports as JSON.

## Example Output

The examples below are sanitized from local smoke runs with `--no-color`
so the structure is reviewable in plain text.

### `codex doctor`

```text
Codex Doctor v0.0.0 · macos-aarch64

Notes
   ↑ updates      0.130.0 available (current 0.0.0, dismissed 0.128.0)
   ⚠ rollouts     1,526 active files · 2.53 GB on disk
   ⚠ mcp          MCP configuration has optional issues
   ⚠ auth         mixed auth signals: ChatGPT login plus API key env var; HTTP reachability uses API-key mode
─────────────────────────────────────────────────────────────

Environment
  ✓ runtime      local debug build
      version                  0.0.0
      install method           other
      commit                   unknown
      executable               ~/code/codex.fcoury-doct…x-rs/target/debug/codex
  ✓ install      consistent
      context                  other
      managed by               npm: no · bun: no · package root —
      PATH entries (2)         ~/.local/share/mise/installs/node/24/bin/codex
                               ~/.local/share/mise/shims/codex
  ✓ search       ripgrep 15.1.0 (system, `rg`)
  ✓ terminal     Ghostty 1.3.2-main-+b0f827665 · tmux 3.6a · TERM=xterm-256color
      terminal                 Ghostty
      TERM_PROGRAM             ghostty
      terminal version         1.3.2-main-+b0f827665
      TERM                     xterm-256color
      multiplexer              tmux 3.6a
      tmux extended-keys       on
      tmux allow-passthrough   on
      tmux set-clipboard       on
  ✓ state        databases healthy
      CODEX_HOME               ~/.codex (dir)
      state DB                 ~/.codex/state_5.sqlite (file) · integrity ok
      log DB                   ~/.codex/logs_2.sqlite (file) · integrity ok
      active rollouts          1,526 files · 2.53 GB (avg 1.70 MB)
      archived rollouts        8 files · 3.84 MB (avg 491.11 KB)

Configuration
  ✓ config       loaded
      model                    gpt-5.5 · openai
      cwd                      ~/code/codex.fcoury-doctor/codex-rs
      config.toml              ~/.codex/config.toml
      config.toml parse        ok
      MCP servers              1
      feature flags            36 enabled · 7 overridden (full list with --all)
      overrides                code_mode, code_mode_only, memories, chronicle, goals, remote_control, prevent_idle_sleep
  ✓ auth         auth is configured
      auth storage mode        File
      auth file                ~/.codex/auth.json
      auth env vars present    OPENAI_API_KEY
      stored auth mode         chatgpt
      stored API key           false
      stored ChatGPT tokens    true
      stored agent identity    false
  ⚠ mcp          MCP configuration has optional issues — Set the missing MCP env vars or disable the affected server.
      configured servers       1
      disabled servers         0
      streamable_http servers  1
      optional reachability    openaiDeveloperDocs: https://developers.openai.com/mcp (HEAD connect failed; GET connect failed)
  ✓ sandbox      restricted fs + restricted network · approval OnRequest
      approval policy          OnRequest
      filesystem sandbox       restricted
      network sandbox          restricted

Connectivity
  ✓ network      network-related environment looks readable
  ✓ websocket    connected (HTTP 101 Switching Protocols) · 15s timeout
      model provider           openai
      provider name            OpenAI
      wire API                 responses
      supports websockets      true
      connect timeout          15000 ms
      auth mode                chatgpt
      endpoint                 wss://chatgpt.com/backend-api/<redacted>
      DNS                      2 IPv4, 2 IPv6, first IPv6
      handshake result         HTTP 101 Switching Protocols
  ✗ reachability one or more required provider endpoints are unreachable over HTTP — Check proxy, VPN, firewall, DNS, and custom CA configuration.
      reachability mode        API key auth
      openai API               https://api.openai.com/v1 connect failed (required)

Background Server
  ○ app-server   not running (ephemeral mode)

─────────────────────────────────────────────────────────────
11 ok · 1 idle · 4 notes · 1 warn · 1 fail failed

--summary compact output           --all expand truncated lists
--json redacted report
```

### `codex doctor --summary`

```text
Codex Doctor v0.0.0 · macos-aarch64

Notes
   ↑ updates      0.130.0 available (current 0.0.0, dismissed 0.128.0)
   ⚠ rollouts     1,526 active files · 2.53 GB on disk
   ⚠ mcp          MCP configuration has optional issues
   ⚠ auth         mixed auth signals: ChatGPT login plus API key env var; HTTP reachability uses API-key mode
─────────────────────────────────────────────────────────────

Environment
  ✓ runtime      local debug build
  ✓ install      consistent
  ✓ search       ripgrep 15.1.0 (system, `rg`)
  ✓ terminal     Ghostty 1.3.2-main-+b0f827665 · tmux 3.6a · TERM=xterm-256color
  ✓ state        databases healthy

Configuration
  ✓ config       loaded
  ✓ auth         auth is configured
  ⚠ mcp          MCP configuration has optional issues — Set the missing MCP env vars or disable the affected server.
  ✓ sandbox      restricted fs + restricted network · approval OnRequest

Updates
  ✓ updates      update configuration is locally consistent

Connectivity
  ✓ network      network-related environment looks readable
  ✓ websocket    connected (HTTP 101 Switching Protocols) · 15s timeout
  ✗ reachability one or more required provider endpoints are unreachable over HTTP — Check proxy, VPN, firewall, DNS, and custom CA configuration.

Background Server
  ○ app-server   not running (ephemeral mode)

─────────────────────────────────────────────────────────────
11 ok · 1 idle · 4 notes · 1 warn · 1 fail failed

Run codex doctor without --summary for detailed diagnostics.
--all expand truncated lists       --json redacted report
```

### `codex doctor --json` shape

```json
{
  "schema_version": 1,
  "overall_status": "fail",
  "checks": {
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "Environment",
      "status": "ok",
      "summary": "local debug build",
      "details": {
        "version": "0.0.0",
        "install method": "other",
        "commit": "unknown"
      }
    },
    "sandbox.helpers": {
      "id": "sandbox.helpers",
      "category": "Configuration",
      "status": "ok",
      "summary": "restricted fs + restricted network · approval OnRequest",
      "details": {
        "approval policy": "OnRequest",
        "filesystem sandbox": "restricted",
        "network sandbox": "restricted"
      }
    }
  }
}
```

### `/feedback` new sentry attachment

<img width="938" height="798" alt="CleanShot 2026-05-13 at 15 36 14"
src="https://github.com/user-attachments/assets/715e62e0-d7b4-4fea-a35a-fd5d5d33c4c0"
/>

### New section in CLI issue template

<img width="1164" height="435" alt="CleanShot 2026-05-13 at 15 47 24"
src="https://github.com/user-attachments/assets/9081dc25-a28c-4afa-8ba1-e299c2b4031d"
/>

## How to Test

1. Run `cargo run --bin codex -- doctor --no-color`.
2. Confirm the detailed report is the default and includes promoted
Notes, grouped sections, terminal details, state DB integrity, rollout
stats, provider reachability, WebSocket diagnostics, and app-server
status.
3. Run `cargo run --bin codex -- doctor --summary --no-color`.
4. Confirm the compact view keeps the same sections and summary counts
but omits detailed key/value rows.
5. Run `cargo run --bin codex -- doctor --json`.
6. Confirm the output is redacted JSON, `checks` is an object keyed by
check id, and each check's `details` is a key/value object.
7. Preview the CLI bug issue template and confirm the `Codex doctor
report` field appears after the terminal field, asks for `codex doctor
--json`, and renders pasted output as JSON.
8. Start a feedback flow that includes logs.
9. Confirm the upload consent copy lists `codex-doctor-report.json`
alongside the log attachments.

Targeted tests:

- `cargo test -p codex-cli doctor`
- `cargo test -p codex-app-server
doctor_report_tags_summarize_status_counts`
- `cargo test -p codex-feedback`
- `cargo test -p codex-tui feedback_view`
- `just argument-comment-lint`
- `git diff --check`
This commit is contained in:
Felipe Coury
2026-05-13 21:23:19 +00:00
committed by GitHub
parent 5d7e6a2503
commit 9798eb377a
29 changed files with 7339 additions and 22 deletions
@@ -439,6 +439,7 @@ mod command_exec_processor;
mod config_processor;
mod environment_processor;
mod external_agent_config_processor;
mod feedback_doctor_report;
mod feedback_processor;
mod fs_processor;
mod git_processor;
@@ -0,0 +1,212 @@
//! Builds a redacted doctor report attachment for feedback uploads.
//!
//! Feedback upload should never depend on doctor succeeding. This module runs
//! the configured Codex executable as a subprocess, accepts only valid JSON from
//! `codex doctor --json`, derives a small set of Sentry tags, and otherwise
//! skips the attachment with a warning. Keeping the report generation out of the
//! app-server process avoids sharing doctor internals across crates while still
//! attaching exactly the same JSON a user could copy from the CLI.
use std::collections::BTreeMap;
use std::time::Duration;
use codex_core::config::Config;
use codex_feedback::DOCTOR_REPORT_ATTACHMENT_FILENAME;
use codex_feedback::FeedbackAttachment;
use serde_json::Value;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::warn;
const DOCTOR_FEEDBACK_REPORT_TIMEOUT: Duration = Duration::from_secs(25);
const MAX_DOCTOR_TAG_VALUE_LEN: usize = 256;
/// Redacted doctor report data that can be merged into a feedback upload.
pub(crate) struct DoctorFeedbackReport {
/// JSON support report to upload as `codex-doctor-report.json`.
pub(crate) attachment: FeedbackAttachment,
/// Low-cardinality Sentry tags derived from the report status and check ids.
pub(crate) tags: BTreeMap<String, String>,
}
/// Runs `codex doctor --json` and returns a best-effort feedback attachment.
///
/// Failure to spawn Codex, finish before the timeout, or parse JSON means the
/// feedback upload proceeds without the doctor report. Callers should merge the
/// returned tags without overriding explicit client-provided tags.
pub(crate) async fn doctor_feedback_report(config: &Config) -> Option<DoctorFeedbackReport> {
let executable = config
.codex_self_exe
.clone()
.or_else(|| std::env::current_exe().ok())?;
let mut command = Command::new(&executable);
command.arg("doctor").arg("--json");
command.kill_on_drop(/*kill_on_drop*/ true);
let output = match timeout(DOCTOR_FEEDBACK_REPORT_TIMEOUT, command.output()).await {
Ok(Ok(output)) => output,
Ok(Err(err)) => {
warn!(
executable = %executable.display(),
error = %err,
"failed to run doctor report for feedback; skipping attachment"
);
return None;
}
Err(_) => {
warn!(
executable = %executable.display(),
"timed out running doctor report for feedback; skipping attachment"
);
return None;
}
};
let stdout = String::from_utf8_lossy(&output.stdout);
let Some(json_start) = stdout.find('{') else {
warn!(
executable = %executable.display(),
status = %output.status,
stderr = %String::from_utf8_lossy(&output.stderr),
"doctor report for feedback did not produce JSON; skipping attachment"
);
return None;
};
let json = stdout[json_start..].trim();
let report: Value = match serde_json::from_str(json) {
Ok(report) => report,
Err(err) => {
warn!(
executable = %executable.display(),
status = %output.status,
error = %err,
"doctor report for feedback was not valid JSON; skipping attachment"
);
return None;
}
};
let pretty = serde_json::to_vec_pretty(&report).unwrap_or_else(|_| json.as_bytes().to_vec());
Some(DoctorFeedbackReport {
tags: doctor_report_tags(&report),
attachment: FeedbackAttachment {
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
content_type: Some("application/json".to_string()),
buffer: pretty,
},
})
}
fn doctor_report_tags(report: &Value) -> BTreeMap<String, String> {
let mut tags = BTreeMap::new();
if let Some(overall_status) = report.get("overallStatus").and_then(Value::as_str) {
tags.insert(
"doctor_overall_status".to_string(),
truncate_tag_value(overall_status),
);
}
let mut ok_count = 0usize;
let mut warning_count = 0usize;
let mut fail_count = 0usize;
let mut failed_checks = Vec::new();
let mut warning_checks = Vec::new();
if let Some(checks) = report.get("checks") {
for check in check_values(checks) {
let status = check.get("status").and_then(Value::as_str);
let id = check.get("id").and_then(Value::as_str).unwrap_or("unknown");
match status {
Some("ok") => ok_count += 1,
Some("warning") => {
warning_count += 1;
warning_checks.push(id.to_string());
}
Some("fail") => {
fail_count += 1;
failed_checks.push(id.to_string());
}
_ => {}
}
}
}
tags.insert("doctor_ok_count".to_string(), ok_count.to_string());
tags.insert(
"doctor_warning_count".to_string(),
warning_count.to_string(),
);
tags.insert("doctor_fail_count".to_string(), fail_count.to_string());
if !failed_checks.is_empty() {
tags.insert(
"doctor_failed_checks".to_string(),
truncate_tag_value(&failed_checks.join(",")),
);
}
if !warning_checks.is_empty() {
tags.insert(
"doctor_warning_checks".to_string(),
truncate_tag_value(&warning_checks.join(",")),
);
}
tags
}
/// Iterates checks from both the current keyed JSON shape and older array reports.
fn check_values(checks: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
match checks {
Value::Array(values) => Box::new(values.iter()),
Value::Object(values) => Box::new(values.values()),
_ => Box::new(std::iter::empty()),
}
}
fn truncate_tag_value(value: &str) -> String {
if value.chars().count() <= MAX_DOCTOR_TAG_VALUE_LEN {
return value.to_string();
}
let prefix = value
.chars()
.take(MAX_DOCTOR_TAG_VALUE_LEN.saturating_sub(3))
.collect::<String>();
format!("{prefix}...")
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn doctor_report_tags_summarize_status_counts() {
let report = json!({
"overallStatus": "fail",
"checks": {
"runtime.provenance": {"id": "runtime.provenance", "status": "ok"},
"websocket.reachability": {
"id": "websocket.reachability",
"status": "warning"
},
"auth.credentials": {"id": "auth.credentials", "status": "fail"}
}
});
let tags = doctor_report_tags(&report);
let expected = BTreeMap::from([
("doctor_fail_count".to_string(), "1".to_string()),
(
"doctor_failed_checks".to_string(),
"auth.credentials".to_string(),
),
("doctor_ok_count".to_string(), "1".to_string()),
("doctor_overall_status".to_string(), "fail".to_string()),
(
"doctor_warning_checks".to_string(),
"websocket.reachability".to_string(),
),
("doctor_warning_count".to_string(), "1".to_string()),
]);
assert_eq!(tags, expected);
}
}
@@ -56,6 +56,7 @@ impl FeedbackRequestProcessor {
extra_log_files,
tags,
} = params;
let mut upload_tags = tags.unwrap_or_default();
let conversation_id = match thread_id.as_deref() {
Some(thread_id) => match ThreadId::from_string(thread_id) {
@@ -197,14 +198,27 @@ impl FeedbackRequestProcessor {
}
}
let mut extra_attachments = Vec::new();
if include_logs
&& let Some(doctor_report) =
super::feedback_doctor_report::doctor_feedback_report(&self.config).await
{
extra_attachments.push(doctor_report.attachment);
for (key, value) in doctor_report.tags {
upload_tags.entry(key).or_insert(value);
}
}
let session_source = self.thread_manager.session_source();
let upload_result = tokio::task::spawn_blocking(move || {
let tags = (!upload_tags.is_empty()).then_some(&upload_tags);
snapshot.upload_feedback(FeedbackUploadOptions {
classification: &classification,
reason: reason.as_deref(),
tags: tags.as_ref(),
tags,
include_logs,
extra_attachments: &extra_attachments,
extra_attachment_paths: &attachment_paths,
session_source: Some(session_source),
logs_override: sqlite_feedback_logs,