Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(statusline): add Claude Code rate-limit pace segment (#2899)

Maximilian Roose22ed71282e4
diff --git a/docs/content/claude-code.md b/docs/content/claude-code.md
index 26a91666c..0c45c564a 100644
--- a/docs/content/claude-code.md
+++ b/docs/content/claude-code.md
@@ -109,9 +109,9 @@ On session exit the worktree is offered for removal via the `WorktreeRemove` hoo
`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. When the CI status cache is stale, this fetches from the network — typically 1–2 seconds — making it suitable for async statuslines but too slow for synchronous shell prompts. If a faster version would be helpful, please [open an issue](https://github.com/max-sixty/worktrunk/issues).
-<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> | Opus 🌔 65%</code>
+<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> Opus 🌔65% <span style='color:#a70'>1.4×pace(10am–3pm)</span></code>
-When Claude Code provides context window usage via stdin JSON, a moon phase gauge appears (🌕→🌑 as context fills).
+When Claude Code provides context window usage via stdin JSON, a moon phase gauge appears (🌕→🌑 as context fills). A yellow `<n>×pace(<window>)` segment appears when Claude's 5-hour or weekly rate limit is on track to be hit before reset — `1.4×pace(10am–3pm)` reads as 1.4× the pace that would exactly fill that window.
<figure class="demo">
<picture>
diff --git a/skills/worktrunk/reference/claude-code.md b/skills/worktrunk/reference/claude-code.md
index a8fe8cb15..668d26435 100644
--- a/skills/worktrunk/reference/claude-code.md
+++ b/skills/worktrunk/reference/claude-code.md
@@ -111,9 +111,9 @@ On session exit the worktree is offered for removal via the `WorktreeRemove` hoo
`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. When the CI status cache is stale, this fetches from the network — typically 1–2 seconds — making it suitable for async statuslines but too slow for synchronous shell prompts. If a faster version would be helpful, please [open an issue](https://github.com/max-sixty/worktrunk/issues).
-<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> | Opus 🌔 65%</code>
+<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> Opus 🌔65% <span style='color:#a70'>1.4×pace(10am–3pm)</span></code>
-When Claude Code provides context window usage via stdin JSON, a moon phase gauge appears (🌕→🌑 as context fills).
+When Claude Code provides context window usage via stdin JSON, a moon phase gauge appears (🌕→🌑 as context fills). A yellow `<n>×pace(<window>)` segment appears when Claude's 5-hour or weekly rate limit is on track to be hit before reset — `1.4×pace(10am–3pm)` reads as 1.4× the pace that would exactly fill that window.
Add to `~/.claude/settings.json`:
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 70d8d270d..4acbd734d 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -31,6 +31,22 @@ struct ClaudeCodeContext {
model_name: Option<String>,
/// Context window usage percentage from `.context_window.used_percentage`
context_used_percentage: Option<f64>,
+ /// Rate-limit window readings from `.rate_limits.{five_hour,seven_day}`.
+ /// Empty when absent (non-subscribers, or before the first API response).
+ rate_limits: Vec<RateLimitReading>,
+}
+
+/// A single rate-limit window reading parsed from Claude Code's JSON.
+#[derive(Clone, Debug)]
+struct RateLimitReading {
+ /// 0–100 from `.rate_limits.<window>.used_percentage`.
+ used_percentage: f64,
+ /// Unix epoch seconds from `.rate_limits.<window>.resets_at`.
+ resets_at: i64,
+ /// Window length in seconds (5h or 7d).
+ window_secs: i64,
+ /// Prior parameters for this window.
+ priors: &'static WindowPriors,
}
impl ClaudeCodeContext {
@@ -54,10 +70,13 @@ impl ClaudeCodeContext {
.pointer("/context_window/used_percentage")
.and_then(|v| v.as_f64());
+ let rate_limits = parse_rate_limits(&v);
+
Some(Self {
current_dir,
model_name,
context_used_percentage,
+ rate_limits,
})
}
@@ -128,6 +147,297 @@ const PRIORITY_MODEL: u8 = 1;
/// Lower priority than model (higher number = dropped first when truncating).
const PRIORITY_CONTEXT: u8 = 2;
+/// Priority for the rate-limit segment (Claude Code only).
+/// Lower priority than context — drops first when the line is tight.
+const PRIORITY_RATE_LIMITS: u8 = 3;
+
+// ---------------------------------------------------------------------------
+// Rate-limit pace prediction
+//
+// Claude Code exposes two rolling rate-limit windows (5-hour and weekly) with
+// `used_percentage` and `resets_at`. We want to surface a one-line statusline
+// warning when the user is likely to actually hit the cap — *not* whenever
+// they're momentarily ahead of pace, which is normal early-window noise.
+//
+// ## The question
+//
+// Given fraction-of-limit-used `u` and fraction-of-window-elapsed `t`, what
+// is the probability that final usage `C(1) ≥ 1`?
+//
+// The naive answer is the linear projection `u/t`: alarm when `u > t`. That
+// triggers wildly early in a window — 5% used at 3% elapsed projects to
+// 167%, but you've barely sampled anything. The fix isn't a different
+// estimator; it's wrapping uncertainty around the projection so a thin slice
+// of data carries less weight than a fat one.
+//
+// ## The model
+//
+// Cumulative consumption as Brownian-with-drift:
+//
+// C(t) = λ·t + σ·W(t)
+//
+// `λ` is the user's long-run rate (λ=1 ⇒ "they'll exactly fill the window"),
+// `σ` is within-window burstiness, `W(t)` is standard Brownian motion.
+//
+// `λ` is unknown. Prior: `λ ~ N(m0, s0²)`. With `m0 ≈ 0.8` the prior says
+// "most windows finish under the cap" — that's what suppresses the
+// hair-trigger on early data.
+//
+// Observing `C(t) = u` updates the posterior on `λ` by Bayes (Gaussian on
+// Gaussian = precision-weighted blend of prior and the observed rate `u/t`).
+// The predictive distribution for `C(1)` is itself Gaussian, and the answer
+// is its upper tail at 1.0.
+//
+// ## σ for the week
+//
+// If consumption were a sum of independent bursts, `σ_7d` would be
+// `σ_5h / √(168/5) ≈ σ_5h / 6` by CLT. It isn't — busy days cluster, busy
+// weeks cluster — so `σ_7d` is only modestly below `σ_5h`. The values below
+// are calibrated by feel; with real `(u, t, resets_at)` traces logged, fit
+// them from data and delete this paragraph.
+// ---------------------------------------------------------------------------
+
+/// Prior parameters for one rate-limit window's pace prediction.
+#[derive(Debug)]
+struct WindowPriors {
+ /// Within-window volatility — residual scatter of `C(t)` around `λ·t`.
+ sigma: f64,
+ /// Prior mean rate. `m0 < 1` ⇒ we expect most windows to finish under.
+ m0: f64,
+ /// Prior std on rate. Bigger = weaker prior = data takes over sooner.
+ s0: f64,
+}
+
+const FIVE_HOUR_PRIORS: WindowPriors = WindowPriors {
+ sigma: 0.35,
+ m0: 0.8,
+ s0: 0.5,
+};
+const SEVEN_DAY_PRIORS: WindowPriors = WindowPriors {
+ sigma: 0.30,
+ m0: 0.8,
+ s0: 0.5,
+};
+
+const FIVE_HOUR_SECS: i64 = 5 * 3600;
+const SEVEN_DAY_SECS: i64 = 7 * 86400;
+
+/// Show the rate-limit segment when P(over) crosses this threshold.
+const RATE_LIMIT_P_THRESHOLD: f64 = 0.50;
+
+/// Extract any present rate-limit windows from the Claude Code JSON.
+///
+/// Both windows are independently optional: subscribers see `rate_limits`
+/// only after the first API response, and each window may be missing.
+fn parse_rate_limits(v: &serde_json::Value) -> Vec<RateLimitReading> {
+ let mut out = Vec::new();
+ for (key, window_secs, priors) in [
+ ("five_hour", FIVE_HOUR_SECS, &FIVE_HOUR_PRIORS),
+ ("seven_day", SEVEN_DAY_SECS, &SEVEN_DAY_PRIORS),
+ ] {
+ let used = v
+ .pointer(&format!("/rate_limits/{key}/used_percentage"))
+ .and_then(|x| x.as_f64());
+ let resets = v
+ .pointer(&format!("/rate_limits/{key}/resets_at"))
+ .and_then(|x| x.as_i64());
+ if let (Some(u), Some(r)) = (used, resets) {
+ out.push(RateLimitReading {
+ used_percentage: u,
+ resets_at: r,
+ window_secs,
+ priors,
+ });
+ }
+ }
+ out
+}
+
+/// Standard normal CDF via Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7).
+fn standard_normal_cdf(z: f64) -> f64 {
+ 0.5 * (1.0 + erf(z / std::f64::consts::SQRT_2))
+}
+
+/// Error function via Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7).
+///
+/// For `x ≥ 0`, with `t = 1 / (1 + p·x)`:
+///
+/// ```text
+/// erf(x) ≈ 1 − (a₁·t + a₂·t² + a₃·t³ + a₄·t⁴ + a₅·t⁵) · exp(−x²)
+/// ```
+///
+/// `p` and the `aᵢ` are numerically fit — they don't come from a closed
+/// form. For `x < 0` we use the odd symmetry `erf(−x) = −erf(x)`.
+fn erf(x: f64) -> f64 {
+ const P: f64 = 0.3275911;
+ const COEFFS: [f64; 5] = [
+ 0.254829592,
+ -0.284496736,
+ 1.421413741,
+ -1.453152027,
+ 1.061405429,
+ ];
+ let sign = x.signum();
+ let x = x.abs();
+ let t = 1.0 / (1.0 + P * x);
+ // Horner's method: build `a₁ + a₂·t + … + a₅·t⁴` inside-out, then one
+ // more multiply by `t` to get the `a₁·t + … + a₅·t⁵` we actually want.
+ let poly = COEFFS.iter().rev().fold(0.0, |acc, &c| acc * t + c) * t;
+ sign * (1.0 - poly * (-x * x).exp())
+}
+
+/// Probability that final usage hits or exceeds the limit (`C(1) ≥ 1.0`),
+/// given fraction-of-limit-used `u` and fraction-of-window-elapsed `t`.
+///
+/// See the section header above [`WindowPriors`] for the model. In short:
+/// posterior on the rate via Bayes, predictive on final usage is Gaussian,
+/// answer is its upper tail at 1.0.
+fn p_over(u: f64, t: f64, p: &WindowPriors) -> f64 {
+ // End of window: deterministic — we either crossed or we didn't.
+ if t >= 1.0 {
+ return if u >= 1.0 { 1.0 } else { 0.0 };
+ }
+ let (mean, var) = if t <= 0.0 {
+ // No data yet. Predictive collapses to the prior on `λ` plus one
+ // window's worth of process noise on top.
+ (p.m0, p.s0 * p.s0 + p.sigma * p.sigma)
+ } else {
+ // --- Bayes update on `λ` from one observation `C(t) = u` ---
+ //
+ // Both precisions live on the rate `λ`. The data precision is `t/σ²`
+ // because observing `C(t) = u` is equivalent to observing the rate
+ // `u/t` with variance `σ²/t`. The posterior is Gaussian with:
+ //
+ // post_prec = prior_prec + data_prec
+ // post_mean = (prior_prec · m₀ + data_prec · (u/t)) / post_prec
+ //
+ // The `data_prec · (u/t)` term is rewritten as `u / σ²` so both
+ // terms share a denominator and the multiplication is cheaper.
+ let sigma2 = p.sigma * p.sigma;
+ let prior_prec = 1.0 / (p.s0 * p.s0);
+ let data_prec = t / sigma2;
+ let post_var = 1.0 / (prior_prec + data_prec);
+ let post_mean = post_var * (p.m0 * prior_prec + u / sigma2);
+
+ // --- Predictive for `C(1) = u + (rate × time remaining) + noise` ---
+ //
+ // Mean: what we've used, plus the posterior rate projected over the
+ // remaining `(1 - t)` of the window.
+ //
+ // Variance has two pieces: uncertainty in the rate estimate
+ // propagated over `(1 - t)` (squared because it scales the deterministic
+ // drift term), plus accumulated process noise `σ² · (1 - t)` over the
+ // remaining interval (linear because Brownian variance grows with time).
+ let mean = u + post_mean * (1.0 - t);
+ let var = post_var * (1.0 - t).powi(2) + sigma2 * (1.0 - t);
+ (mean, var)
+ };
+ // Upper tail of the Gaussian predictive at 1.0: `P(C(1) ≥ 1)`.
+ standard_normal_cdf((mean - 1.0) / var.sqrt())
+}
+
+/// Format a `DateTime` as a clock time only: `3pm`, `5:45pm`. `:00` minutes
+/// are elided (chrono can't do that conditionally in one format string).
+fn format_clock<Tz: chrono::TimeZone>(dt: &chrono::DateTime<Tz>) -> String
+where
+ Tz::Offset: std::fmt::Display,
+{
+ use chrono::Timelike as _;
+ if dt.minute() == 0 {
+ dt.format("%-I%P").to_string()
+ } else {
+ dt.format("%-I:%M%P").to_string()
+ }
+}
+
+/// Format the rate-limit window's start and end as a short label that
+/// goes inside the parenthetical: `10am-3pm` for the 5-hour window,
+/// `Mon-Mon 3pm` for the 7-day window.
+///
+/// The 5h variant uses clock times on both endpoints. The longer window
+/// uses the weekday on both ends (they're equal for a true 7-day rolling
+/// window) and the clock time only on the end, which is the reset.
+///
+/// Generic over `TimeZone` so unit tests can pass `&chrono::Utc` directly
+/// without mutating the process-global `TZ`; production passes
+/// `&chrono::Local`.
+fn format_window_bounds<Tz: chrono::TimeZone>(resets_at: i64, window_secs: i64, tz: &Tz) -> String
+where
+ Tz::Offset: std::fmt::Display,
+{
+ let to_tz = |unix| {
+ chrono::DateTime::from_timestamp(unix, 0)
+ .map(|t| t.with_timezone(tz))
+ .unwrap_or_else(|| chrono::Utc::now().with_timezone(tz))
+ };
+ let start = to_tz(resets_at - window_secs);
+ let end = to_tz(resets_at);
+ // En-dash (U+2013) is the typographically correct separator for a
+ // numeric range and stays visually distinct from the ASCII hyphens
+ // used elsewhere in the statusline (e.g. `-3` for line deletions).
+ if window_secs <= 12 * 3600 {
+ format!("{}–{}", format_clock(&start), format_clock(&end))
+ } else {
+ format!(
+ "{}–{} {}",
+ start.format("%a"),
+ end.format("%a"),
+ format_clock(&end)
+ )
+ }
+}
+
+/// Pick the window most likely to be hit; return `None` to hide the segment.
+///
+/// Both windows can simultaneously be over the show threshold. We surface
+/// only the worse-projected one because a single-segment statusline is
+/// already crowded — the user gets the binding constraint, not a list.
+///
+/// Split out from rendering so the selection logic stays testable without
+/// dragging in `chrono::Local`.
+fn select_binding_window(
+ readings: &[RateLimitReading],
+ now_unix: i64,
+) -> Option<&RateLimitReading> {
+ readings
+ .iter()
+ .filter_map(|r| {
+ let u = (r.used_percentage / 100.0).clamp(0.0, 1.0);
+ let elapsed = (now_unix - (r.resets_at - r.window_secs)) as f64 / r.window_secs as f64;
+ let t = elapsed.clamp(0.0, 1.0);
+ let p = p_over(u, t, r.priors);
+ (p >= RATE_LIMIT_P_THRESHOLD).then_some((p, r))
+ })
+ .max_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
+ .map(|(_, r)| r)
+}
+
+/// Build the rate-limit segment, or `None` to hide.
+///
+/// Shape: `<pace>×pace(<window_bounds>)` — e.g. `1.4×pace(10am-3pm)` or
+/// `1.9×pace(Mon-Mon 3pm)`. `pace` is the **naive `u/t` ratio**: what the
+/// user has actually consumed per unit elapsed window. `1.0×` is on pace
+/// to exactly fill the window; `>1.0×` is over-pace. The Bayesian
+/// posterior `m₁` is only used by [`p_over`] to decide whether to show —
+/// for the *displayed* number, the raw measurement is more honest, more
+/// transparent, and tracks bursts naturally.
+fn format_rate_limit_segment(readings: &[RateLimitReading], now_unix: i64) -> Option<String> {
+ let r = select_binding_window(readings, now_unix)?;
+ let u = r.used_percentage / 100.0;
+ // `t` is the elapsed fraction of the window. Floor avoids division by
+ // zero on absurd inputs; in practice `select_binding_window` only
+ // returns a reading whose `P(over) ≥ 0.5`, which requires `t > 0`.
+ let elapsed = (now_unix - (r.resets_at - r.window_secs)) as f64 / r.window_secs as f64;
+ let t = elapsed.clamp(0.001, 1.0);
+ let pace = u / t;
+ let bounds = format_window_bounds(r.resets_at, r.window_secs, &chrono::Local);
+ // The whole segment is wrapped in yellow because its appearance *is*
+ // the warning. Unlike informational segments where color picks out one
+ // sub-glyph (`@+1` green, `?` cyan), here the entire string is the
+ // "you should look at this" signal.
+ Some(color_print::cformat!("<yellow>{pace:.1}×pace({bounds})</>"))
+}
+
/// Format context usage as a moon phase gauge.
///
/// Uses moon phase emoji to show fill level (waning - gets darker as context fills).
@@ -149,7 +459,9 @@ fn format_context_gauge(percentage: f64) -> String {
_ => '🌑',
};
// Display the original percentage (not clamped) for transparency
- format!("{symbol} {:.0}%", percentage)
+ // Emoji + percent runs together (no separator) to match the other
+ // prefix-char segments in the statusline: `@+1`, `↓1`, `?^|`.
+ format!("{symbol}{:.0}%", percentage)
}
/// Run the statusline command.
@@ -169,20 +481,27 @@ pub fn run(format: OutputFormat) -> Result<()> {
let claude_code = matches!(format, OutputFormat::ClaudeCode);
// Get context - either from stdin (claude-code mode) or current directory
- let (cwd, model_name, context_used_percentage) = if claude_code {
+ let (cwd, model_name, context_used_percentage, rate_limits) = 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.as_ref().and_then(|c| c.model_name.clone());
- let context_pct = ctx.and_then(|c| c.context_used_percentage);
- (Path::new(&current_dir).to_path_buf(), model, context_pct)
+ let context_pct = ctx.as_ref().and_then(|c| c.context_used_percentage);
+ let limits = ctx.map(|c| c.rate_limits).unwrap_or_default();
+ (
+ Path::new(&current_dir).to_path_buf(),
+ model,
+ context_pct,
+ limits,
+ )
} else {
(
env::current_dir().context("Failed to get current directory")?,
None,
None,
+ Vec::new(),
)
};
@@ -220,10 +539,11 @@ pub fn run(format: OutputFormat) -> Result<()> {
segments.extend(git_segments);
}
- // Model name (claude-code mode only) - priority 1 (same as Branch)
+ // Model name (claude-code mode only) - priority 1 (same as Branch).
+ // The two-space inter-segment separator handles spacing on its own; no
+ // decorative prefix needed.
if let Some(model) = model_name {
- // Use "| " prefix to visually separate from git status
- segments.push(StatuslineSegment::new(format!("| {model}"), PRIORITY_MODEL));
+ segments.push(StatuslineSegment::new(model, PRIORITY_MODEL));
}
// Context gauge (claude-code mode only) - priority 2 (placed after model)
@@ -234,6 +554,17 @@ pub fn run(format: OutputFormat) -> Result<()> {
));
}
+ // Rate-limit segment (claude-code mode only) - priority 3, shown only
+ // when the binding window has a real chance of going over.
+ // `epoch_now()` honours `WORKTRUNK_TEST_EPOCH` so snapshot tests can pin
+ // "now" alongside `TZ=UTC` for deterministic output.
+ if !rate_limits.is_empty()
+ && let Some(content) =
+ format_rate_limit_segment(&rate_limits, worktrunk::utils::epoch_now() as i64)
+ {
+ segments.push(StatuslineSegment::new(content, PRIORITY_RATE_LIMITS));
+ }
+
if segments.is_empty() {
return Ok(());
}
@@ -613,38 +944,38 @@ mod tests {
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%");
+ 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%");
+ 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%
+ 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%");
+ assert_eq!(format_context_gauge(105.0), "🌑105%");
+ assert_eq!(format_context_gauge(150.0), "🌑150%");
}
#[test]
@@ -684,4 +1015,310 @@ mod tests {
let ctx = ClaudeCodeContext::parse(json).expect("should parse");
assert_eq!(ctx.context_used_percentage, None);
}
+
+ // --- Rate-limit pace prediction ---
+
+ #[test]
+ fn test_erf_matches_reference_values() {
+ // Reference values from Abramowitz & Stegun Table 7.1; A&S 7.1.26
+ // claims |error| < 1.5e-7.
+ let cases = [
+ (0.0, 0.0),
+ (0.5, 0.520_499_877_8),
+ (1.0, 0.842_700_792_9),
+ (2.0, 0.995_322_265_0),
+ (-1.0, -0.842_700_792_9),
+ ];
+ for (x, expected) in cases {
+ assert!(
+ (erf(x) - expected).abs() < 1e-6,
+ "erf({x}): expected {expected}, got {}",
+ erf(x)
+ );
+ }
+ // Tail saturates.
+ assert!((erf(5.0) - 1.0).abs() < 1e-7);
+ assert!((erf(-5.0) + 1.0).abs() < 1e-7);
+ }
+
+ #[test]
+ fn test_standard_normal_cdf_known_points() {
+ let cases = [
+ (0.0, 0.5),
+ (1.0, 0.841_344_746),
+ (-1.0, 0.158_655_254),
+ (1.96, 0.975_002_105),
+ (-1.96, 0.024_997_895),
+ ];
+ for (z, expected) in cases {
+ assert!(
+ (standard_normal_cdf(z) - expected).abs() < 1e-5,
+ "phi({z}): expected {expected}, got {}",
+ standard_normal_cdf(z)
+ );
+ }
+ }
+
+ #[test]
+ fn test_p_over_boundary_cases() {
+ // t = 1: deterministic.
+ assert_eq!(p_over(0.5, 1.0, &FIVE_HOUR_PRIORS), 0.0);
+ assert_eq!(p_over(1.0, 1.0, &FIVE_HOUR_PRIORS), 1.0);
+ assert_eq!(p_over(1.5, 1.0, &FIVE_HOUR_PRIORS), 1.0);
+
+ // t = 0: predictive is the prior, so u doesn't matter.
+ let p0 = p_over(0.0, 0.0, &FIVE_HOUR_PRIORS);
+ let p1 = p_over(0.9, 0.0, &FIVE_HOUR_PRIORS);
+ assert!((p0 - p1).abs() < 1e-9);
+ // m0 < 1 means the prior expects to come in under the cap.
+ assert!(p0 < 0.5);
+ }
+
+ #[test]
+ fn test_p_over_matches_prototype_values() {
+ // Values computed by the Python prototype (.tmp/rate_limit_pace.py)
+ // with the same priors. Tolerance covers the A&S erf error and
+ // round-off in either implementation.
+ let cases: &[(f64, f64, &WindowPriors, f64, &str)] = &[
+ (0.05, 0.03, &FIVE_HOUR_PRIORS, 0.415, "5%@3% on 5h"),
+ (0.30, 0.20, &FIVE_HOUR_PRIORS, 0.59, "30%@20% on 5h"),
+ (0.50, 0.40, &FIVE_HOUR_PRIORS, 0.61, "50%@40% on 5h"),
+ (0.80, 0.60, &FIVE_HOUR_PRIORS, 0.82, "80%@60% on 5h"),
+ (0.50, 0.30, &SEVEN_DAY_PRIORS, 0.83, "50%@30% on 7d"),
+ (0.30, 0.20, &SEVEN_DAY_PRIORS, 0.63, "30%@20% on 7d"),
+ ];
+ for &(u, t, p, expected, label) in cases {
+ let got = p_over(u, t, p);
+ assert!(
+ (got - expected).abs() < 0.02,
+ "{label}: expected ~{expected:.3}, got {got:.3}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_p_over_monotonic_in_u() {
+ // Holding t and priors fixed, P(over) is non-decreasing in u.
+ let mut prev = 0.0;
+ for u_pct in 0..=100 {
+ let u = u_pct as f64 / 100.0;
+ let p = p_over(u, 0.5, &FIVE_HOUR_PRIORS);
+ assert!(
+ p >= prev - 1e-9,
+ "non-monotone at u={u}: prev={prev}, p={p}"
+ );
+ prev = p;
+ }
+ }
+
+ #[test]
+ fn test_format_clock_renders_12h_and_elides_zero_minutes() {
+ use chrono::TimeZone;
+ let cases: &[(u32, u32, &str)] = &[
+ (15, 0, "3pm"),
+ (17, 45, "5:45pm"),
+ (0, 0, "12am"),
+ (12, 0, "12pm"),
+ (1, 5, "1:05am"),
+ (23, 59, "11:59pm"),
+ ];
+ for &(h, m, expected) in cases {
+ let d = chrono::Utc.with_ymd_and_hms(2026, 5, 23, h, m, 0).unwrap();
+ assert_eq!(format_clock(&d), expected, "h={h} m={m}");
+ }
+ }
+
+ #[test]
+ fn test_format_window_bounds_five_hour_is_clock_only() {
+ use chrono::TimeZone;
+ // resets_at = 2026-05-23 15:00 UTC, window = 5h → start = 10:00 UTC.
+ let resets_at = chrono::Utc
+ .with_ymd_and_hms(2026, 5, 23, 15, 0, 0)
+ .unwrap()
+ .timestamp();
+ assert_eq!(
+ format_window_bounds(resets_at, FIVE_HOUR_SECS, &chrono::Utc),
+ "10am\u{2013}3pm"
+ );
+ }
+
+ #[test]
+ fn test_format_window_bounds_seven_day_is_weekday_with_end_time() {
+ use chrono::TimeZone;
+ // 2026-01-05 is a Monday; resets Mon 15:00 UTC, window 7d → start
+ // prev Mon 15:00 UTC. Both endpoints are Monday.
+ let resets_at = chrono::Utc
+ .with_ymd_and_hms(2026, 1, 5, 15, 0, 0)
+ .unwrap()
+ .timestamp();
+ assert_eq!(
+ format_window_bounds(resets_at, SEVEN_DAY_SECS, &chrono::Utc),
+ "Mon\u{2013}Mon 3pm"
+ );
+ }
+
+ fn make_reading(
+ used_pct: f64,
+ t_elapsed: f64,
+ priors: &'static WindowPriors,
+ now: i64,
+ window_secs: i64,
+ ) -> RateLimitReading {
+ let resets_at = now + ((1.0 - t_elapsed) * window_secs as f64).round() as i64;
+ RateLimitReading {
+ used_percentage: used_pct,
+ resets_at,
+ window_secs,
+ priors,
+ }
+ }
+
+ #[test]
+ fn test_select_binding_window_empty() {
+ assert!(select_binding_window(&[], 1_700_000_000).is_none());
+ }
+
+ #[test]
+ fn test_select_binding_window_below_threshold_hides() {
+ let now = 1_700_000_000_i64;
+ // 5%@3% on the 5h window: P ~ 42%, below the 50% trigger.
+ let r = make_reading(5.0, 0.03, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS);
+ assert!(select_binding_window(&[r], now).is_none());
+ }
+
+ #[test]
+ fn test_select_binding_window_visible_single() {
+ let now = 1_700_000_000_i64;
+ // 80%@60% on 5h: P ~ 82%, above threshold.
+ let r = make_reading(80.0, 0.60, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS);
+ let sel = select_binding_window(std::slice::from_ref(&r), now);
+ assert!(sel.is_some());
+ assert_eq!(sel.unwrap().used_percentage, 80.0);
+ }
+
+ #[test]
+ fn test_select_binding_window_picks_worse_of_two() {
+ let now = 1_700_000_000_i64;
+ let readings = [
+ make_reading(50.0, 0.30, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS),
+ make_reading(80.0, 0.40, &SEVEN_DAY_PRIORS, now, SEVEN_DAY_SECS),
+ ];
+ let sel = select_binding_window(&readings, now);
+ assert!(sel.is_some());
+ // 7d is worse-projected — wins.
+ assert_eq!(sel.unwrap().used_percentage, 80.0);
+ }
+
+ #[test]
+ fn test_select_binding_window_filters_below_threshold() {
+ let now = 1_700_000_000_i64;
+ let readings = [
+ make_reading(5.0, 0.03, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS),
+ make_reading(50.0, 0.30, &SEVEN_DAY_PRIORS, now, SEVEN_DAY_SECS),
+ ];
+ let sel = select_binding_window(&readings, now);
+ assert!(sel.is_some());
+ assert_eq!(sel.unwrap().used_percentage, 50.0);
+ }
+
+ #[test]
+ fn test_format_rate_limit_segment_format_string() {
+ let now = 1_700_000_000_i64;
+ // u=0.8 used over t=0.6 of the window ⇒ pace = u/t ≈ 1.33 → "1.3×".
+ let r = make_reading(80.0, 0.60, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS);
+ let out =
+ format_rate_limit_segment(std::slice::from_ref(&r), now).expect("should be visible");
+ // Strip ANSI before asserting on the visible characters — the segment
+ // is wrapped in `<yellow>…</>`.
+ let visible = out.ansi_strip();
+ assert!(
+ visible.starts_with("1.3×pace(") && visible.ends_with(')'),
+ "unexpected format: {visible:?}"
+ );
+ }
+
+ #[test]
+ fn test_format_rate_limit_segment_hidden() {
+ let now = 1_700_000_000_i64;
+ let r = make_reading(5.0, 0.03, &FIVE_HOUR_PRIORS, now, FIVE_HOUR_SECS);
+ assert!(format_rate_limit_segment(&[r], now).is_none());
+ }
+
+ #[test]
+ fn test_parse_rate_limits_both_windows() {
+ let v: serde_json::Value = serde_json::from_str(
+ r#"{
+ "rate_limits": {
+ "five_hour": {"used_percentage": 23.5, "resets_at": 1738425600},
+ "seven_day": {"used_percentage": 41.2, "resets_at": 1738857600}
+ }
+ }"#,
+ )
+ .unwrap();
+ let limits = parse_rate_limits(&v);
+ assert_eq!(limits.len(), 2);
+ assert_eq!(limits[0].used_percentage, 23.5);
+ assert_eq!(limits[0].resets_at, 1738425600);
+ assert_eq!(limits[0].window_secs, FIVE_HOUR_SECS);
+ assert_eq!(limits[1].used_percentage, 41.2);
+ assert_eq!(limits[1].resets_at, 1738857600);
+ assert_eq!(limits[1].window_secs, SEVEN_DAY_SECS);
+ }
+
+ #[test]
+ fn test_parse_rate_limits_one_window_present() {
+ let v: serde_json::Value = serde_json::from_str(
+ r#"{
+ "rate_limits": {
+ "five_hour": {"used_percentage": 23.5, "resets_at": 1738425600}
+ }
+ }"#,
+ )
+ .unwrap();
+ let limits = parse_rate_limits(&v);
+ assert_eq!(limits.len(), 1);
+ assert_eq!(limits[0].window_secs, FIVE_HOUR_SECS);
+ }
+
+ #[test]
+ fn test_parse_rate_limits_absent() {
+ let v: serde_json::Value = serde_json::from_str(r#"{}"#).unwrap();
+ assert!(parse_rate_limits(&v).is_empty());
+ }
+
+ #[test]
+ fn test_parse_rate_limits_partial_window_dropped() {
+ // Each window needs both used_percentage and resets_at; otherwise
+ // it's treated as absent rather than half-parsed.
+ let v: serde_json::Value = serde_json::from_str(
+ r#"{
+ "rate_limits": {
+ "five_hour": {"used_percentage": 23.5},
+ "seven_day": {"resets_at": 1738857600}
+ }
+ }"#,
+ )
+ .unwrap();
+ assert!(parse_rate_limits(&v).is_empty());
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_with_rate_limits() {
+ let json = r#"{
+ "workspace": {"current_dir": "/tmp/test"},
+ "rate_limits": {
+ "five_hour": {"used_percentage": 23.5, "resets_at": 1738425600},
+ "seven_day": {"used_percentage": 41.2, "resets_at": 1738857600}
+ }
+ }"#;
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert_eq!(ctx.rate_limits.len(), 2);
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_no_rate_limits() {
+ let json = r#"{"workspace": {"current_dir": "/tmp/test"}}"#;
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert!(ctx.rate_limits.is_empty());
+ }
}
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index 97ffa721e..0d7bf6f88 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -201,7 +201,7 @@ fn test_statusline_claude_code_full_context(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ?^| @+1 | Opus");
+ assert_snapshot!(output, @"[PATH] main ?^| @+1 Opus");
});
}
@@ -228,7 +228,7 @@ fn test_statusline_claude_code_with_model(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ^| | Haiku");
+ assert_snapshot!(output, @"[PATH] main ^| Haiku");
});
}
@@ -247,7 +247,7 @@ fn test_statusline_claude_code_with_context_gauge(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ^| | Opus 🌕 42%");
+ assert_snapshot!(output, @"[PATH] main ^| Opus 🌕42%");
});
}
@@ -264,7 +264,7 @@ fn test_statusline_claude_code_context_gauge_low(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ^| | Opus 🌕 5%");
+ assert_snapshot!(output, @"[PATH] main ^| Opus 🌕5%");
});
}
@@ -281,7 +281,7 @@ fn test_statusline_claude_code_context_gauge_high(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ^| | Opus 🌑 98%");
+ assert_snapshot!(output, @"[PATH] main ^| Opus 🌑98%");
});
}
@@ -298,7 +298,7 @@ fn test_statusline_claude_code_missing_context_window(repo: TestRepo) {
let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));
claude_code_snapshot_settings().bind(|| {
- assert_snapshot!(output, @"[PATH] main ^| | Opus");
+ assert_snapshot!(output, @"[PATH] main ^| Opus");
});
}
@@ -614,3 +614,228 @@ fn test_statusline_json_nested_worktree(mut repo: TestRepo) {
"Nested worktree should report 'feature' branch, not parent"
);
}
+
+// --- Rate-limit segment snapshots ---
+//
+// These tests pin the "now" used by the rate-limit predictor (via
+// `WORKTRUNK_TEST_EPOCH`) and force `TZ=UTC` so the deadline string is
+// deterministic across machines and timezones.
+//
+// All cases use Thursday 2025-01-02 13:00 UTC as the reference "now", and
+// resets_at values relative to it.
+
+use crate::common::TEST_EPOCH;
+
+const TEST_NOW_THU_1PM: u64 = TEST_EPOCH + 13 * 3600;
+
+/// Run statusline with a pinned "now" and timezone; optional COLUMNS override.
+fn run_statusline_at_time(
+ repo: &TestRepo,
+ stdin_json: &str,
+ now_epoch: u64,
+ columns: Option<u32>,
+) -> String {
+ let mut cmd = wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.args(["list", "statusline", "--format=claude-code"]);
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK_TEST_EPOCH", now_epoch.to_string());
+ cmd.env("TZ", "UTC");
+ if let Some(c) = columns {
+ cmd.env("COLUMNS", c.to_string());
+ }
+ cmd.stdin(Stdio::piped());
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+
+ let mut child = cmd.spawn().expect("failed to spawn command");
+ let mut stdin = child.stdin.take().expect("failed to get stdin");
+ stdin
+ .write_all(stdin_json.as_bytes())
+ .expect("failed to write stdin");
+ drop(stdin);
+
+ let output = child.wait_with_output().expect("failed to wait for output");
+ String::from_utf8_lossy(&output.stdout).to_string()
+}
+
+/// Build a minimal Claude Code JSON with the given rate-limit windows.
+///
+/// `windows`: `[(key, used_percentage, seconds_until_reset_from_now)]`.
+fn build_claude_code_json(
+ repo_path: &std::path::Path,
+ model: Option<&str>,
+ context_pct: Option<f64>,
+ now_epoch: u64,
+ windows: &[(&str, f64, i64)],
+) -> String {
+ use std::fmt::Write;
+ let escaped = escape_path_for_json(repo_path);
+ let mut json = format!(r#"{{"workspace":{{"current_dir":"{escaped}"}}"#);
+ if let Some(m) = model {
+ write!(json, r#","model":{{"display_name":"{m}"}}"#).unwrap();
+ }
+ if let Some(p) = context_pct {
+ write!(json, r#","context_window":{{"used_percentage":{p}}}"#).unwrap();
+ }
+ if !windows.is_empty() {
+ json.push_str(r#","rate_limits":{"#);
+ for (i, (key, used, secs_to_reset)) in windows.iter().enumerate() {
+ if i > 0 {
+ json.push(',');
+ }
+ let resets_at = now_epoch as i64 + secs_to_reset;
+ write!(
+ json,
+ r#""{key}":{{"used_percentage":{used},"resets_at":{resets_at}}}"#
+ )
+ .unwrap();
+ }
+ json.push('}');
+ }
+ json.push('}');
+ json
+}
+
+#[rstest]
+fn test_statusline_rate_limit_hidden_when_safe(repo: TestRepo) {
+ // Both windows well under threshold → segment absent.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[
+ ("five_hour", 30.0, 2 * 3600 + 1800), // 50% elapsed, 30% used
+ ("seven_day", 20.0, 4 * 86400), // ~43% elapsed, 20% used
+ ],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_hidden_when_safe", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_5h_clock_time(repo: TestRepo) {
+ // 5h burning mid-window, reset in 2h → 3pm.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[("five_hour", 80.0, 2 * 3600)],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_5h_clock_time", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_5h_with_minutes(repo: TestRepo) {
+ // Reset 30 minutes from now → 1:30pm — exercises the `:mm` time spec.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[("five_hour", 95.0, 1800)],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_5h_with_minutes", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_5h_at_limit(repo: TestRepo) {
+ // 100% used — the throttled edge.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[("five_hour", 100.0, 2 * 3600)],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_5h_at_limit", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_7d_with_day_and_time(repo: TestRepo) {
+ // 7d binding, reset 4d 2h from Thu 1pm → Mon 3pm.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[
+ ("five_hour", 15.0, 4 * 3600), // safe
+ ("seven_day", 80.0, 4 * 86400 + 2 * 3600),
+ ],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_7d_with_day_and_time", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_both_picks_worse(repo: TestRepo) {
+ // Both windows flagged; 7d projects worse, so 7d is the segment shown.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[
+ ("five_hour", 85.0, 90 * 60), // 70% elapsed, 85% used → visible
+ ("seven_day", 80.0, 4 * 86400 + 2 * 3600), // ~40% elapsed, 80% used → worse
+ ],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_both_picks_worse", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_with_dirty_worktree_and_context(repo: TestRepo) {
+ // Uncommitted change + 95% context + 5h binding — checks segment
+ // composition with other state.
+ add_uncommitted_changes(&repo);
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(95.0),
+ TEST_NOW_THU_1PM,
+ &[("five_hour", 80.0, 2 * 3600)],
+ );
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, None);
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_with_dirty_worktree_and_context", out);
+ });
+}
+
+#[rstest]
+fn test_statusline_rate_limit_drops_at_narrow_width(repo: TestRepo) {
+ // Same input as `5h_clock_time` but COLUMNS=80 — the rate-limit
+ // segment is the lowest-priority Claude-Code segment, so it drops first.
+ let json = build_claude_code_json(
+ repo.root_path(),
+ Some("Opus"),
+ Some(42.0),
+ TEST_NOW_THU_1PM,
+ &[("five_hour", 80.0, 2 * 3600)],
+ );
+ // COLUMNS=40 is narrower than the rendered line with rate-limit, so
+ // the lowest-priority segments drop. The full line is ~60 chars wide
+ // even on the short test repo path.
+ let out = run_statusline_at_time(&repo, &json, TEST_NOW_THU_1PM, Some(40));
+ claude_code_snapshot_settings().bind(|| {
+ assert_snapshot!("rate_limit_drops_at_narrow_width", out);
+ });
+}
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_at_limit.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_at_limit.snap
new file mode 100644
index 000000000..1c3536ae7
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_at_limit.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42% 1.7×pace(10am–3pm)
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_clock_time.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_clock_time.snap
new file mode 100644
index 000000000..d6cb02423
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_clock_time.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42% 1.3×pace(10am–3pm)
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_with_minutes.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_with_minutes.snap
new file mode 100644
index 000000000..92c769032
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_5h_with_minutes.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42% 1.1×pace(8:30am–1:30pm)
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_7d_with_day_and_time.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_7d_with_day_and_time.snap
new file mode 100644
index 000000000..bf52ea4b1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_7d_with_day_and_time.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42% 1.9×pace(Mon–Mon 3pm)
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_both_picks_worse.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_both_picks_worse.snap
new file mode 100644
index 000000000..bf52ea4b1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_both_picks_worse.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42% 1.9×pace(Mon–Mon 3pm)
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_drops_at_narrow_width.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_drops_at_narrow_width.snap
new file mode 100644
index 000000000..114b02d8a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_drops_at_narrow_width.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42%
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_hidden_when_safe.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_hidden_when_safe.snap
new file mode 100644
index 000000000..114b02d8a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_hidden_when_safe.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ^| Opus 🌕42%
diff --git a/tests/snapshots/integration__integration_tests__statusline__rate_limit_with_dirty_worktree_and_context.snap b/tests/snapshots/integration__integration_tests__statusline__rate_limit_with_dirty_worktree_and_context.snap
new file mode 100644
index 000000000..54edb0484
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__statusline__rate_limit_with_dirty_worktree_and_context.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/statusline.rs
+expression: out
+---
+[PATH] main ?^| @+1 Opus 🌒95% 1.3×pace(10am–3pm)