Synced from monorepo

Synced from monorepo

Changes:
- Shell: accept target response id on rewind execute
- Shell: stamp response id on chat user message chunks
- Worktree: optional rebuild and stale git registration cleanup in auto-GC
- Worktree: kind-aware auto-GC TTLs and config knobs
- Worktree: macOS process CWD scan and Unix PID liveness for GC guards
- Worktree: automatic throttled GC on startup (Linux age-based; non-Linux dead-only)
- Pager: add `[ui].combine_queued_prompts` to batch queued follow-ups
- Shell: stop overwriting user skills
- Tools: read markdown in `skills/` directories untruncated
- `/usage` shows per-session token and dollar usage in the TUI
- Security: prompt on environment-dumping `ps` variants
- Security: always-safe `kubectl` no longer runs arbitrary kubeconfig credential plugins without permission
- Tools: make scheduler deletion durable
- Shell: add relocation storage primitives
- Shell: give side model calls their own conversation ids
- Fix five workflow-runtime bugs (budget, pause, cancel, reconnect)
- Security: peel `env -S` / `--split-string` operands in the Bash permission gate (managed deny/ask)
- Pager: expose doctor in the TUI
- Security: block unauthorized RCE via abused safe commands
- Pager idle watcher cue: "1 subagent still running" instead of "watching · 1 subagent"
- Security: block `rg --pre` arbitrary code execution in auto-mode
- Voice: diagnose silent-mic failures (macOS permission) and add doctor/terminal-setup Voice section
- App builder deployer: `allow_forking` and `show_built_with_grok`
- Pager: stop stacking duplicate "Worked for" markers on parked turns
- Shell: support `max` as a distinct reasoning effort tier
- Tools: serialize background `/loop` fires on the whole work unit
- Shell: add working-directory relocation state primitives
- Proto: `ClientToolResult` and `ChatConfig` client-side tools
- Shell: model providers
- Chat: select App Builder product on the Build path
- Shell: attach author identity to feedback when the deployment opts in
- Doctor: fix for SSH wrap setup
- Workflow authoring skills: create-workflow and import-claude-workflow docs
- Add read-only grok doctor
- Sandbox: apply Landlock without a controlling TTY
- Pager: recover image paste over grok wrap on headless remotes
- Pager: make actions screen-mode aware
- Shell: resume sessions when the working directory moves
- Pager: centralize terminal diagnostics
- Workspace: gate inline shell file access
- Pager: centralize terminal probes
- Pager: edit minimal prompts in an external editor
- Pager: standardize backgrounding on Ctrl+B
- Shell: recap rides the parent turn's prompt cache
- Tools: add scheduler lifecycle version clock

Source-Revision: 0f4d7c91b8b2b408333f6de1e8a76cb8eaa71899
This commit is contained in:
grokkybara[bot] 2026-07-21 18:10:23 +00:00
commit 3af4d5d398
556 changed files with 56609 additions and 21892 deletions

View file

@ -31,6 +31,8 @@ const TIMESTAMPS_DEFAULT: bool = true;
/// const context and the effective-config fallback read.
const TIMELINE_DEFAULT: bool = UiConfig::SHOW_TIMELINE_DEFAULT;
const PAGE_FLIP_ON_SEND_DEFAULT: bool = UiConfig::PAGE_FLIP_ON_SEND_DEFAULT;
/// Combine-queued-prompts rollout flag defaults OFF (opt-in).
const COMBINE_QUEUED_PROMPTS_DEFAULT: bool = false;
const SIMPLE_MODE_DEFAULT: bool = true;
/// Vim-mode scrollback default — matches the previous on-disk default.
const VIM_MODE_DEFAULT: bool = false;
@ -164,6 +166,35 @@ pub fn set_page_flip_on_send(enabled: bool) {
PAGE_FLIP_ON_SEND_LOADED.with(|l| l.set(true));
}
// -- Combine queued prompts ---------------------------------------------------
thread_local! {
static COMBINE_QUEUED_PROMPTS_CURRENT: Cell<bool> =
const { Cell::new(COMBINE_QUEUED_PROMPTS_DEFAULT) };
static COMBINE_QUEUED_PROMPTS_LOADED: Cell<bool> = const { Cell::new(false) };
}
/// Cached `combine_queued_prompts`, seeding from `[ui]` on first call.
pub fn load_combine_queued_prompts() -> bool {
COMBINE_QUEUED_PROMPTS_LOADED.with(|loaded| {
if !loaded.get() {
COMBINE_QUEUED_PROMPTS_CURRENT.with(|c| {
c.set(load_bool_from_effective_config(
"combine_queued_prompts",
COMBINE_QUEUED_PROMPTS_DEFAULT,
))
});
loaded.set(true);
}
});
COMBINE_QUEUED_PROMPTS_CURRENT.with(|c| c.get())
}
pub fn set_combine_queued_prompts(enabled: bool) {
COMBINE_QUEUED_PROMPTS_CURRENT.with(|c| c.set(enabled));
COMBINE_QUEUED_PROMPTS_LOADED.with(|l| l.set(true));
}
// -- Simple mode --------------------------------------------------------------
thread_local! {
@ -575,6 +606,10 @@ pub fn prime(ui: &UiConfig) {
set_timestamps(ui.show_timestamps.unwrap_or(TIMESTAMPS_DEFAULT));
set_show_timeline(ui.show_timeline_enabled());
set_page_flip_on_send(ui.page_flip_on_send_enabled());
set_combine_queued_prompts(
ui.combine_queued_prompts
.unwrap_or(COMBINE_QUEUED_PROMPTS_DEFAULT),
);
set_simple_mode(ui.simple_mode.unwrap_or(SIMPLE_MODE_DEFAULT));
set_keep_text_selection(text_selection_from_ui(ui));
// Layered-config keys (not the `UiConfig` arg) — seed so the first frame
@ -687,6 +722,11 @@ mod tests {
assert_eq!(TIMESTAMPS_DEFAULT, ui.show_timestamps.unwrap_or(true));
assert_eq!(TIMELINE_DEFAULT, ui.show_timeline_enabled());
assert_eq!(PAGE_FLIP_ON_SEND_DEFAULT, ui.page_flip_on_send_enabled());
assert_eq!(
COMBINE_QUEUED_PROMPTS_DEFAULT,
ui.combine_queued_prompts
.unwrap_or(COMBINE_QUEUED_PROMPTS_DEFAULT)
);
assert_eq!(SIMPLE_MODE_DEFAULT, ui.simple_mode.unwrap_or(true));
assert_eq!(VIM_MODE_DEFAULT, ui.vim_mode.unwrap_or(false));
assert_eq!(
@ -769,6 +809,18 @@ mod tests {
.unwrap();
}
#[test]
fn set_then_load_round_trips_combine_queued_prompts() {
std::thread::spawn(|| {
set_combine_queued_prompts(true);
assert!(load_combine_queued_prompts());
set_combine_queued_prompts(false);
assert!(!load_combine_queued_prompts());
})
.join()
.unwrap();
}
#[test]
fn set_then_load_round_trips_simple_mode() {
std::thread::spawn(|| {

View file

@ -367,7 +367,7 @@ impl ClipboardFeedback {
Self::VsCodeSshNonAscii => {
"Copied. VS Code over SSH may garble non-ASCII; use /minimal if needed."
}
Self::FailedRemote | Self::Failed => "Copy failed. Try /terminal-setup or /minimal.",
Self::FailedRemote | Self::Failed => "Copy failed. Try /doctor or /minimal.",
}
}
@ -2064,14 +2064,14 @@ mod tests {
(
ClipboardFeedback::FailedRemote,
ClipboardDelivery::Failed,
"Copy failed. Try /terminal-setup or /minimal.",
"Copy failed. Try /doctor or /minimal.",
"failed_remote",
120,
),
(
ClipboardFeedback::Failed,
ClipboardDelivery::Failed,
"Copy failed. Try /terminal-setup or /minimal.",
"Copy failed. Try /doctor or /minimal.",
"failed",
120,
),

View file

@ -135,7 +135,7 @@ pub fn token_arrow() -> &'static str {
/// U+25CE BULLSEYE, U+25C9 FISHEYE, U+25CE BULLSEYE) normally; a 1-column
/// dot pulse (`·`, `○`, `•`, `○`) on legacy ConHost.
///
/// Animates the "watching · N monitors" cue in the turn-status line: a
/// Animates the "N monitors still running" cue in the turn-status line: a
/// concentric circle that breathes open → shut like a scanning scope. Of
/// the fancy frames only the white circle `○` (U+25CB, CP437 `0x09`) is
/// part of CP437 — the bullseye `◎` and fisheye `◉` live in the Geometric

View file

@ -2,8 +2,8 @@
//!
//! Classifies keyboard delivery semantics so input-handling code can consume one struct
//! instead of branching on brand. The classification depends on the
//! current `HostOs`, queried internally — today only macOS rows are
//! populated. Extend [`KeyboardCapabilities`] with new fields (paste
//! host OS — today only macOS rows are populated. Extend
//! [`KeyboardCapabilities`] with new fields (paste
//! protocol, focus reporting, custom escapes) instead of adding more
//! `match self.brand` sites scattered through the pager.
@ -81,13 +81,18 @@ impl KeyboardCapabilities {
}
}
/// Classify keyboard capabilities for a given `(brand, os, display_server)`.
/// Classify keyboard capabilities for the current host.
///
/// Today the table is populated only for macOS; other OSes return the
/// default (all-`Unknown`). When a Linux/Windows probe lands, add a
/// per-OS arm here rather than forking the function.
pub fn keyboard_capabilities(brand: TerminalName) -> KeyboardCapabilities {
match HostOs::current() {
keyboard_capabilities_for_host(brand, HostOs::current())
}
/// Classify keyboard capabilities for explicit host evidence.
pub fn keyboard_capabilities_for_host(brand: TerminalName, host: HostOs) -> KeyboardCapabilities {
match host {
HostOs::Macos => macos_capabilities(brand),
HostOs::Linux | HostOs::Windows | HostOs::Other => KeyboardCapabilities::default(),
}

View file

@ -4,7 +4,6 @@
//! Pure env-map helpers (`detect_*_from_env`) enable full matrix testing.
use std::collections::HashMap;
use std::process::Command;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
@ -16,6 +15,7 @@ pub mod image;
pub mod keyboard;
pub mod overlay;
pub(crate) mod probe;
pub mod tmux_probe;
pub mod xtversion;
pub use embedded_editor::{EmbeddedEditor, embedded_editor_from_env};
@ -23,7 +23,10 @@ pub use hyperlinks::{
HyperlinkCapabilities, Osc8Support, SchemeFilter, SetDefaultCursor, SetPointerCursor,
hyperlink_capabilities,
};
pub use keyboard::{KeyboardCapabilities, ModifierDelivery, ModifierFate, keyboard_capabilities};
pub use keyboard::{
KeyboardCapabilities, ModifierDelivery, ModifierFate, keyboard_capabilities,
keyboard_capabilities_for_host,
};
#[cfg(test)]
mod test;
@ -64,29 +67,6 @@ pub fn take_kitty_flags_pushed() -> bool {
KITTY_FLAGS_PUSHED.swap(false, Ordering::AcqRel)
}
/// Run `tmux show-option -gqv <option>` and return the trimmed value,
/// or `None` if the subprocess fails or returns empty / whitespace.
/// Stderr is suppressed so startup probes don't leak shell noise.
pub fn tmux_show_option(option: &str) -> Option<String> {
let mut cmd = Command::new("tmux");
cmd.args(["show-option", "-gqv", option])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
xai_tty_utils::detach_std_command(&mut cmd);
let output = cmd.output().ok()?;
parse_tmux_show_option_output(output.status.success(), &output.stdout)
}
/// Pure post-processing for `tmux show-option`: collapses subprocess
/// failure, empty stdout, and whitespace-only stdout to `None`.
pub fn parse_tmux_show_option_output(status_success: bool, stdout: &[u8]) -> Option<String> {
if !status_success {
return None;
}
let val = String::from_utf8_lossy(stdout).trim().to_string();
if val.is_empty() { None } else { Some(val) }
}
/// Known terminal emulator categories.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, strum::Display)]
pub enum TerminalName {
@ -639,6 +619,23 @@ pub fn terminal_context() -> &'static TerminalContext {
TERMINAL_CONTEXT.get_or_init(detect_terminal_context)
}
/// Detect terminal environment facts without any live tmux subprocesses.
///
/// Standalone diagnostics use this so an unhealthy tmux server cannot block
/// before the diagnostic runner has a chance to report unavailable evidence.
pub fn standalone_terminal_context() -> TerminalContext {
standalone_terminal_context_from_env(&collect_process_env(), HostOs::current())
}
fn standalone_terminal_context_from_env(
env: &HashMap<String, String>,
host: HostOs,
) -> TerminalContext {
let mut ctx = build_terminal_context_from_env(env);
ctx.brand = refine_unknown_brand_for_host(ctx.brand, host);
ctx
}
/// Build a [`TerminalContext`] from the current process environment.
fn detect_terminal_context() -> TerminalContext {
let env = collect_process_env();
@ -1020,70 +1017,24 @@ pub enum AltScreenMode {
/// Detect whether the current tmux session is in control mode.
///
/// tmux control mode is detected by checking the `client_flags` on the
/// current client. In control mode, the flags contain "control-mode".
///
/// Returns `false` when not inside tmux or when the query fails.
pub fn detect_tmux_control_mode(ctx: &TerminalContext) -> bool {
if ctx.multiplexer != MultiplexerKind::Tmux {
return false;
}
detect_tmux_control_mode_subprocess()
}
/// Subprocess-based control-mode detection.
///
/// Queries `tmux display-message -p "#{client_flags}"` and checks whether
/// the output contains `"control-mode"`.
fn detect_tmux_control_mode_subprocess() -> bool {
let mut cmd = std::process::Command::new("tmux");
cmd.args(["display-message", "-p", "#{client_flags}"])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
xai_tty_utils::detach_std_command(&mut cmd);
cmd.output()
.ok()
.and_then(|out| {
if out.status.success() {
let flags = String::from_utf8_lossy(&out.stdout);
Some(flags.contains("control-mode"))
} else {
None
}
})
tmux_probe::query_control_mode()
.into_option()
.unwrap_or(false)
}
/// Detect the tmux server version by running `tmux -V`.
///
/// Returns the trimmed version string (e.g. `"tmux 3.4"`) on success,
/// or `None` when not inside tmux or when the subprocess fails.
/// Only call this when `ctx.is_tmux_backed()` is true.
pub fn detect_tmux_version() -> Option<String> {
let mut cmd = std::process::Command::new("tmux");
cmd.arg("-V")
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
xai_tty_utils::detach_std_command(&mut cmd);
cmd.output().ok().and_then(|out| {
if out.status.success() {
let version = String::from_utf8_lossy(&out.stdout).trim().to_owned();
if version.is_empty() {
None
} else {
Some(version)
}
} else {
None
}
})
tmux_probe::query_version().into_option()
}
/// Trimmed value of tmux's global `extended-keys` option, or `None` if
/// the subprocess fails or the option is unset / empty. Only call this
/// when `ctx.is_tmux_backed()` is true.
/// Trimmed value of tmux's global `extended-keys` option.
pub fn detect_tmux_extended_keys() -> Option<String> {
tmux_show_option("extended-keys")
tmux_probe::query_option("extended-keys").into_option()
}
/// Parse major.minor from a plain semver-ish string like `"3.6.0"` or `"1.2"`.

View file

@ -472,6 +472,15 @@ fn tmux_meta_empty_outside_tmux() {
// -- build_terminal_context_from_env (integration) ------------------------
#[test]
fn standalone_context_does_not_run_live_tmux_queries() {
let env = env_from(&[("TMUX", "/tmp/definitely-missing-tmux-server")]);
let ctx = standalone_terminal_context_from_env(&env, crate::host::HostOs::Linux);
assert_eq!(ctx.multiplexer, MultiplexerKind::Tmux);
assert_eq!(ctx.tmux_version, None);
assert_eq!(ctx.tmux_extended_keys, None);
}
#[test]
fn context_plain_terminal() {
let env = env_from(&[("TERM_PROGRAM", "Ghostty")]);

View file

@ -0,0 +1,274 @@
//! Shared tmux command protocol and result parsing.
use std::process::{Command, Stdio};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TmuxCommand<'a> {
Version,
OptionValue(&'a str),
OptionSupport(&'a str),
ControlMode,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct TmuxCommandOutput {
status_success: bool,
stdout: Vec<u8>,
stderr: Vec<u8>,
}
trait TmuxCommandRunner {
fn run(&self, command: TmuxCommand<'_>) -> Result<TmuxCommandOutput, String>;
}
struct LiveTmuxCommandRunner;
impl TmuxCommandRunner for LiveTmuxCommandRunner {
fn run(&self, command: TmuxCommand<'_>) -> Result<TmuxCommandOutput, String> {
let output = build_tmux_command(command)
.output()
.map_err(|error| format!("failed to run tmux: {error}"))?;
Ok(TmuxCommandOutput {
status_success: output.status.success(),
stdout: output.stdout,
stderr: output.stderr,
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TmuxQueryResult<T> {
Available(T),
Unsupported,
Unavailable,
Error(String),
}
impl<T> TmuxQueryResult<T> {
pub fn into_option(self) -> Option<T> {
match self {
Self::Available(value) => Some(value),
Self::Unsupported | Self::Unavailable | Self::Error(_) => None,
}
}
}
pub fn query_version() -> TmuxQueryResult<String> {
query_version_with(&LiveTmuxCommandRunner)
}
fn query_version_with(runner: &dyn TmuxCommandRunner) -> TmuxQueryResult<String> {
parse_value(runner.run(TmuxCommand::Version))
}
pub fn query_option(option: &str) -> TmuxQueryResult<String> {
query_option_with(&LiveTmuxCommandRunner, option)
}
fn query_option_with(runner: &dyn TmuxCommandRunner, option: &str) -> TmuxQueryResult<String> {
parse_value(runner.run(TmuxCommand::OptionValue(option)))
}
pub fn query_option_support(option: &str) -> TmuxQueryResult<()> {
query_option_support_with(&LiveTmuxCommandRunner, option)
}
fn query_option_support_with(runner: &dyn TmuxCommandRunner, option: &str) -> TmuxQueryResult<()> {
match runner.run(TmuxCommand::OptionSupport(option)) {
Ok(output) if output.status_success => TmuxQueryResult::Available(()),
Ok(output) if stderr_identifies_unknown_option(&output.stderr, option) => {
TmuxQueryResult::Unsupported
}
Ok(_) => TmuxQueryResult::Unavailable,
Err(error) => TmuxQueryResult::Error(error),
}
}
pub fn query_control_mode() -> TmuxQueryResult<bool> {
query_control_mode_with(&LiveTmuxCommandRunner)
}
fn query_control_mode_with(runner: &dyn TmuxCommandRunner) -> TmuxQueryResult<bool> {
match runner.run(TmuxCommand::ControlMode) {
Ok(output) if output.status_success => TmuxQueryResult::Available(
String::from_utf8_lossy(&output.stdout).contains("control-mode"),
),
Ok(_) => TmuxQueryResult::Unavailable,
Err(error) => TmuxQueryResult::Error(error),
}
}
fn build_tmux_command(command: TmuxCommand<'_>) -> Command {
let mut cmd = Command::new("tmux");
match command {
TmuxCommand::Version => {
cmd.arg("-V").stdout(Stdio::piped()).stderr(Stdio::null());
}
TmuxCommand::OptionValue(option) => {
cmd.args(["show-option", "-gqv", option])
.stdout(Stdio::piped())
.stderr(Stdio::null());
}
TmuxCommand::OptionSupport(option) => {
cmd.args(["show-option", "-gv", option])
.stdout(Stdio::null())
.stderr(Stdio::piped());
}
TmuxCommand::ControlMode => {
cmd.args(["display-message", "-p", "#{client_flags}"])
.stdout(Stdio::piped())
.stderr(Stdio::null());
}
}
cmd.stdin(Stdio::null()).envs(xai_tty_utils::pager_env());
xai_tty_utils::detach_std_command(&mut cmd);
cmd
}
fn parse_value(output: Result<TmuxCommandOutput, String>) -> TmuxQueryResult<String> {
match output {
Ok(output) if output.status_success => {
let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if value.is_empty() {
TmuxQueryResult::Unavailable
} else {
TmuxQueryResult::Available(value)
}
}
Ok(_) => TmuxQueryResult::Unavailable,
Err(error) => TmuxQueryResult::Error(error),
}
}
fn stderr_identifies_unknown_option(stderr: &[u8], option: &str) -> bool {
let invalid = format!("invalid option: {option}");
let unknown = format!("unknown option: {option}");
String::from_utf8_lossy(stderr)
.lines()
.any(|line| matches!(line.trim(), value if value == invalid || value == unknown))
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use super::*;
struct FakeRunner {
output: Result<TmuxCommandOutput, String>,
calls: RefCell<Vec<String>>,
}
impl FakeRunner {
fn output(status_success: bool, stdout: &[u8], stderr: &[u8]) -> Self {
Self {
output: Ok(TmuxCommandOutput {
status_success,
stdout: stdout.to_vec(),
stderr: stderr.to_vec(),
}),
calls: RefCell::new(Vec::new()),
}
}
}
impl TmuxCommandRunner for FakeRunner {
fn run(&self, command: TmuxCommand<'_>) -> Result<TmuxCommandOutput, String> {
self.calls.borrow_mut().push(match command {
TmuxCommand::Version => "version".to_owned(),
TmuxCommand::OptionValue(option) => format!("value:{option}"),
TmuxCommand::OptionSupport(option) => format!("support:{option}"),
TmuxCommand::ControlMode => "control-mode".to_owned(),
});
self.output.clone()
}
}
#[test]
fn command_protocol_uses_exact_argv_and_pager_env() {
let cases = [
(TmuxCommand::Version, vec!["-V"]),
(
TmuxCommand::OptionValue("set-clipboard"),
vec!["show-option", "-gqv", "set-clipboard"],
),
(
TmuxCommand::OptionSupport("allow-passthrough"),
vec!["show-option", "-gv", "allow-passthrough"],
),
(
TmuxCommand::ControlMode,
vec!["display-message", "-p", "#{client_flags}"],
),
];
for (request, args) in cases {
let cmd = build_tmux_command(request);
assert_eq!(cmd.get_program(), OsStr::new("tmux"));
assert_eq!(cmd.get_args().collect::<Vec<_>>(), args);
let actual: HashMap<OsString, Option<OsString>> = cmd
.get_envs()
.map(|(key, value)| (key.to_owned(), value.map(OsStr::to_owned)))
.collect();
let expected: HashMap<OsString, Option<OsString>> = xai_tty_utils::pager_env()
.into_iter()
.map(|(key, value)| (key.into(), Some(value.into())))
.collect();
assert_eq!(actual, expected);
}
}
#[test]
fn value_and_control_queries_use_the_injected_runner() {
let runner = FakeRunner::output(true, b" on\n", b"");
assert_eq!(
query_option_with(&runner, "set-clipboard"),
TmuxQueryResult::Available("on".to_owned())
);
assert_eq!(runner.calls.into_inner(), ["value:set-clipboard"]);
let runner = FakeRunner::output(true, b"control-mode,utf8\n", b"");
assert_eq!(
query_control_mode_with(&runner),
TmuxQueryResult::Available(true)
);
assert_eq!(runner.calls.into_inner(), ["control-mode"]);
}
#[test]
fn nonzero_and_execution_failure_remain_fail_open_facts() {
let runner = FakeRunner::output(false, b"on", b"server unavailable");
assert_eq!(
query_option_with(&runner, "set-clipboard"),
TmuxQueryResult::Unavailable
);
let runner = FakeRunner {
output: Err("spawn failed".to_owned()),
calls: RefCell::new(Vec::new()),
};
assert_eq!(
query_version_with(&runner),
TmuxQueryResult::Error("spawn failed".to_owned())
);
}
#[test]
fn support_query_accepts_both_known_spellings_only() {
for stderr in [
b"invalid option: allow-passthrough\n".as_slice(),
b"unknown option: allow-passthrough\n".as_slice(),
] {
let runner = FakeRunner::output(false, b"", stderr);
assert_eq!(
query_option_support_with(&runner, "allow-passthrough"),
TmuxQueryResult::Unsupported
);
}
let runner = FakeRunner::output(false, b"", b"no server running\n");
assert_eq!(
query_option_support_with(&runner, "allow-passthrough"),
TmuxQueryResult::Unavailable
);
}
}

View file

@ -121,6 +121,85 @@ fn detect_raw() -> ColorLevel {
})
}
/// Standalone diagnostic color evidence.
///
/// This never consults stdout, because `grok doctor --json` is commonly piped.
/// Stderr or an independently opened controlling terminal is sufficient
/// evidence that the process is diagnosing that terminal; a fully headless
/// invocation is honest about having no color evidence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StandaloneColorEvidence {
Available(ColorLevel),
Unavailable,
}
pub fn standalone(terminal: TerminalName) -> StandaloneColorEvidence {
use std::io::IsTerminal;
standalone_from_env(
&crate::host::collect_unicode_env(),
std::io::stderr().is_terminal(),
controlling_terminal_available(),
terminal,
)
}
fn controlling_terminal_available() -> bool {
#[cfg(unix)]
{
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
.is_ok()
}
#[cfg(windows)]
{
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("CONIN$")
.is_ok()
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn standalone_from_env(
env: &std::collections::HashMap<String, String>,
stderr_is_terminal: bool,
controlling_terminal: bool,
terminal: TerminalName,
) -> StandaloneColorEvidence {
if env.contains_key("NO_COLOR") {
return StandaloneColorEvidence::Available(ColorLevel::None);
}
if !stderr_is_terminal && !controlling_terminal {
return StandaloneColorEvidence::Unavailable;
}
let colorterm = env.get("COLORTERM").map(|value| value.to_ascii_lowercase());
if colorterm
.as_deref()
.is_some_and(|value| value == "truecolor" || value == "24bit")
|| terminal_supports_truecolor_brand(terminal)
{
return StandaloneColorEvidence::Available(ColorLevel::TrueColor);
}
let term = env
.get("TERM")
.map(|value| value.to_ascii_lowercase())
.unwrap_or_default();
if term.contains("256color") {
StandaloneColorEvidence::Available(ColorLevel::Ansi256)
} else if term.is_empty() || term == "dumb" {
StandaloneColorEvidence::Unavailable
} else {
StandaloneColorEvidence::Available(ColorLevel::Basic)
}
}
/// Return the cached color level (calls [`detect`] if not yet initialized).
pub fn get() -> ColorLevel {
detect()
@ -175,8 +254,12 @@ pub fn quantize(color: Color) -> Color {
/// this fallback our themes get quantized to the 16-color ANSI palette there
/// and the subtle bg/border/muted gradations collapse onto each other.
fn terminal_supports_truecolor() -> bool {
terminal_supports_truecolor_brand(terminal_context().brand)
}
fn terminal_supports_truecolor_brand(terminal: TerminalName) -> bool {
if matches!(
terminal_context().brand,
terminal,
TerminalName::Iterm2
| TerminalName::Ghostty
| TerminalName::Kitty
@ -270,6 +353,79 @@ fn rgb_to_ansi16(r: u8, g: u8, b: u8) -> Color {
mod tests {
use super::*;
fn env(pairs: &[(&str, &str)]) -> std::collections::HashMap<String, String> {
pairs
.iter()
.map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
.collect()
}
#[test]
fn standalone_color_uses_stderr_terminal_not_stdout() {
assert_eq!(
standalone_from_env(
&env(&[("COLORTERM", "truecolor")]),
true,
false,
TerminalName::Unknown,
),
StandaloneColorEvidence::Available(ColorLevel::TrueColor)
);
assert_eq!(
standalone_from_env(
&env(&[("TERM", "xterm-256color")]),
true,
false,
TerminalName::Unknown,
),
StandaloneColorEvidence::Available(ColorLevel::Ansi256)
);
assert_eq!(
standalone_from_env(
&env(&[("COLORTERM", "truecolor")]),
false,
false,
TerminalName::Ghostty,
),
StandaloneColorEvidence::Unavailable
);
assert_eq!(
standalone_from_env(
&env(&[("NO_COLOR", "1")]),
false,
false,
TerminalName::Ghostty,
),
StandaloneColorEvidence::Available(ColorLevel::None)
);
}
#[test]
fn standalone_color_uses_controlling_terminal_when_stderr_is_piped() {
assert_eq!(
standalone_from_env(
&env(&[("TERM", "xterm-256color")]),
false,
true,
TerminalName::Unknown,
),
StandaloneColorEvidence::Available(ColorLevel::Ansi256)
);
}
#[test]
fn standalone_color_uses_known_terminal_brand_without_colorterm() {
assert_eq!(
standalone_from_env(
&env(&[("TERM", "xterm")]),
true,
false,
TerminalName::WezTerm,
),
StandaloneColorEvidence::Available(ColorLevel::TrueColor)
);
}
#[test]
fn truecolor_passes_through() {
let rgb = Color::Rgb(122, 162, 247);

View file

@ -198,10 +198,31 @@ pub fn parse_schedule_interval_secs(human: &str) -> Option<u64> {
Some(n * secs_per)
}
/// Group a count's digits with commas for display: `1234567` → `"1,234,567"`.
pub fn group_thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn group_thousands_inserts_separators() {
assert_eq!(group_thousands(0), "0");
assert_eq!(group_thousands(999), "999");
assert_eq!(group_thousands(1_000), "1,000");
assert_eq!(group_thousands(1_234_567), "1,234,567");
}
#[test]
fn subsecond() {
assert_eq!(format_duration(Duration::from_millis(500)), "0.5s");