Skip to content

Commit 0f2d584

Browse files
committed
fix(progress): keep the spinner status on a single row
Each spinner frame clears its line with `\r\x1b[K`, which only erases the row the cursor sits on. When the status is wider than the terminal it wraps, so every redraw leaves the overflow row on screen and the line reads as flicker. The combined status `Refreshing model pricing from LiteLLM... :: Loading usage logs (0/2) :: Claude, Codex` is ~85 columns, so any terminal narrower than that hits it on every online run; `-O` skips the pricing status and avoids it. Truncate the status to the terminal width minus the spinner prefix and one spare column before writing, so the single-line clear stays correct and the cursor never ends a frame in the wrap-pending state. `table.rs` already had ANSI- and CJK-aware truncation for cells, so that helper moves to `ccusage-terminal::width` as the public `truncate_to_width` instead of being duplicated. Its tests and insta snapshot move with it. Verified under a pty at `COLUMNS=40`: all 284 spinner frames stay within 39 columns, and at `COLUMNS=80` nothing is truncated. Closes #1411
1 parent d7fec09 commit 0f2d584

7 files changed

Lines changed: 158 additions & 69 deletions

File tree

‎rust/crates/ccusage-core/src/progress.rs‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,14 @@ use std::{
66
time::Duration,
77
};
88

9+
use ccusage_terminal::{terminal_width, truncate_to_width};
10+
911
const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
1012
const SPINNER_INTERVAL: Duration = Duration::from_millis(80);
1113

14+
/// Display columns the spinner frame and the space after it take up.
15+
const SPINNER_PREFIX_WIDTH: usize = 2;
16+
1217
thread_local! {
1318
static ACTIVE_PROGRESS: RefCell<Option<ProgressController>> = const { RefCell::new(None) };
1419
}
@@ -72,6 +77,20 @@ fn format_usage_load_progress_text(
7277
}
7378
}
7479

80+
/// Shorten the status text so the spinner line always occupies a single row.
81+
///
82+
/// Each frame clears its own line with `\r\x1b[K`, which only erases the row the
83+
/// cursor sits on. A status wide enough to wrap therefore leaves the overflow
84+
/// row on screen and the redraw reads as flicker. One column is left free on top
85+
/// of the spinner prefix so the cursor never ends a frame in the wrap-pending
86+
/// state some terminals enter at the last column.
87+
fn fit_status_to_width(text: &str, terminal_width: usize) -> String {
88+
truncate_to_width(
89+
text,
90+
terminal_width.saturating_sub(SPINNER_PREFIX_WIDTH + 1),
91+
)
92+
}
93+
7594
pub fn usage_load_output_is_tty() -> bool {
7695
io::stdout().is_terminal()
7796
}
@@ -253,7 +272,10 @@ impl ProgressState {
253272
if !self.has_content() {
254273
return;
255274
}
256-
let text = format_usage_load_progress_text(&self.states, self.status.as_deref());
275+
let text = fit_status_to_width(
276+
&format_usage_load_progress_text(&self.states, self.status.as_deref()),
277+
terminal_width(),
278+
);
257279
let frame = SPINNER_FRAMES[self.frame % SPINNER_FRAMES.len()];
258280
self.frame = self.frame.wrapping_add(1);
259281
let _ = write!(
@@ -338,6 +360,37 @@ mod tests {
338360
);
339361
}
340362

363+
#[test]
364+
fn fits_the_status_within_a_narrow_terminal() {
365+
let text = format_usage_load_progress_text(
366+
&[
367+
(UsageLoadAgent("Claude"), LoadProgressState::Loading),
368+
(UsageLoadAgent("Codex"), LoadProgressState::Loading),
369+
],
370+
Some("Refreshing model pricing from LiteLLM..."),
371+
);
372+
373+
let fitted = fit_status_to_width(&text, 80);
374+
375+
assert_eq!(
376+
fitted,
377+
"Refreshing model pricing from LiteLLM... :: Loading usage logs (0/2) :: Clau…"
378+
);
379+
assert_eq!(fitted.chars().count() + SPINNER_PREFIX_WIDTH, 79);
380+
}
381+
382+
#[test]
383+
fn keeps_the_status_intact_on_a_wide_terminal() {
384+
let text = format_usage_load_progress_text(&[], Some("Refreshing model pricing"));
385+
386+
assert_eq!(fit_status_to_width(&text, 120), "Refreshing model pricing");
387+
}
388+
389+
#[test]
390+
fn fits_the_status_when_the_terminal_has_no_room_at_all() {
391+
assert_eq!(fit_status_to_width("Loading usage logs", 2), "…");
392+
}
393+
341394
#[test]
342395
fn hides_progress_for_json_or_non_tty_output() {
343396
assert!(!should_show_usage_load_progress(true, true));

‎rust/crates/ccusage-terminal/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ the table writer every report uses.
1010
- `style.rs` — `TerminalStyle`, color selection, and `NO_COLOR` handling.
1111
- `terminal.rs` — terminal width detection.
1212
- `title.rs` — the boxed report titles.
13+
- `width.rs` — ANSI-aware display width measurement and truncation.
1314

1415
`ccusage-core` re-exports this crate's types, so adapters reach them through
1516
`ccusage_core` rather than depending on it directly.
@@ -23,6 +24,7 @@ the table writer every report uses.
2324
- `table::SimpleTable`
2425
- `terminal::terminal_width`
2526
- `title::print_box_title`
27+
- `width::truncate_to_width`
2628

2729
## Depends on
2830

‎rust/crates/ccusage-terminal/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ pub use style::{Color, TerminalStyle, color};
88
pub use table::{Align, SimpleTable};
99
pub use terminal::terminal_width;
1010
pub use title::print_box_title;
11+
pub use width::truncate_to_width;

‎rust/crates/ccusage-terminal/src/snapshots/ccusage_terminal__table__tests__snapshots_ansi_truncation_boundary.snap‎

Lines changed: 0 additions & 6 deletions
This file was deleted.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
source: crates/ccusage-terminal/src/width.rs
3+
expression: "truncate_to_width(\"\\x1b[33mvery-long-value\\x1b[0m\", 8)"
4+
---
5+
very-lo…

‎rust/crates/ccusage-terminal/src/table.rs‎

Lines changed: 3 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::io::{self, Write};
33
use crate::{
44
style::{Color, TerminalStyle, color},
55
terminal::DEFAULT_TERMINAL_WIDTH,
6-
width::{char_display_width, contains_ansi, visible_width, visible_width_max_line},
6+
width::{truncate_to_width, visible_width, visible_width_max_line},
77
};
88

99
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -245,7 +245,7 @@ fn wrap_cell_lines(cell: &str, width: usize) -> Vec<String> {
245245

246246
fn wrap_cell_line(line: &str, width: usize) -> Vec<String> {
247247
if line.split_whitespace().count() <= 1 {
248-
return vec![truncate_visible(line, width)];
248+
return vec![truncate_to_width(line, width)];
249249
}
250250

251251
let mut lines = Vec::new();
@@ -266,7 +266,7 @@ fn wrap_cell_line(line: &str, width: usize) -> Vec<String> {
266266
lines.push(current);
267267
}
268268
current = if visible_width(word) > width {
269-
truncate_visible(word, width)
269+
truncate_to_width(word, width)
270270
} else {
271271
word.to_string()
272272
};
@@ -278,51 +278,6 @@ fn wrap_cell_line(line: &str, width: usize) -> Vec<String> {
278278
lines
279279
}
280280

281-
fn truncate_visible(value: &str, width: usize) -> String {
282-
if visible_width(value) <= width {
283-
return value.to_string();
284-
}
285-
if width <= 1 {
286-
return "…".to_string();
287-
}
288-
let mut output = String::new();
289-
let mut current_width = 0;
290-
let mut index = 0;
291-
let bytes = value.as_bytes();
292-
while index < bytes.len() {
293-
if bytes[index] == 0x1b {
294-
let start = index;
295-
index += 1;
296-
if index < bytes.len() && bytes[index] == b'[' {
297-
index += 1;
298-
while index < bytes.len() && !(bytes[index] as char).is_ascii_alphabetic() {
299-
index += 1;
300-
}
301-
if index < bytes.len() {
302-
index += 1;
303-
}
304-
}
305-
output.push_str(&value[start..index]);
306-
continue;
307-
}
308-
let Some(ch) = value[index..].chars().next() else {
309-
break;
310-
};
311-
let char_width = char_display_width(ch);
312-
if current_width + char_width >= width {
313-
break;
314-
}
315-
output.push(ch);
316-
current_width += char_width;
317-
index += ch.len_utf8();
318-
}
319-
if contains_ansi(value) && !output.ends_with("\x1b[0m") {
320-
output.push_str("\x1b[0m");
321-
}
322-
output.push('…');
323-
output
324-
}
325-
326281
fn compact_date_cell(value: &str) -> Option<String> {
327282
let bytes = value.as_bytes();
328283
if bytes.len() == 10
@@ -478,18 +433,6 @@ mod tests {
478433
insta::assert_snapshot!(table.render_lines().join("\n"));
479434
}
480435

481-
#[test]
482-
fn truncate_visible_preserves_ansi_reset() {
483-
let truncated = truncate_visible("\x1b[33mvery-long-value\x1b[0m", 8);
484-
485-
assert!(truncated.ends_with("\x1b[0m…"));
486-
}
487-
488-
#[test]
489-
fn snapshots_ansi_truncation_boundary() {
490-
insta::assert_snapshot!(truncate_visible("\x1b[33mvery-long-value\x1b[0m", 8));
491-
}
492-
493436
#[test]
494437
fn column_widths_uses_max_line_not_sum_for_multiline_cells() {
495438
let mut table = SimpleTable::new(

‎rust/crates/ccusage-terminal/src/width.rs‎

Lines changed: 93 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,79 @@ pub(crate) fn visible_width(value: &str) -> usize {
2525
width
2626
}
2727

28-
pub(crate) fn contains_ansi(value: &str) -> bool {
28+
fn contains_ansi(value: &str) -> bool {
2929
value.as_bytes().contains(&0x1b)
3030
}
3131

32-
pub(crate) fn char_display_width(ch: char) -> usize {
32+
fn char_display_width(ch: char) -> usize {
3333
UnicodeWidthChar::width(ch).unwrap_or(0)
3434
}
3535

3636
pub(crate) fn visible_width_max_line(value: &str) -> usize {
3737
value.lines().map(visible_width).max().unwrap_or_default()
3838
}
3939

40+
/// Shorten `value` to at most `width` display columns, marking the cut with `…`.
41+
///
42+
/// Values that already fit are returned unchanged. ANSI escapes are copied
43+
/// through without spending width, and a reset is appended before the ellipsis
44+
/// so a cut inside a colored run cannot leak its style into the rest of the
45+
/// line.
46+
///
47+
/// # Examples
48+
///
49+
/// ```
50+
/// use ccusage_terminal::truncate_to_width;
51+
///
52+
/// assert_eq!(truncate_to_width("fits", 10), "fits");
53+
/// assert_eq!(truncate_to_width("Loading usage logs", 10), "Loading u…");
54+
/// ```
55+
pub fn truncate_to_width(value: &str, width: usize) -> String {
56+
if visible_width(value) <= width {
57+
return value.to_string();
58+
}
59+
if width <= 1 {
60+
return "…".to_string();
61+
}
62+
let mut output = String::new();
63+
let mut current_width = 0;
64+
let mut index = 0;
65+
let bytes = value.as_bytes();
66+
while index < bytes.len() {
67+
if bytes[index] == 0x1b {
68+
let start = index;
69+
index += 1;
70+
if index < bytes.len() && bytes[index] == b'[' {
71+
index += 1;
72+
while index < bytes.len() && !(bytes[index] as char).is_ascii_alphabetic() {
73+
index += 1;
74+
}
75+
if index < bytes.len() {
76+
index += 1;
77+
}
78+
}
79+
output.push_str(&value[start..index]);
80+
continue;
81+
}
82+
let Some(ch) = value[index..].chars().next() else {
83+
break;
84+
};
85+
let char_width = char_display_width(ch);
86+
// Stop one column early so the ellipsis itself stays inside `width`.
87+
if current_width + char_width >= width {
88+
break;
89+
}
90+
output.push(ch);
91+
current_width += char_width;
92+
index += ch.len_utf8();
93+
}
94+
if contains_ansi(value) && !output.ends_with("\x1b[0m") {
95+
output.push_str("\x1b[0m");
96+
}
97+
output.push('…');
98+
output
99+
}
100+
40101
#[cfg(test)]
41102
mod tests {
42103
use super::*;
@@ -47,6 +108,36 @@ mod tests {
47108
assert_eq!(visible_width("表"), 2);
48109
}
49110

111+
#[test]
112+
fn truncate_to_width_keeps_values_that_already_fit() {
113+
assert_eq!(
114+
truncate_to_width("Loading usage logs", 40),
115+
"Loading usage logs"
116+
);
117+
}
118+
119+
#[test]
120+
fn truncate_to_width_stays_within_the_requested_width() {
121+
assert_eq!(truncate_to_width("Loading usage logs", 10), "Loading u…");
122+
}
123+
124+
#[test]
125+
fn truncate_to_width_never_splits_a_wide_char_across_the_boundary() {
126+
assert_eq!(truncate_to_width("表表表表", 5), "表表…");
127+
}
128+
129+
#[test]
130+
fn truncate_to_width_preserves_ansi_reset() {
131+
let truncated = truncate_to_width("\x1b[33mvery-long-value\x1b[0m", 8);
132+
133+
assert!(truncated.ends_with("\x1b[0m…"));
134+
}
135+
136+
#[test]
137+
fn snapshots_ansi_truncation_boundary() {
138+
insta::assert_snapshot!(truncate_to_width("\x1b[33mvery-long-value\x1b[0m", 8));
139+
}
140+
50141
#[test]
51142
fn char_display_width_handles_standard_width_cases() {
52143
assert_eq!(char_display_width('a'), 1);

0 commit comments

Comments
 (0)