Detect Ghostty truecolor when SSH omits COLORTERM (#63710)

## Why

SSH can forward Ghostty's `TERM=xterm-ghostty` without `COLORTERM`,
leaving Codex to use an ANSI-16 palette for a truecolor terminal.

## What changed

Centralize stdout color detection in `codex-terminal-detection`. Upgrade
an ANSI-16 result to truecolor when `TERM` is `xterm-ghostty` and neither
`FORCE_COLOR` nor an active `CLICOLOR_FORCE` override is present.

Use the shared detection for TUI colors, including shimmer and activity
indicators. Share the existing Windows Terminal palette rules between
diff rendering and theme colors.

## Testing

Cover Ghostty's `TERM` fallback, explicit color overrides, and Windows
Terminal palette detection in unit tests. Exercise theme preview,
selection, and restoration with Ghostty's `TERM` and no `COLORTERM`.

GitOrigin-RevId: e7b6832fc7e721d5e2c23ef19df5fe55fbfeb21a
This commit is contained in:
Eric Traut
2026-11-24 18:50:19 +00:00
committed by copyberry
parent c4345a0079
commit 7f8dcb3e64
13 changed files with 138 additions and 275 deletions
+1 -1
View File
@@ -5245,6 +5245,7 @@ name = "codex-terminal-detection"
version = "0.0.0"
dependencies = [
"pretty_assertions",
"supports-color 3.0.2",
"tracing",
]
@@ -5455,7 +5456,6 @@ dependencies = [
"shlex",
"strum 0.27.2",
"strum_macros 0.28.0",
"supports-color 3.0.2",
"syntect",
"tempfile",
"textwrap 0.16.2",
+1
View File
@@ -13,6 +13,7 @@ doctest = false
workspace = true
[dependencies]
supports-color = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
+64
View File
@@ -0,0 +1,64 @@
//! Resolve stdout color depth and terminal-specific fallbacks without probing the terminal.
use super::Environment;
use super::GHOSTTY_TERM;
use super::ProcessEnvironment;
use super::TerminalName;
use super::terminal_info;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum StdoutColorLevel {
TrueColor,
Ansi256,
Ansi16,
Unknown,
}
/// Color depth for stdout, including terminal types missed by supports-color.
pub fn stdout_color_level() -> StdoutColorLevel {
match supports_color::on_cached(supports_color::Stream::Stdout) {
Some(level) if level.has_16m => StdoutColorLevel::TrueColor,
Some(level) if level.has_256 => StdoutColorLevel::Ansi256,
Some(_) => ansi_color_level(&ProcessEnvironment),
None => StdoutColorLevel::Unknown,
}
}
pub(super) fn ansi_color_level(env: &dyn Environment) -> StdoutColorLevel {
// SSH may forward TERM without COLORTERM. Check TERM itself, since a
// multiplexer can inherit Ghostty's identity but advertise a different palette.
if env.var("TERM").as_deref() == Some(GHOSTTY_TERM)
&& !env.has("FORCE_COLOR")
&& env.var("CLICOLOR_FORCE").is_none_or(|value| value == "0")
{
StdoutColorLevel::TrueColor
} else {
StdoutColorLevel::Ansi16
}
}
/// Color depth for interactive palettes, including Windows Terminal sessions
/// where stdout detection can be inconclusive.
pub fn terminal_color_level() -> StdoutColorLevel {
color_level_for_terminal(
stdout_color_level(),
terminal_info().name,
&ProcessEnvironment,
)
}
pub(super) fn color_level_for_terminal(
level: StdoutColorLevel,
name: TerminalName,
env: &dyn Environment,
) -> StdoutColorLevel {
// TERM_PROGRAM can mask WT_SESSION during terminal identification.
if (env.has("WT_SESSION")
|| (level == StdoutColorLevel::Ansi16 && name == TerminalName::WindowsTerminal))
&& !env.has("FORCE_COLOR")
{
StdoutColorLevel::TrueColor
} else {
level
}
}
+10 -3
View File
@@ -1,11 +1,18 @@
//! Terminal detection utilities.
//!
//! This module feeds terminal metadata into OpenTelemetry user-agent logging and into
//! terminal-specific configuration choices in the TUI. Detection only reads the
//! environment; it must not execute helpers selected by an untrusted PATH.
//! terminal-specific configuration choices in the TUI. Detection reads the
//! environment and stdout capabilities without executing helpers from PATH.
use std::sync::OnceLock;
mod color;
pub use color::StdoutColorLevel;
pub use color::stdout_color_level;
pub use color::terminal_color_level;
const GHOSTTY_TERM: &str = "xterm-ghostty";
/// Structured terminal identification data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TerminalInfo {
@@ -141,7 +148,7 @@ impl TerminalInfo {
fn from_term(term: String, multiplexer: Option<Multiplexer>) -> Self {
let name = match term.as_str() {
"dumb" => TerminalName::Dumb,
"xterm-ghostty" => TerminalName::Ghostty,
GHOSTTY_TERM => TerminalName::Ghostty,
"xterm-rex" => TerminalName::Rex,
"wezterm" | "wezterm-mux" => TerminalName::WezTerm,
_ => TerminalName::Unknown,
@@ -216,6 +216,40 @@ fn detects_ghostty() {
"xterm-ghostty",
"ghostty_term_user_agent"
);
assert_eq!(color::ansi_color_level(&env), StdoutColorLevel::TrueColor);
for key in ["FORCE_COLOR", "CLICOLOR_FORCE"] {
let forced = FakeEnvironment::new()
.with_var("TERM", "xterm-ghostty")
.with_var(key, "1");
assert_eq!(color::ansi_color_level(&forced), StdoutColorLevel::Ansi16);
}
let generic = env
.with_var("TERM", "xterm")
.with_var("TERM_PROGRAM", "Ghostty");
assert_eq!(color::ansi_color_level(&generic), StdoutColorLevel::Ansi16);
}
#[test]
fn windows_terminal_palette_respects_stdout_overrides() {
use StdoutColorLevel::*;
let palette = |level, env: &FakeEnvironment| {
color::color_level_for_terminal(level, detect_terminal_info_from_env(env).name, env)
};
let named = FakeEnvironment::new().with_var("TERM_PROGRAM", "WindowsTerminal");
assert_eq!(palette(Ansi16, &named), TrueColor);
assert_eq!(palette(Unknown, &named), Unknown);
assert_eq!(palette(Ansi16, &named.with_var("FORCE_COLOR", "1")), Ansi16);
let other = FakeEnvironment::new().with_var("TERM_PROGRAM", "WezTerm");
assert_eq!(palette(Ansi16, &other), Ansi16);
let session = other.with_var("WT_SESSION", "session");
assert_eq!(palette(Ansi16, &session), TrueColor);
assert_eq!(palette(Unknown, &session), TrueColor);
assert_eq!(
palette(Ansi256, &session.with_var("FORCE_COLOR", "2")),
Ansi256
);
}
#[test]
-1
View File
@@ -110,7 +110,6 @@ sha2 = { workspace = true }
shlex = { workspace = true }
strum = { workspace = true }
strum_macros = { workspace = true }
supports-color = { workspace = true }
tempfile = { workspace = true }
textwrap = { workspace = true }
thiserror = { workspace = true }
+6 -175
View File
@@ -101,11 +101,8 @@ use crate::terminal_palette::XTERM_COLORS;
use crate::terminal_palette::default_bg;
use crate::terminal_palette::indexed_color;
use crate::terminal_palette::rgb_color;
use crate::terminal_palette::stdout_color_level;
use crate::width::display_width;
use codex_git_utils::get_git_repo_root;
use codex_terminal_detection::TerminalName;
use codex_terminal_detection::terminal_info;
/// Classifies a diff line for gutter sign rendering and style selection.
///
@@ -133,13 +130,6 @@ enum DiffTheme {
}
/// Palette depth the diff renderer will target.
///
/// This is the *renderer's own* notion of color depth, derived from — but not
/// identical to — the raw [`StdoutColorLevel`] reported by `supports-color`.
/// The indirection exists because some terminals (notably Windows Terminal)
/// advertise only ANSI-16 support while actually rendering truecolor sequences
/// correctly; [`diff_color_level_for_terminal`] promotes those cases so the
/// diff output uses the richer palette.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DiffColorLevel {
TrueColor,
@@ -214,7 +204,7 @@ fn resolve_diff_backgrounds(
/// Snapshot the current terminal environment into a reusable style context.
///
/// Queries `diff_theme`, `diff_color_level`, and the active syntax theme's
/// Queries `diff_theme`, terminal color depth, and the active syntax theme's
/// scope backgrounds once, bundling them into a [`DiffRenderStyleContext`]
/// that callers thread through every line-rendering call in a single pass.
///
@@ -223,7 +213,11 @@ fn resolve_diff_backgrounds(
/// mid-render (theme picker live preview).
pub(crate) fn current_diff_render_style_context() -> DiffRenderStyleContext {
let theme = diff_theme();
let color_level = diff_color_level();
let color_level = match codex_terminal_detection::terminal_color_level() {
StdoutColorLevel::TrueColor => DiffColorLevel::TrueColor,
StdoutColorLevel::Ansi256 => DiffColorLevel::Ansi256,
StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown => DiffColorLevel::Ansi16,
};
let diff_backgrounds = resolve_diff_backgrounds(theme, color_level);
DiffRenderStyleContext {
theme,
@@ -1101,78 +1095,6 @@ fn diff_theme() -> DiffTheme {
diff_theme_for_bg(default_bg())
}
/// Return the [`DiffColorLevel`] for the current terminal session.
///
/// This is the environment-reading adapter: it samples runtime signals
/// (`supports-color` level, terminal name, `WT_SESSION`, and `FORCE_COLOR`)
/// and forwards them to [`diff_color_level_for_terminal`].
///
/// Keeping env reads in this thin wrapper lets
/// [`diff_color_level_for_terminal`] stay pure and easy to unit test.
fn diff_color_level() -> DiffColorLevel {
diff_color_level_for_terminal(
stdout_color_level(),
terminal_info().name,
std::env::var_os("WT_SESSION").is_some(),
has_force_color_override(),
)
}
/// Returns whether `FORCE_COLOR` is explicitly set.
fn has_force_color_override() -> bool {
std::env::var_os("FORCE_COLOR").is_some()
}
/// Map a raw [`StdoutColorLevel`] to a [`DiffColorLevel`] using
/// Windows Terminal-specific truecolor promotion rules.
///
/// This helper is intentionally pure (no env access) so tests can validate
/// the policy table by passing explicit inputs.
///
/// Windows Terminal fully supports 24-bit color but the `supports-color`
/// crate often reports only ANSI-16 there because no `COLORTERM` variable
/// is set. We detect Windows Terminal two ways — via `terminal_name`
/// (parsed from `WT_SESSION` / `TERM_PROGRAM` by `terminal_info()`) and
/// via the raw `has_wt_session` flag.
///
/// These signals are intentionally not equivalent: `terminal_name` is a
/// derived classification with `TERM_PROGRAM` precedence, so `WT_SESSION`
/// can be present while `terminal_name` is not `WindowsTerminal`.
///
/// When `WT_SESSION` is present, we promote to truecolor unconditionally
/// unless `FORCE_COLOR` is set. This keeps Windows Terminal rendering rich
/// by default while preserving explicit `FORCE_COLOR` user intent.
///
/// Outside `WT_SESSION`, only ANSI-16 is promoted for identified
/// `WindowsTerminal` sessions; `Unknown` stays conservative.
fn diff_color_level_for_terminal(
stdout_level: StdoutColorLevel,
terminal_name: TerminalName,
has_wt_session: bool,
has_force_color_override: bool,
) -> DiffColorLevel {
if has_wt_session && !has_force_color_override {
return DiffColorLevel::TrueColor;
}
let base = match stdout_level {
StdoutColorLevel::TrueColor => DiffColorLevel::TrueColor,
StdoutColorLevel::Ansi256 => DiffColorLevel::Ansi256,
StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown => DiffColorLevel::Ansi16,
};
// Outside `WT_SESSION`, keep the existing Windows Terminal promotion for
// ANSI-16 sessions that likely support truecolor.
if stdout_level == StdoutColorLevel::Ansi16
&& terminal_name == TerminalName::WindowsTerminal
&& !has_force_color_override
{
DiffColorLevel::TrueColor
} else {
base
}
}
// -- Style helpers ------------------------------------------------------------
//
// Each diff line is composed of three visual regions, styled independently:
@@ -2255,97 +2177,6 @@ mod tests {
assert_eq!(lines[1].style.bg, Some(rgb_color(LIGHT_TC_ADD_LINE_BG_RGB)));
}
#[test]
fn windows_terminal_promotes_ansi16_to_truecolor_for_diffs() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::WindowsTerminal,
/*has_wt_session*/ false,
/*has_force_color_override*/ false,
),
DiffColorLevel::TrueColor
);
}
#[test]
fn wt_session_promotes_ansi16_to_truecolor_for_diffs() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::Unknown,
/*has_wt_session*/ true,
/*has_force_color_override*/ false,
),
DiffColorLevel::TrueColor
);
}
#[test]
fn non_windows_terminal_keeps_ansi16_diff_palette() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::WezTerm,
/*has_wt_session*/ false,
/*has_force_color_override*/ false,
),
DiffColorLevel::Ansi16
);
}
#[test]
fn wt_session_promotes_unknown_color_level_to_truecolor() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Unknown,
TerminalName::WindowsTerminal,
/*has_wt_session*/ true,
/*has_force_color_override*/ false,
),
DiffColorLevel::TrueColor
);
}
#[test]
fn non_wt_windows_terminal_keeps_unknown_color_level_conservative() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Unknown,
TerminalName::WindowsTerminal,
/*has_wt_session*/ false,
/*has_force_color_override*/ false,
),
DiffColorLevel::Ansi16
);
}
#[test]
fn explicit_force_override_keeps_ansi16_on_windows_terminal() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::WindowsTerminal,
/*has_wt_session*/ false,
/*has_force_color_override*/ true,
),
DiffColorLevel::Ansi16
);
}
#[test]
fn explicit_force_override_keeps_ansi256_on_windows_terminal() {
assert_eq!(
diff_color_level_for_terminal(
StdoutColorLevel::Ansi256,
TerminalName::WindowsTerminal,
/*has_wt_session*/ true,
/*has_force_color_override*/ true,
),
DiffColorLevel::Ansi256
);
}
#[test]
fn add_diff_uses_path_extension_for_highlighting() {
crate::terminal_palette::with_test_default_colors(
+3 -2
View File
@@ -6,12 +6,13 @@ use clap::Parser;
use codex_arg0::Arg0DispatchPaths;
use codex_arg0::arg0_dispatch_or_else;
use codex_config::LoaderOverrides;
use codex_terminal_detection::StdoutColorLevel;
use codex_terminal_detection::stdout_color_level;
use codex_tui::Cli;
use codex_tui::ExitReason;
use codex_tui::run_main;
use codex_utils_cli::CliConfigOverrides;
use std::io::Write;
use supports_color::Stream;
#[derive(Parser, Debug)]
struct TopCli {
@@ -46,7 +47,7 @@ fn main() -> anyhow::Result<()> {
ExitReason::UserRequested | ExitReason::TurnInterrupted => false,
};
let color_enabled = supports_color::on(Stream::Stdout).is_some();
let color_enabled = stdout_color_level() != StdoutColorLevel::Unknown;
for line in exit_info.format_exit_messages(color_enabled) {
println!("{line}");
}
+3 -4
View File
@@ -6,6 +6,8 @@
use std::time::Duration;
use std::time::Instant;
use crate::terminal_palette::StdoutColorLevel;
use crate::terminal_palette::stdout_color_level;
use crate::text_formatting::contains_rtl_or_arabic_number;
use crate::tui::FrameRequester;
use ratatui::style::Stylize;
@@ -101,10 +103,7 @@ pub(crate) fn shimmer_text(text: &str, motion_mode: MotionMode) -> Vec<Span<'sta
fn animated_activity_indicator(start_time: Option<Instant>) -> Span<'static> {
let elapsed = start_time.map(|st| st.elapsed()).unwrap_or_default();
if supports_color::on_cached(supports_color::Stream::Stdout)
.map(|level| level.has_16m)
.unwrap_or(false)
{
if stdout_color_level() == StdoutColorLevel::TrueColor {
shimmer_spans("•")
.into_iter()
.next()
+3 -3
View File
@@ -8,8 +8,10 @@ use ratatui::style::Style;
use ratatui::text::Span;
use crate::color::blend;
use crate::terminal_palette::StdoutColorLevel;
use crate::terminal_palette::default_bg;
use crate::terminal_palette::default_fg;
use crate::terminal_palette::stdout_color_level;
static PROCESS_START: OnceLock<Instant> = OnceLock::new();
@@ -30,9 +32,7 @@ pub(super) fn shimmer_spans(text: &str) -> Vec<Span<'static>> {
let pos_f =
(elapsed_since_start().as_secs_f32() % sweep_seconds) / sweep_seconds * (period as f32);
let pos = pos_f as usize;
let has_true_color = supports_color::on_cached(supports_color::Stream::Stdout)
.map(|level| level.has_16m)
.unwrap_or(false);
let has_true_color = stdout_color_level() == StdoutColorLevel::TrueColor;
let band_half_width = 5.0;
let mut spans: Vec<Span<'static>> = Vec::with_capacity(chars.len());
+3 -84
View File
@@ -1,25 +1,8 @@
use crate::color::perceptual_distance;
use codex_terminal_detection::TerminalName;
use codex_terminal_detection::terminal_info;
pub use codex_terminal_detection::StdoutColorLevel;
pub use codex_terminal_detection::stdout_color_level;
use ratatui::style::Color;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum StdoutColorLevel {
TrueColor,
Ansi256,
Ansi16,
Unknown,
}
pub fn stdout_color_level() -> StdoutColorLevel {
match supports_color::on_cached(supports_color::Stream::Stdout) {
Some(level) if level.has_16m => StdoutColorLevel::TrueColor,
Some(level) if level.has_256 => StdoutColorLevel::Ansi256,
Some(_) => StdoutColorLevel::Ansi16,
None => StdoutColorLevel::Unknown,
}
}
#[allow(clippy::disallowed_methods)]
pub fn rgb_color((r, g, b): (u8, u8, u8)) -> Color {
Color::Rgb(r, g, b)
@@ -47,32 +30,7 @@ pub(crate) fn effective_stdout_color_level() -> StdoutColorLevel {
return StdoutColorLevel::TrueColor;
}
stdout_color_level_for_terminal(
stdout_color_level(),
terminal_info().name,
std::env::var_os("WT_SESSION").is_some(),
std::env::var_os("FORCE_COLOR").is_some(),
)
}
fn stdout_color_level_for_terminal(
stdout_level: StdoutColorLevel,
terminal_name: TerminalName,
has_wt_session: bool,
has_force_color_override: bool,
) -> StdoutColorLevel {
if has_wt_session && !has_force_color_override {
return StdoutColorLevel::TrueColor;
}
if stdout_level == StdoutColorLevel::Ansi16
&& terminal_name == TerminalName::WindowsTerminal
&& !has_force_color_override
{
StdoutColorLevel::TrueColor
} else {
stdout_level
}
codex_terminal_detection::terminal_color_level()
}
fn best_color_for_color_level(target: (u8, u8, u8), color_level: StdoutColorLevel) -> Color {
@@ -513,43 +471,4 @@ mod tests {
Color::Reset
);
}
#[test]
fn windows_terminal_wt_session_promotes_to_truecolor() {
assert_eq!(
stdout_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::Unknown,
/*has_wt_session*/ true,
/*has_force_color_override*/ false,
),
StdoutColorLevel::TrueColor
);
}
#[test]
fn windows_terminal_name_promotes_ansi16_to_truecolor() {
assert_eq!(
stdout_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::WindowsTerminal,
/*has_wt_session*/ false,
/*has_force_color_override*/ false,
),
StdoutColorLevel::TrueColor
);
}
#[test]
fn force_color_keeps_reported_stdout_level() {
assert_eq!(
stdout_color_level_for_terminal(
StdoutColorLevel::Ansi16,
TerminalName::WindowsTerminal,
/*has_wt_session*/ true,
/*has_force_color_override*/ true,
),
StdoutColorLevel::Ansi16
);
}
}
+9 -1
View File
@@ -15,7 +15,15 @@ fn model_theme_files_preview_select_and_restore() {
"--nocapture",
])
.env("CODEX_MODEL_THEME_TEST_CHILD", "1")
.env("FORCE_COLOR", "3")
// Reproduce SSH forwarding Ghostty's TERM without COLORTERM.
.env("TERM", "xterm-ghostty")
.env("IGNORE_IS_TERMINAL", "1")
.env_remove("TERM_PROGRAM")
.env_remove("WT_SESSION")
.env_remove("COLORTERM")
.env_remove("NO_COLOR")
.env_remove("FORCE_COLOR")
.env_remove("CLICOLOR_FORCE")
.output()
.unwrap();
assert!(
+1 -1
View File
@@ -813,7 +813,7 @@ impl Tui {
let frame_requester = FrameRequester::new(draw_tx.clone());
// Cache this to avoid contention with the event reader.
supports_color::on_cached(supports_color::Stream::Stdout);
codex_terminal_detection::stdout_color_level();
let _ = crate::terminal_palette::default_colors();
let terminal_info = codex_terminal_detection::terminal_info();
let scrollback = ScrollbackStrategy::detect(&terminal_info);