Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(statusline): add context window gauge for Claude Code (#840)
Maximilian Roos13310657b310
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 24f80defd..62bc92300 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -74,7 +74,8 @@ repos:# select.rs: skim API's selected.output() is not Command::output()# tests/benches: test utilities run commands directly# src/config/{test,expansion,mod,user}.rs: TestRepo test fixtures use git init directly- exclude: '^(src/shell_exec\.rs|src/commands/select/|src/config/(test|expansion|mod|user)\.rs|tests/|benches/)'+ # src/styling/mod.rs: terminal width detection probes should be silent/quick+ exclude: '^(src/shell_exec\.rs|src/commands/select/|src/config/(test|expansion|mod|user)\.rs|src/styling/mod\.rs|tests/|benches/)'ci:# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex b680a5f5e..36e4d22dd 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -17,30 +17,14 @@ use worktrunk::styling::{fix_dim_after_color_reset, get_terminal_width, truncateuse super::list::{self, CollectOptions, StatuslineSegment};-#[derive(serde::Deserialize, Default)]-struct ClaudeCodeContextJson {- #[serde(default)]- workspace: ClaudeCodeWorkspace,- #[serde(default)]- model: ClaudeCodeModel,-}--#[derive(serde::Deserialize, Default)]-struct ClaudeCodeWorkspace {- current_dir: Option<String>,-}--#[derive(serde::Deserialize, Default)]-struct ClaudeCodeModel {- display_name: Option<String>,-}-/// Claude Code context parsed from stdin JSONstruct ClaudeCodeContext {/// Working directory from `.workspace.current_dir`current_dir: String,/// Model name from `.model.display_name`model_name: Option<String>,+ /// Context window usage percentage from `.context_window.used_percentage`+ context_used_percentage: Option<f64>,}impl ClaudeCodeContext {@@ -51,16 +35,27 @@ impl ClaudeCodeContext {return None;}- let json: ClaudeCodeContextJson = serde_json::from_str(input).ok()?;- let current_dir = json- .workspace- .current_dir- .unwrap_or_else(|| ".".to_string());- let model_name = json.model.display_name;+ let v: serde_json::Value = serde_json::from_str(input).ok()?;++ let current_dir = v+ .pointer("/workspace/current_dir")+ .and_then(|v| v.as_str())+ .unwrap_or(".")+ .to_string();++ let model_name = v+ .pointer("/model/display_name")+ .and_then(|v| v.as_str())+ .map(String::from);++ let context_used_percentage = v+ .pointer("/context_window/used_percentage")+ .and_then(|v| v.as_f64());Some(Self {current_dir,model_name,+ context_used_percentage,})}@@ -127,24 +122,54 @@ const PRIORITY_DIRECTORY: u8 = 0;/// Same as Branch - model identity is important.const PRIORITY_MODEL: u8 = 1;+/// Priority for context gauge segment (Claude Code only).+/// Lower priority than model (higher number = dropped first when truncating).+const PRIORITY_CONTEXT: u8 = 2;++/// Format context usage as a moon phase gauge.+///+/// Uses moon phase emoji to show fill level (waning - gets darker as context fills).+/// Thresholds use exponential halving where each range is half the previous.+/// Formula: 5 buckets with ratio 16:8:4:2:1, normalized to 100% (sum = 31).+/// - π (0-51%) - full moon (plenty of room) - 16/31 β 52%+/// - π (52-77%) - waning gibbous - 8/31 β 26%+/// - π (78-90%) - last quarter - 4/31 β 13%+/// - π (91-97%) - waning crescent - 2/31 β 7%+/// - π (98-100%) - new moon (nearly full, warning) - 1/31 β 3%+fn format_context_gauge(percentage: f64) -> String {+ // Clamp to valid range to handle edge cases (negative or >100%)+ let clamped = percentage.clamp(0.0, 100.0);+ let symbol = match clamped as u32 {+ 0..=51 => 'π',+ 52..=77 => 'π',+ 78..=90 => 'π',+ 91..=97 => 'π',+ _ => 'π',+ };+ // Display the original percentage (not clamped) for transparency+ format!("{symbol} {:.0}%", percentage)+}+/// Run the statusline command.////// Output uses `println!` for raw stdout (bypasses anstream color detection)./// Shell prompts (PS1) and Claude Code always expect ANSI codes.pub fn run(claude_code: bool) -> Result<()> {// Get context - either from stdin (claude-code mode) or current directory- let (cwd, model_name) = if claude_code {+ let (cwd, model_name, context_used_percentage) = if claude_code {let ctx = ClaudeCodeContext::from_stdin();let current_dir = ctx.as_ref().map(|c| c.current_dir.clone()).unwrap_or_else(|| env::current_dir().unwrap_or_default().display().to_string());- let model = ctx.and_then(|c| c.model_name);- (Path::new(¤t_dir).to_path_buf(), model)+ let model = ctx.as_ref().and_then(|c| c.model_name.clone());+ let context_pct = ctx.and_then(|c| c.context_used_percentage);+ (Path::new(¤t_dir).to_path_buf(), model, context_pct)} else {(env::current_dir().context("Failed to get current directory")?,None,+ None,)};@@ -188,6 +213,14 @@ pub fn run(claude_code: bool) -> Result<()> {segments.push(StatuslineSegment::new(format!("| {model}"), PRIORITY_MODEL));}+ // Context gauge (claude-code mode only) - priority 2 (placed after model)+ if let Some(pct) = context_used_percentage {+ segments.push(StatuslineSegment::new(+ format_context_gauge(pct),+ PRIORITY_CONTEXT,+ ));+ }+if segments.is_empty() {return Ok(());}@@ -472,4 +505,80 @@ mod tests {original_visible.len());}++ #[test]+ fn test_context_gauge_formatting() {+ // Test boundary values for each moon phase symbol (waning - darker as context fills)+ // Thresholds use exponential halving: ratio 16:8:4:2:1, normalized to 100%+ assert_eq!(format_context_gauge(0.0), "π 0%");+ assert_eq!(format_context_gauge(51.0), "π 51%");+ assert_eq!(format_context_gauge(52.0), "π 52%");+ assert_eq!(format_context_gauge(77.0), "π 77%");+ assert_eq!(format_context_gauge(78.0), "π 78%");+ assert_eq!(format_context_gauge(90.0), "π 90%");+ assert_eq!(format_context_gauge(91.0), "π 91%");+ assert_eq!(format_context_gauge(97.0), "π 97%");+ assert_eq!(format_context_gauge(98.0), "π 98%");+ assert_eq!(format_context_gauge(100.0), "π 100%");+ }++ #[test]+ fn test_context_gauge_fractional_percentages() {+ // Fractional values are rounded (per {:.0} format specifier)+ // Rust uses banker's rounding (round half to even)+ assert_eq!(format_context_gauge(42.7), "π 43%"); // 43% is in 0-51% range+ assert_eq!(format_context_gauge(0.4), "π 0%");+ assert_eq!(format_context_gauge(0.5), "π 0%"); // banker's rounding: 0.5 rounds to even (0)+ assert_eq!(format_context_gauge(1.5), "π 2%"); // banker's rounding: 1.5 rounds to even (2)+ assert_eq!(format_context_gauge(99.9), "π 100%");+ }++ #[test]+ fn test_context_gauge_edge_cases() {+ // Negative values: symbol clamps to bright (low usage), but display shows original value+ assert_eq!(format_context_gauge(-5.0), "π -5%");+ assert_eq!(format_context_gauge(-0.1), "π -0%"); // rounds to -0%++ // Values over 100%: symbol clamps to dark (high usage), but display shows original value+ assert_eq!(format_context_gauge(105.0), "π 105%");+ assert_eq!(format_context_gauge(150.0), "π 150%");+ }++ #[test]+ fn test_claude_code_context_parse_with_context_window() {+ let json = r#"{+ "workspace": {"current_dir": "/tmp/test"},+ "model": {"display_name": "Opus"},+ "context_window": {"used_percentage": 42.5}+ }"#;++ let ctx = ClaudeCodeContext::parse(json).expect("should parse");+ assert_eq!(ctx.current_dir, "/tmp/test");+ assert_eq!(ctx.model_name, Some("Opus".to_string()));+ assert_eq!(ctx.context_used_percentage, Some(42.5));+ }++ #[test]+ fn test_claude_code_context_parse_missing_context_window() {+ // context_window is optional+ let json = r#"{+ "workspace": {"current_dir": "/tmp/test"},+ "model": {"display_name": "Opus"}+ }"#;++ let ctx = ClaudeCodeContext::parse(json).expect("should parse");+ assert_eq!(ctx.context_used_percentage, None);+ }++ #[test]+ fn test_claude_code_context_parse_context_window_missing_percentage() {+ // context_window can exist without used_percentage+ let json = r#"{+ "workspace": {"current_dir": "/tmp/test"},+ "context_window": {}+ }"#;++ let ctx = ClaudeCodeContext::parse(json).expect("should parse");+ assert_eq!(ctx.context_used_percentage, None);+ }}diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex c2ae5c30b..04885734e 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -91,10 +91,70 @@ pub fn get_terminal_width() -> usize {return width;}+ // Try parent TTY detection (Unix only)+ // This is used when running in a subprocess without direct TTY access,+ // such as Claude Code's statusline hook.+ #[cfg(unix)]+ if let Some(width) = detect_parent_tty_width() {+ return width;+ }+// Can't detect width β don't truncate, let the consumer handle itusize::MAX}+/// Detect terminal width by walking up the process tree to find a TTY.+///+/// This is a fallback for subprocesses (like Claude Code hooks) that don't have+/// direct TTY access. Walks up to 10 parent processes looking for one with a TTY,+/// then queries that TTY's size.+///+/// Returns 80% of the detected width to reserve space for Claude Code's UI messages+/// (like "Approaching context limit").+#[cfg(unix)]+fn detect_parent_tty_width() -> Option<usize> {+ use std::process::Command;++ let mut pid = std::process::id().to_string();++ for _ in 0..10 {+ let output = Command::new("ps")+ .args(["-o", "ppid=,tty=", "-p", &pid])+ .output()+ .ok()?;++ let info = String::from_utf8_lossy(&output.stdout);+ let mut parts = info.split_whitespace();+ let ppid = parts.next()?;+ let tty = parts.next()?;++ // Valid TTY found (not "?" or "??")+ if !tty.is_empty() && tty != "?" && tty != "??" {+ // Query TTY size using stty+ let size = Command::new("sh")+ .args(["-c", &format!("stty size < /dev/{tty}")])+ .output()+ .ok()?;++ let cols = String::from_utf8_lossy(&size.stdout)+ .split_whitespace()+ .nth(1)?+ .parse::<usize>()+ .ok()?;++ // Reserve 20% for Claude Code UI messages+ return Some(cols * 80 / 100);+ }++ if ppid == "1" || ppid == "0" {+ break;+ }+ pid = ppid.to_string();+ }++ None+}+/// Calculate visual width of a string, ignoring ANSI escape codes////// Uses unicode-width for proper handling of wide characters (CJK, emoji).diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rsindex cedfb0b7b..7fff88c9d 100644--- a/tests/integration_tests/statusline.rs+++ b/tests/integration_tests/statusline.rs@@ -201,6 +201,85 @@ fn test_statusline_claude_code_with_model(repo: TestRepo) {});}+// --- Context Gauge Tests ---++#[rstest]+fn test_statusline_claude_code_with_context_gauge(repo: TestRepo) {+ let escaped_path = escape_path_for_json(repo.root_path());+ let json = format!(+ r#"{{+ "workspace": {{"current_dir": "{escaped_path}"}},+ "model": {{"display_name": "Opus"}},+ "context_window": {{"used_percentage": 42}}+ }}"#,+ );++ let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ claude_code_snapshot_settings().bind(|| {+ assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus π 42%");+ });+}++#[rstest]+fn test_statusline_claude_code_context_gauge_low(repo: TestRepo) {+ let escaped_path = escape_path_for_json(repo.root_path());+ let json = format!(+ r#"{{+ "workspace": {{"current_dir": "{escaped_path}"}},+ "model": {{"display_name": "Opus"}},+ "context_window": {{"used_percentage": 5}}+ }}"#,+ );++ let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ claude_code_snapshot_settings().bind(|| {+ assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus π 5%");+ });+}++#[rstest]+fn test_statusline_claude_code_context_gauge_high(repo: TestRepo) {+ let escaped_path = escape_path_for_json(repo.root_path());+ let json = format!(+ r#"{{+ "workspace": {{"current_dir": "{escaped_path}"}},+ "model": {{"display_name": "Opus"}},+ "context_window": {{"used_percentage": 98}}+ }}"#,+ );++ let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ claude_code_snapshot_settings().bind(|| {+ assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus π 98%");+ });+}++#[rstest]+fn test_statusline_claude_code_missing_context_window(repo: TestRepo) {+ // When context_window is missing, no gauge should be displayed+ let escaped_path = escape_path_for_json(repo.root_path());+ let json = format!(+ r#"{{+ "workspace": {{"current_dir": "{escaped_path}"}},+ "model": {{"display_name": "Opus"}}+ }}"#,+ );++ let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ claude_code_snapshot_settings().bind(|| {+ // No gauge symbol (βββββ) should appear+ assert!(+ !output.contains('β')+ && !output.contains('β')+ && !output.contains('β')+ && !output.contains('β')+ && !output.contains('β'),+ "No gauge should appear when context_window is missing: {output}"+ );+ assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus");+ });+}+// --- Directive Mode Tests ---// Note: With the new WORKTRUNK_DIRECTIVE_FILE architecture, data output (like statusline)// still goes to stdout. The directive file is only used for shell directives like