mirror of
https://github.com/openai/codex.git
synced 2026-11-13 14:46:14 +00:00
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:
1 parent
5d7e6a2503
commit
9798eb377a
29 files changed
+7339
-22
No files matched your search
@@ -0,0 +1,648 @@
|
||||
//! Converts raw doctor detail strings into human-oriented rows.
|
||||
//!
|
||||
//! Checks intentionally store details as simple redacted `label: value` strings
|
||||
//! so JSON serialization and human rendering share the same source data. This
|
||||
//! module owns the presentation-only transformations: collapsing noisy booleans,
|
||||
//! truncating long paths for terminal output, grouping repeated values, and
|
||||
//! keeping the `--all` expansion behavior out of check construction.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::env;
|
||||
|
||||
use super::DoctorCheck;
|
||||
use super::HumanOutputOptions;
|
||||
use super::redact_detail;
|
||||
|
||||
const LIST_LIMIT: usize = 7;
|
||||
const PATH_LIMIT: usize = 48;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(super) enum HumanDetail {
|
||||
Row {
|
||||
label: String,
|
||||
value: String,
|
||||
expected: Option<String>,
|
||||
},
|
||||
Continuation(String),
|
||||
Bullet(String),
|
||||
Remedy(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct ParsedDetail {
|
||||
label: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
pub(super) fn detail_lines(check: &DoctorCheck, options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let parsed = parsed_details(check);
|
||||
let details = match check.category.as_str() {
|
||||
"runtime" => runtime_details(&parsed),
|
||||
"install" => install_details(&parsed, options),
|
||||
"config" => config_details(&parsed, options),
|
||||
"state" => state_details(&parsed),
|
||||
_ => generic_details(&parsed),
|
||||
};
|
||||
let mut details = details
|
||||
.into_iter()
|
||||
.map(|detail| attach_issue_metadata(detail, check))
|
||||
.map(|detail| humanize_detail(detail, options))
|
||||
.collect::<Vec<_>>();
|
||||
details.extend(issue_remedies(check));
|
||||
details
|
||||
}
|
||||
|
||||
pub(super) fn detail_value(check: &DoctorCheck, label: &str) -> Option<String> {
|
||||
parsed_details(check)
|
||||
.into_iter()
|
||||
.find(|detail| detail.label == label)
|
||||
.map(|detail| detail.value)
|
||||
}
|
||||
|
||||
pub(super) fn rollout_summary(value: &str) -> Option<String> {
|
||||
let (files, rest) = value.split_once(" files, ")?;
|
||||
let (total_bytes, rest) = rest.split_once(" total bytes, ")?;
|
||||
let (average_bytes, _) = rest.split_once(" average bytes")?;
|
||||
let files = files.trim().parse::<u64>().ok()?;
|
||||
let total_bytes = total_bytes.trim().parse::<u64>().ok()?;
|
||||
let average_bytes = average_bytes.trim().parse::<u64>().ok()?;
|
||||
Some(format!(
|
||||
"{} files · {} (avg {})",
|
||||
format_count(files),
|
||||
format_bytes(total_bytes),
|
||||
format_bytes(average_bytes)
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn rollout_files_and_bytes(value: &str) -> Option<(u64, u64)> {
|
||||
let (files, rest) = value.split_once(" files, ")?;
|
||||
let (total_bytes, _) = rest.split_once(" total bytes, ")?;
|
||||
Some((
|
||||
files.trim().parse::<u64>().ok()?,
|
||||
total_bytes.trim().parse::<u64>().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn format_bytes(bytes: u64) -> String {
|
||||
const KIB: f64 = 1024.0;
|
||||
const MIB: f64 = KIB * 1024.0;
|
||||
const GIB: f64 = MIB * 1024.0;
|
||||
|
||||
let bytes = bytes as f64;
|
||||
if bytes >= GIB {
|
||||
format!("{:.2} GB", bytes / GIB)
|
||||
} else if bytes >= MIB {
|
||||
format!("{:.2} MB", bytes / MIB)
|
||||
} else if bytes >= KIB {
|
||||
format!("{:.2} KB", bytes / KIB)
|
||||
} else {
|
||||
format!("{} B", bytes as u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn format_count(count: u64) -> String {
|
||||
let mut digits = count.to_string();
|
||||
let mut out = String::new();
|
||||
while digits.len() > 3 {
|
||||
let tail = digits.split_off(digits.len() - 3);
|
||||
if out.is_empty() {
|
||||
out = tail;
|
||||
} else {
|
||||
out = format!("{tail},{out}");
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
digits
|
||||
} else {
|
||||
format!("{digits},{out}")
|
||||
}
|
||||
}
|
||||
|
||||
fn parsed_details(check: &DoctorCheck) -> Vec<ParsedDetail> {
|
||||
check
|
||||
.details
|
||||
.iter()
|
||||
.map(|detail| redact_detail(detail))
|
||||
.map(|detail| {
|
||||
detail
|
||||
.split_once(": ")
|
||||
.map(|(label, value)| ParsedDetail {
|
||||
label: label.to_string(),
|
||||
value: value.to_string(),
|
||||
})
|
||||
.unwrap_or_else(|| ParsedDetail {
|
||||
label: String::new(),
|
||||
value: detail,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn runtime_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "version", "version");
|
||||
push_row_if_present(&mut out, parsed, "install method", "install method");
|
||||
push_row_if_present(&mut out, parsed, "commit", "commit");
|
||||
push_row_if_present(&mut out, parsed, "current executable", "executable");
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"version",
|
||||
"platform",
|
||||
"install method",
|
||||
"commit",
|
||||
"current executable",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "install context", "context");
|
||||
if parsed.iter().any(|detail| {
|
||||
detail.value == "ignored inherited package-manager launch env for cargo-built binary"
|
||||
}) {
|
||||
out.push(HumanDetail::Bullet(
|
||||
"ignored inherited package-manager launch env for cargo-built binary".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let managed_by_npm = value(parsed, "managed by npm").unwrap_or("false");
|
||||
let managed_by_bun = value(parsed, "managed by bun").unwrap_or("false");
|
||||
let package_root = value(parsed, "managed package root").unwrap_or("not set");
|
||||
out.push(HumanDetail::Row {
|
||||
label: "managed by".to_string(),
|
||||
value: format!(
|
||||
"npm: {} · bun: {} · package root {}",
|
||||
yes_no(managed_by_npm),
|
||||
yes_no(managed_by_bun),
|
||||
if is_falsy(package_root) {
|
||||
"—".to_string()
|
||||
} else {
|
||||
package_root.to_string()
|
||||
}
|
||||
),
|
||||
expected: None,
|
||||
});
|
||||
|
||||
let path_entries = numbered_values(parsed, "PATH codex #");
|
||||
if !path_entries.is_empty() {
|
||||
let total = path_entries.len();
|
||||
let shown = if options.show_all {
|
||||
total
|
||||
} else {
|
||||
total.min(3)
|
||||
};
|
||||
out.push(HumanDetail::Row {
|
||||
label: format!("PATH entries ({total})"),
|
||||
value: path_entries[0].clone(),
|
||||
expected: None,
|
||||
});
|
||||
out.extend(
|
||||
path_entries
|
||||
.iter()
|
||||
.skip(1)
|
||||
.take(shown.saturating_sub(1))
|
||||
.cloned()
|
||||
.map(HumanDetail::Continuation),
|
||||
);
|
||||
if shown < total {
|
||||
out.push(HumanDetail::Continuation(
|
||||
"… (full list with --all)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"current executable",
|
||||
"install context",
|
||||
"managed by npm",
|
||||
"managed by bun",
|
||||
"managed package root",
|
||||
"PATH codex entries",
|
||||
],
|
||||
&["PATH codex #"],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn config_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(model) = value(parsed, "model") {
|
||||
let value = value(parsed, "model provider").map_or_else(
|
||||
|| model.to_string(),
|
||||
|provider| format!("{model} · {provider}"),
|
||||
);
|
||||
out.push(HumanDetail::Row {
|
||||
label: "model".to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
push_row_if_present(&mut out, parsed, "cwd", "cwd");
|
||||
push_row_if_present(&mut out, parsed, "config.toml", "config.toml");
|
||||
push_row_if_present(&mut out, parsed, "config.toml parse", "config.toml parse");
|
||||
push_row_if_present(&mut out, parsed, "config.toml read", "config.toml read");
|
||||
push_row_if_present(&mut out, parsed, "mcp servers", "MCP servers");
|
||||
push_feature_flags(&mut out, parsed, options);
|
||||
|
||||
for detail in parsed
|
||||
.iter()
|
||||
.filter(|detail| detail.label == "legacy feature flag")
|
||||
{
|
||||
out.push(HumanDetail::Row {
|
||||
label: "legacy alias".to_string(),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"CODEX_HOME",
|
||||
"cwd",
|
||||
"model",
|
||||
"model provider",
|
||||
"log dir",
|
||||
"sqlite home",
|
||||
"mcp servers",
|
||||
"feature flags enabled",
|
||||
"enabled feature flags",
|
||||
"feature flag overrides",
|
||||
"legacy feature flag",
|
||||
"config.toml",
|
||||
"config.toml parse",
|
||||
"config.toml read",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn state_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "CODEX_HOME", "CODEX_HOME");
|
||||
push_row_if_present(&mut out, parsed, "log dir", "log dir");
|
||||
push_row_if_present(&mut out, parsed, "sqlite home", "sqlite home");
|
||||
push_database_row(&mut out, parsed, "state DB");
|
||||
push_database_row(&mut out, parsed, "log DB");
|
||||
|
||||
for (source, label) in [
|
||||
("active rollout files", "active rollouts"),
|
||||
("archived rollout files", "archived rollouts"),
|
||||
] {
|
||||
if let Some(value) = value(parsed, source) {
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value: rollout_summary(value).unwrap_or_else(|| value.to_string()),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"CODEX_HOME",
|
||||
"log dir",
|
||||
"sqlite home",
|
||||
"state DB",
|
||||
"log DB",
|
||||
"state DB integrity",
|
||||
"log DB integrity",
|
||||
"active rollout files",
|
||||
"archived rollout files",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn generic_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
parsed
|
||||
.iter()
|
||||
.map(|detail| {
|
||||
if detail.label.is_empty() {
|
||||
HumanDetail::Bullet(detail.value.clone())
|
||||
} else {
|
||||
HumanDetail::Row {
|
||||
label: display_label(&detail.label),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_feature_flags(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
options: HumanOutputOptions,
|
||||
) {
|
||||
let enabled_count = value(parsed, "feature flags enabled")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.unwrap_or_default();
|
||||
let overrides = list_items(value(parsed, "feature flag overrides").unwrap_or("none"));
|
||||
let override_count = overrides.len();
|
||||
let hint = if !options.show_all && enabled_count > 0 {
|
||||
" (full list with --all)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
out.push(HumanDetail::Row {
|
||||
label: "feature flags".to_string(),
|
||||
value: format!("{enabled_count} enabled · {override_count} overridden{hint}"),
|
||||
expected: None,
|
||||
});
|
||||
|
||||
if !overrides.is_empty() {
|
||||
push_list_row(out, "overrides", &override_names(&overrides), options);
|
||||
}
|
||||
if options.show_all {
|
||||
let enabled = list_items(value(parsed, "enabled feature flags").unwrap_or("none"));
|
||||
if !enabled.is_empty() {
|
||||
push_list_row(out, "enabled flags", &enabled, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_list_row(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
label: &str,
|
||||
items: &[String],
|
||||
options: HumanOutputOptions,
|
||||
) {
|
||||
let limit = if options.show_all {
|
||||
items.len()
|
||||
} else {
|
||||
items.len().min(LIST_LIMIT)
|
||||
};
|
||||
let mut value = items
|
||||
.iter()
|
||||
.take(limit)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
if limit < items.len() {
|
||||
value.push_str(", … (full list with --all)");
|
||||
}
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn push_database_row(out: &mut Vec<HumanDetail>, parsed: &[ParsedDetail], label: &str) {
|
||||
let Some(path) = value(parsed, label) else {
|
||||
return;
|
||||
};
|
||||
let integrity = value(parsed, &format!("{label} integrity"));
|
||||
let value = integrity.map_or_else(
|
||||
|| path.to_string(),
|
||||
|integrity| format!("{path} · integrity {integrity}"),
|
||||
);
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn push_row_if_present(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
source_label: &str,
|
||||
display_label: &str,
|
||||
) {
|
||||
if let Some(value) = value(parsed, source_label) {
|
||||
out.push(HumanDetail::Row {
|
||||
label: display_label.to_string(),
|
||||
value: value.to_string(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn push_remaining(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
consumed_labels: &[&str],
|
||||
consumed_prefixes: &[&str],
|
||||
) {
|
||||
for detail in parsed {
|
||||
if detail.value == "ignored inherited package-manager launch env for cargo-built binary" {
|
||||
continue;
|
||||
}
|
||||
if consumed_labels.contains(&detail.label.as_str())
|
||||
|| consumed_prefixes
|
||||
.iter()
|
||||
.any(|prefix| detail.label.starts_with(prefix))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if detail.label.is_empty() {
|
||||
out.push(HumanDetail::Bullet(detail.value.clone()));
|
||||
} else {
|
||||
out.push(HumanDetail::Row {
|
||||
label: display_label(&detail.label),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn humanize_detail(detail: HumanDetail, options: HumanOutputOptions) -> HumanDetail {
|
||||
match detail {
|
||||
HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
} => HumanDetail::Row {
|
||||
label,
|
||||
value: humanize_value(&value, options),
|
||||
expected,
|
||||
},
|
||||
HumanDetail::Continuation(value) => {
|
||||
HumanDetail::Continuation(humanize_value(&value, options))
|
||||
}
|
||||
HumanDetail::Bullet(value) => HumanDetail::Bullet(humanize_value(&value, options)),
|
||||
HumanDetail::Remedy(value) => HumanDetail::Remedy(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_issue_metadata(detail: HumanDetail, check: &DoctorCheck) -> HumanDetail {
|
||||
let HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
} = detail
|
||||
else {
|
||||
return detail;
|
||||
};
|
||||
let expected = expected.or_else(|| issue_expected_for_label(check, &label));
|
||||
HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn issue_expected_for_label(check: &DoctorCheck, label: &str) -> Option<String> {
|
||||
check
|
||||
.issues
|
||||
.iter()
|
||||
.find(|issue| {
|
||||
issue
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| display_label(field) == label || field == label)
|
||||
})
|
||||
.and_then(|issue| issue.expected.clone())
|
||||
}
|
||||
|
||||
fn issue_remedies(check: &DoctorCheck) -> Vec<HumanDetail> {
|
||||
let mut seen = BTreeSet::new();
|
||||
check
|
||||
.issues
|
||||
.iter()
|
||||
.filter_map(|issue| issue.remedy.as_ref())
|
||||
.filter(|remedy| seen.insert((*remedy).clone()))
|
||||
.cloned()
|
||||
.map(HumanDetail::Remedy)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn humanize_value(value: &str, _options: HumanOutputOptions) -> String {
|
||||
if looks_like_path(value) {
|
||||
return shorten_path_prefix(value);
|
||||
}
|
||||
if let Some(timestamp) = humanize_timestamp(value) {
|
||||
return timestamp;
|
||||
}
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
fn humanize_timestamp(value: &str) -> Option<String> {
|
||||
if value.len() < 17 || !value.ends_with('Z') {
|
||||
return None;
|
||||
}
|
||||
let (date, time) = value.split_once('T')?;
|
||||
let hour_minute = time.get(..5)?;
|
||||
Some(format!("{date} {hour_minute} UTC"))
|
||||
}
|
||||
|
||||
fn shorten_path_prefix(value: &str) -> String {
|
||||
let (path, suffix) = value.split_once(" (").map_or_else(
|
||||
|| (value, String::new()),
|
||||
|(path, suffix)| (path, format!(" ({suffix}")),
|
||||
);
|
||||
let home_shortened = home_shortened_path(path);
|
||||
let shortened = middle_truncate(&home_shortened, PATH_LIMIT);
|
||||
format!("{shortened}{suffix}")
|
||||
}
|
||||
|
||||
fn home_shortened_path(path: &str) -> String {
|
||||
let Some(home) = env::var_os("HOME").and_then(|home| home.into_string().ok()) else {
|
||||
return path.to_string();
|
||||
};
|
||||
if path == home {
|
||||
"~".to_string()
|
||||
} else {
|
||||
path.strip_prefix(&format!("{home}/"))
|
||||
.map_or_else(|| path.to_string(), |tail| format!("~/{tail}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn middle_truncate(value: &str, max_chars: usize) -> String {
|
||||
let char_count = value.chars().count();
|
||||
if char_count <= max_chars {
|
||||
return value.to_string();
|
||||
}
|
||||
let head_len = max_chars / 2;
|
||||
let tail_len = max_chars.saturating_sub(head_len + 1);
|
||||
let head = value.chars().take(head_len).collect::<String>();
|
||||
let tail = value
|
||||
.chars()
|
||||
.rev()
|
||||
.take(tail_len)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev()
|
||||
.collect::<String>();
|
||||
format!("{head}…{tail}")
|
||||
}
|
||||
|
||||
fn looks_like_path(value: &str) -> bool {
|
||||
value.starts_with('/')
|
||||
|| value.starts_with("~/")
|
||||
|| value.starts_with("./")
|
||||
|| value.starts_with("../")
|
||||
}
|
||||
|
||||
fn numbered_values(parsed: &[ParsedDetail], prefix: &str) -> Vec<String> {
|
||||
parsed
|
||||
.iter()
|
||||
.filter(|detail| detail.label.starts_with(prefix))
|
||||
.map(|detail| detail.value.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn value<'a>(parsed: &'a [ParsedDetail], label: &str) -> Option<&'a str> {
|
||||
parsed
|
||||
.iter()
|
||||
.find(|detail| detail.label == label)
|
||||
.map(|detail| detail.value.as_str())
|
||||
}
|
||||
|
||||
fn display_label(label: &str) -> String {
|
||||
match label {
|
||||
"codex-linux-sandbox helper" => "linux helper",
|
||||
"optional reachability failed" => "optional reachability",
|
||||
"check for update on startup" => "startup update check",
|
||||
other => other,
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn list_items(value: &str) -> Vec<String> {
|
||||
if is_falsy(value) {
|
||||
return Vec::new();
|
||||
}
|
||||
value
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|item| !item.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn override_names(items: &[String]) -> Vec<String> {
|
||||
items
|
||||
.iter()
|
||||
.map(|item| item.split_once('=').map_or(item.as_str(), |(name, _)| name))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn yes_no(value: &str) -> &'static str {
|
||||
if value == "true" { "yes" } else { "no" }
|
||||
}
|
||||
|
||||
pub(super) fn is_falsy(value: &str) -> bool {
|
||||
matches!(
|
||||
value.trim().to_ascii_lowercase().as_str(),
|
||||
"" | "false" | "none" | "not set" | "unknown" | "missing" | "absent" | "no" | "—" | "-"
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user