supercode-cli 0.4.19

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! UX-15: a lightweight "Thinking… (Ns)" progress indicator shown on stderr
//! while `supercode` is waiting on the model (or a long local operation like
//! `audit`/`convert`), so the terminal doesn't look frozen.
//!
//! Design goals (see `.volter/tracker/markdown/UX-15.md`):
//! - Zero-dependency: a plain thread + a couple of atomics, no spinner crate.
//! - Byte-clean on any non-interactive path: `run --output-format json`,
//!   piped/redirected output, `NO_COLOR`, or a dumb terminal must never see a
//!   single spinner byte on stdout *or* stderr. Achieved by never
//!   constructing/starting a [`Spinner`] on those paths (the gating predicate
//!   below, mirroring `ui::detect_color_level`'s pure-function shape) rather
//!   than trying to suppress output after the fact.
//! - Never touches stdout: all rendering goes to stderr, so the model's
//!   streamed answer (and any `--output-format json` payload) is never at
//!   risk of interleaving with spinner bytes.
//! - Cleared the instant real output starts: callers stop the spinner before
//!   printing anything of their own.
//!
//! ## UX-39: live streaming token counter
//!
//! Once tokens start streaming, [`Spinner`] ALSO drives a live "this turn: ~N
//! tok · session: ~M tok" status line (`record_delta`/`render_counter`/
//! `clear_counter`) — deliberately folded into this same struct rather than
//! adding a second thing that writes to stderr, so there is only ever one
//! owner of the status line:
//! - before the first token: the background-thread "Thinking… (Ns)"
//!   animation (unchanged by this ticket);
//! - once tokens are streaming: the synchronous counter below, drawn from
//!   the SAME calling thread that already invokes `stop()` at the top of
//!   every sink event — by the time a counter redraw happens, the animation
//!   thread has always already been joined, so the two can never race on
//!   the same line.
//!
//! Counts are the documented `ceil(utf8_bytes / 4)` estimator
//! (`supercode::tokens::estimate_tokens`) applied to a running byte total —
//! supercode has no real tokenizer, and more fundamentally, providers only
//! report exact `Usage.completion_tokens` once at the END of a round-trip,
//! never incrementally per delta, so a genuinely LIVE count can only ever be
//! an estimate. Always rendered with a leading `~` so it reads as one,
//! matching every other estimated figure in the codebase. The exact,
//! provider-reported total remains available on request via `/tokens`
//! (`Agent::total_output_tokens()`), unaffected by any of this. Gated by the
//! exact same `enabled` decision as the spinner (tty/quiet/`NO_COLOR`/dumb
//! term) — see `should_show_spinner`.

use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

/// Braille frames — cheap, small, and legible even on a narrow terminal.
const FRAMES: [char; 10] = ['', '', '', '', '', '', '', '', '', ''];

/// How long to wait before the first frame renders, so a fast (sub-second)
/// response never flashes a spinner the user barely perceives.
const START_DELAY: Duration = Duration::from_millis(200);

/// How often the frame/elapsed-time text is redrawn once visible.
const FRAME_INTERVAL: Duration = Duration::from_millis(90);

/// How often the background thread re-checks the stop flag while waiting
/// (keeps `stop()` responsive without busy-spinning).
const POLL_INTERVAL: Duration = Duration::from_millis(10);

/// UX-39: minimum gap between consecutive live-counter redraws — the same
/// spirit as `FRAME_INTERVAL` (the spinner's own redraw cadence): frequent
/// enough to feel live, far too coarse to flood the terminal with a `\r`
/// write on every single small delta a provider streams (many APIs send
/// deltas a few characters at a time).
const COUNTER_THROTTLE: Duration = Duration::from_millis(120);

/// Pure decision function for "should a spinner ever be shown?" — no I/O, so
/// it's unit-testable without a real tty or mutated env vars, the same shape
/// as `ui::detect_color_level`.
///
/// A spinner is suppressed when:
/// - `NO_COLOR` is set (the spinner is cursor-control/animation, not color,
///   but UX-15's AC groups it with the other chrome `NO_COLOR` silences);
/// - the caller is in `--quiet`/non-interactive mode (`quiet`);
/// - `TERM=dumb` (no cursor control the spinner could rely on); or
/// - stderr isn't a terminal (piped/redirected — the spinner writes there,
///   so this is the byte-cleanliness gate for `run ... | cat` /
///   `run --output-format json` / CI).
pub(crate) fn should_show_spinner(
    no_color: bool,
    quiet: bool,
    term_dumb: bool,
    stderr_is_tty: bool,
) -> bool {
    !(no_color || quiet || term_dumb || !stderr_is_tty)
}

/// Real-world gating: reads `NO_COLOR`/`TERM` and stderr's tty-ness. `quiet`
/// is threaded in by the caller — UX-38 landed the real `--quiet`/`-q` CLI
/// flag, so every call site now passes `main.rs`'s `effective_quiet(cli)`
/// (`cli.quiet || env_quiet()`), not a bare env check.
fn should_show_spinner_now(quiet: bool) -> bool {
    should_show_spinner(
        std::env::var_os("NO_COLOR").is_some(),
        quiet,
        std::env::var("TERM").ok().as_deref() == Some("dumb"),
        std::io::stderr().is_terminal(),
    )
}

/// `true` when `SUPERCODE_QUIET` is set (any value). UX-38 landed the real
/// `--quiet`/`-q` flag; this env var remains a first-class, equally-honored
/// alternative (a wrapper script that can't easily thread an extra flag
/// through still works) — `main.rs::effective_quiet` ORs the two together
/// (`cli.quiet || env_quiet()`) at every call site so the flag and the env
/// var can never give different answers.
pub(crate) fn env_quiet() -> bool {
    std::env::var_os("SUPERCODE_QUIET").is_some()
}

/// A background "Thinking… (Ns)" indicator on stderr. Cheap to construct;
/// `start`/`stop` are idempotent and safe to call from multiple sites (e.g.
/// once around a whole multi-turn `agent.send()`, and again from the event
/// sink on every streamed event) — only the first `start` after a `stop`
/// actually spawns a thread, and `stop` on an already-stopped spinner is a
/// no-op.
pub struct Spinner {
    enabled: bool,
    running: AtomicBool,
    stop_flag: Arc<AtomicBool>,
    handle: Mutex<Option<JoinHandle<()>>>,
    // UX-39: live token-counter state (see the module doc's "live streaming
    // token counter" section). `turn_bytes` resets every new user turn
    // (`reset_turn`); `session_bytes` accumulates for this `Spinner`'s whole
    // lifetime (one CLI process).
    turn_bytes: AtomicU64,
    session_bytes: AtomicU64,
    counter_drawn: AtomicBool,
    last_counter_render: Mutex<Instant>,
}

impl Spinner {
    /// A spinner gated on the real environment (stderr tty, `NO_COLOR`,
    /// `TERM=dumb`, and `quiet`). When gating disallows it, every method on
    /// the returned `Spinner` is a no-op that never touches stderr — this is
    /// the single choke point that keeps `--output-format json` / piped /
    /// `NO_COLOR` runs byte-clean.
    pub fn new(quiet: bool) -> Self {
        Self::with_enabled(should_show_spinner_now(quiet))
    }

    /// Construct with an explicit enabled/disabled decision — used by tests
    /// (and available to callers that already computed gating themselves).
    pub(crate) fn with_enabled(enabled: bool) -> Self {
        Self {
            enabled,
            running: AtomicBool::new(false),
            stop_flag: Arc::new(AtomicBool::new(false)),
            handle: Mutex::new(None),
            turn_bytes: AtomicU64::new(0),
            session_bytes: AtomicU64::new(0),
            counter_drawn: AtomicBool::new(false),
            // Backdated so the very first `render_counter` after a turn
            // starts always draws immediately rather than waiting out a
            // full throttle window (`checked_sub` guards the (practically
            // unreachable) case of a monotonic clock younger than the
            // throttle window itself).
            last_counter_render: Mutex::new(
                Instant::now()
                    .checked_sub(COUNTER_THROTTLE)
                    .unwrap_or_else(Instant::now),
            ),
        }
    }

    /// Start animating (after `START_DELAY`) with the given label, e.g.
    /// `"Thinking…"` or `"Working…"`. No-op if disabled or already running.
    pub fn start(&self, label: &str) {
        if !self.enabled {
            return;
        }
        // Only the transition false -> true actually spawns a thread.
        if self.running.swap(true, Ordering::AcqRel) {
            return;
        }
        self.stop_flag.store(false, Ordering::Release);
        let stop_flag = self.stop_flag.clone();
        let label = label.to_string();
        let handle = thread::spawn(move || spin(&stop_flag, &label));
        *self.handle.lock().unwrap() = Some(handle);
    }

    /// Stop animating and clear the line, if a frame was ever drawn. No-op
    /// if not running (including when disabled, since it's never running).
    /// Blocks briefly (bounded by `POLL_INTERVAL`) for the render thread to
    /// acknowledge the stop and finish clearing, so callers can rely on the
    /// line being clean the instant `stop()` returns.
    pub fn stop(&self) {
        if !self.running.swap(false, Ordering::AcqRel) {
            return;
        }
        self.stop_flag.store(true, Ordering::Release);
        if let Some(handle) = self.handle.lock().unwrap().take() {
            let _ = handle.join();
        }
    }

    /// UX-39: reset the "this turn" counter to zero. Call once, immediately
    /// before `start("Thinking…")`, at the TRUE beginning of a new
    /// `agent.send()`/`agent.send_with_images()` call — never on the
    /// mid-turn restarts `streaming_sink` issues after a tool call
    /// completes, since those continue the SAME turn (the counter must keep
    /// accumulating across a turn's tool round-trips, not zero between
    /// them). The "session" total is never reset by this call — it
    /// accumulates for this `Spinner`'s whole lifetime (one CLI process /
    /// one REPL session). No-op when disabled.
    pub(crate) fn reset_turn(&self) {
        if !self.enabled {
            return;
        }
        self.turn_bytes.store(0, Ordering::Relaxed);
    }

    /// UX-39: record a streamed chunk of assistant text toward both the
    /// "this turn" and "session" running byte totals. No-op when disabled,
    /// so a piped/`--quiet`/non-tty/`--output-format json` run never even
    /// pays for the extra atomic adds. Does not itself draw anything —
    /// pair with `render_counter`.
    pub(crate) fn record_delta(&self, text: &str) {
        if !self.enabled {
            return;
        }
        let bytes = text.len() as u64;
        self.turn_bytes.fetch_add(bytes, Ordering::Relaxed);
        self.session_bytes.fetch_add(bytes, Ordering::Relaxed);
    }

    /// UX-39: redraw the live counter line on stderr, throttled to at most
    /// once per [`COUNTER_THROTTLE`] (the very first call after a
    /// `reset_turn` always draws immediately — see the backdated initial
    /// value of `last_counter_render`). No-op when disabled — the same
    /// choke point shape as the spinner's own `enabled` gate, so
    /// `--output-format json`/piped/`NO_COLOR`/`--quiet` runs stay
    /// byte-clean by construction.
    ///
    /// Writes `\r<text>\x1b[K` (return to column 0, print, erase to end of
    /// line) rather than clear-then-write, so a shorter redraw never leaves
    /// a trailing fragment of a longer previous one, and so the line never
    /// flashes empty between redraws.
    pub(crate) fn render_counter(&self) {
        if !self.enabled {
            return;
        }
        {
            let mut last = self.last_counter_render.lock().unwrap();
            if last.elapsed() < COUNTER_THROTTLE {
                return;
            }
            *last = Instant::now();
        }

        // The same `ceil(bytes / 4)` heuristic as
        // `supercode::tokens::estimate_tokens`, applied to a running byte
        // total instead of a materialized string (avoids retaining the
        // whole streamed reply just to re-estimate it on every redraw).
        let turn_tok = self.turn_bytes.load(Ordering::Relaxed).div_ceil(4);
        let session_tok = self.session_bytes.load(Ordering::Relaxed).div_ceil(4);

        let mut out = std::io::stderr();
        let _ = write!(
            out,
            "\rthis turn: ~{turn_tok} tok · session: ~{session_tok} tok\x1b[K"
        );
        let _ = out.flush();
        self.counter_drawn.store(true, Ordering::Release);
    }

    /// UX-39: clear the live counter line, if one is currently drawn —
    /// idempotent (a no-op if nothing was drawn), same teardown discipline
    /// as the animated spinner. Called at the top of every sink event
    /// (alongside `stop()`) so whatever renders next — a tool-call trace
    /// line, the "Thinking…" spinner restarting, or nothing at all once the
    /// turn is over — never has to share the line with a stale counter.
    /// Also called explicitly from `race_ctrl_c`'s Ctrl-C arm: a mid-stream
    /// SIGINT drops the in-flight turn's future before any further sink
    /// event would otherwise have cleared it naturally.
    pub(crate) fn clear_counter(&self) {
        if !self.counter_drawn.swap(false, Ordering::AcqRel) {
            return;
        }
        let mut out = std::io::stderr();
        let _ = write!(out, "\r\x1b[2K");
        let _ = out.flush();
    }
}

impl Drop for Spinner {
    fn drop(&mut self) {
        // Belt-and-suspenders teardown on every exit path (early return,
        // `?`, panic-unwind) that didn't already call `stop()`/
        // `clear_counter()` explicitly.
        self.stop();
        self.clear_counter();
    }
}

/// The render-thread body: wait `START_DELAY` (bailing early if stopped
/// before it elapses, so a fast response never draws anything), then animate
/// until told to stop, then clear the line. Only reachable via `thread::spawn`
/// in [`Spinner::start`], which already checked `enabled`.
fn spin(stop_flag: &AtomicBool, label: &str) {
    let started = Instant::now();
    while started.elapsed() < START_DELAY {
        if stop_flag.load(Ordering::Acquire) {
            return; // stopped before the delay elapsed: nothing was drawn.
        }
        thread::sleep(POLL_INTERVAL);
    }

    let mut out = std::io::stderr();
    let mut frame = 0usize;
    loop {
        if stop_flag.load(Ordering::Acquire) {
            break;
        }
        let elapsed = started.elapsed().as_secs_f32();
        let _ = write!(
            out,
            "\r{} {label} ({elapsed:.1}s)",
            FRAMES[frame % FRAMES.len()]
        );
        let _ = out.flush();
        frame += 1;

        let deadline = Instant::now() + FRAME_INTERVAL;
        while Instant::now() < deadline {
            if stop_flag.load(Ordering::Acquire) {
                break;
            }
            thread::sleep(POLL_INTERVAL);
        }
    }
    // At least one frame was drawn to reach here — clear it: return to
    // column 0 and erase to end of line, leaving no residue.
    let _ = write!(out, "\r\x1b[2K");
    let _ = out.flush();
}

/// Run a synchronous, possibly-slow local operation (UX-15 dev/03: `audit`/
/// `convert` on a large corpus) with a `"Working…"` spinner, gated exactly
/// like the model-wait spinner. Frozen-terminal feedback for local ops that
/// have no incremental progress hook to drive a real progress bar.
pub fn with_spinner<T>(quiet: bool, f: impl FnOnce() -> T) -> T {
    let spinner = Spinner::new(quiet);
    spinner.start("Working…");
    let out = f();
    spinner.stop();
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- should_show_spinner: the gating predicate, unit-tested like
    // ui::detect_color_level (non-vacuous: each case flips exactly one input
    // and checks the boolean actually changes). ----

    #[test]
    fn shows_on_a_plain_interactive_tty() {
        assert!(should_show_spinner(false, false, false, true));
    }

    #[test]
    fn suppressed_when_no_color_is_set() {
        assert!(!should_show_spinner(true, false, false, true));
    }

    #[test]
    fn suppressed_in_quiet_mode() {
        assert!(!should_show_spinner(false, true, false, true));
    }

    /// UX-38: the real `--quiet`/`-q` flag (or `SUPERCODE_QUIET`) forces
    /// this off even on an otherwise-perfect interactive tty — the case a
    /// bare non-tty check alone (`suppressed_when_stderr_is_not_a_tty`)
    /// can't cover, since a `--quiet` run can absolutely happen on a real
    /// terminal (a human deliberately asking for scripting-quiet output).
    /// `main.rs::effective_quiet(cli)` (`cli.quiet || env_quiet()`) is what
    /// callers now pass as this `quiet` argument at every `Spinner::new`/
    /// `with_spinner` call site — this predicate is the single place that
    /// decision is honored.
    #[test]
    fn quiet_flag_wins_even_on_a_perfectly_normal_interactive_tty() {
        assert!(should_show_spinner(false, false, false, true)); // sanity: would show without quiet
        assert!(!should_show_spinner(
            /* no_color */ false, /* quiet */ true, /* term_dumb */ false,
            /* stderr_is_tty */ true,
        ));
    }

    #[test]
    fn suppressed_on_dumb_terminal() {
        assert!(!should_show_spinner(false, false, true, true));
    }

    #[test]
    fn suppressed_when_stderr_is_not_a_tty() {
        assert!(!should_show_spinner(false, false, false, false));
    }

    #[test]
    fn suppressed_when_stderr_is_not_a_tty_even_with_everything_else_favorable() {
        // Piped/redirected stderr (the `run ... | cat` / CI / json case) is
        // the byte-cleanliness gate: nothing else should be able to
        // override it back on.
        assert!(!should_show_spinner(false, false, false, false));
    }

    #[test]
    fn multiple_suppressors_still_suppress() {
        assert!(!should_show_spinner(true, true, true, false));
    }

    // ---- Spinner: an enabled-but-never-started-past-the-delay spinner
    // draws nothing; a disabled spinner's start()/stop() are true no-ops. ----

    #[test]
    fn disabled_spinner_start_stop_is_a_no_op() {
        let s = Spinner::with_enabled(false);
        s.start("Thinking…");
        // Not running: stop() must take the "not running" early-return path
        // (nothing to join).
        s.stop();
    }

    #[test]
    fn enabled_spinner_stopped_before_delay_elapses_draws_nothing() {
        // Regression guard for the "fast responses don't flash" requirement:
        // starting then immediately stopping (well under START_DELAY) must
        // return promptly and must not have spawned a lingering thread.
        let s = Spinner::with_enabled(true);
        s.start("Thinking…");
        s.stop();
        // A second start/stop cycle should behave identically (idempotent,
        // no leftover state from the first).
        s.start("Thinking…");
        s.stop();
    }

    #[test]
    fn start_is_idempotent_while_running() {
        let s = Spinner::with_enabled(true);
        s.start("Thinking…");
        s.start("Thinking…"); // no-op: already running, must not double-spawn
        s.stop();
    }

    // ---- UX-39: live token counter — record_delta/reset_turn/
    // render_counter/clear_counter. `mod tests` is a descendant module of
    // `spinner`, so it can read the private counter fields directly to
    // assert on state a stderr-output-only check couldn't observe. ----

    #[test]
    fn record_delta_accumulates_turn_and_session_bytes() {
        let s = Spinner::with_enabled(true);
        s.record_delta("hello"); // 5 bytes
        s.record_delta(" world"); // 6 bytes
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), 11);
        assert_eq!(s.session_bytes.load(Ordering::Relaxed), 11);
    }

    #[test]
    fn record_delta_is_a_true_no_op_when_disabled() {
        // Byte-cleanliness: a disabled counter (piped/--quiet/json/non-tty)
        // must not even accumulate bytes it will never render.
        let s = Spinner::with_enabled(false);
        s.record_delta("hello world");
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), 0);
        assert_eq!(s.session_bytes.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn reset_turn_zeroes_this_turn_but_not_session() {
        // The core semantic this ticket depends on: session accumulates for
        // the whole process, "this turn" only for the current turn — a tool
        // round-trip's mid-turn spinner restart must NOT call this (that's
        // enforced by main.rs's call sites, not by this type), but a brand
        // new `agent.send()` must.
        let first = "first turn output";
        let second = "second turn";
        let s = Spinner::with_enabled(true);
        s.record_delta(first);
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), first.len() as u64);
        s.reset_turn();
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), 0);
        assert_eq!(
            s.session_bytes.load(Ordering::Relaxed),
            first.len() as u64,
            "session total must survive a turn reset"
        );
        s.record_delta(second);
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), second.len() as u64);
        assert_eq!(
            s.session_bytes.load(Ordering::Relaxed),
            (first.len() + second.len()) as u64
        );
    }

    #[test]
    fn reset_turn_is_a_no_op_when_disabled() {
        let s = Spinner::with_enabled(false);
        s.reset_turn(); // must not panic on a disabled spinner
        assert_eq!(s.turn_bytes.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn render_counter_draws_when_enabled_and_due() {
        let s = Spinner::with_enabled(true);
        s.record_delta("some streamed text");
        assert!(!s.counter_drawn.load(Ordering::Acquire));
        s.render_counter();
        assert!(
            s.counter_drawn.load(Ordering::Acquire),
            "first render after construction must draw immediately (backdated throttle)"
        );
    }

    #[test]
    fn render_counter_is_a_no_op_when_disabled() {
        let s = Spinner::with_enabled(false);
        s.record_delta("text");
        s.render_counter();
        assert!(!s.counter_drawn.load(Ordering::Acquire));
    }

    #[test]
    fn render_counter_is_throttled_within_the_window() {
        // Non-vacuous throttle check: clear the flag after the first draw,
        // then immediately request another redraw — since no time has
        // passed, the throttle must suppress it (flag stays false) rather
        // than redrawing on every single delta.
        let s = Spinner::with_enabled(true);
        s.record_delta("a");
        s.render_counter();
        assert!(s.counter_drawn.load(Ordering::Acquire));
        s.clear_counter();
        assert!(!s.counter_drawn.load(Ordering::Acquire));

        s.record_delta("b");
        s.render_counter(); // called <120ms after the first — must be throttled
        assert!(
            !s.counter_drawn.load(Ordering::Acquire),
            "a redraw inside COUNTER_THROTTLE must be suppressed"
        );
    }

    #[test]
    fn clear_counter_is_idempotent_when_nothing_was_drawn() {
        let s = Spinner::with_enabled(true);
        s.clear_counter(); // no-op: nothing drawn yet
        assert!(!s.counter_drawn.load(Ordering::Acquire));
        s.clear_counter(); // still a no-op, must not panic or misbehave
        assert!(!s.counter_drawn.load(Ordering::Acquire));
    }

    #[test]
    fn clear_counter_resets_the_drawn_flag() {
        let s = Spinner::with_enabled(true);
        s.record_delta("hi");
        s.render_counter();
        assert!(s.counter_drawn.load(Ordering::Acquire));
        s.clear_counter();
        assert!(!s.counter_drawn.load(Ordering::Acquire));
    }

    /// The counter's `ceil(bytes / 4)` math must agree with the shared
    /// `supercode::tokens::estimate_tokens` heuristic it's documented as
    /// reusing — this pins that equivalence so the two can't silently drift
    /// (e.g. one switching to `/3` or truncating instead of ceiling).
    #[test]
    fn token_math_matches_the_shared_estimator() {
        for sample in ["", "a", "abcd", "abcde", "hello, world! this streams."] {
            let bytes = sample.len() as u64;
            let from_bytes = bytes.div_ceil(4);
            let from_estimator = supercode::tokens::estimate_tokens(sample);
            assert_eq!(
                from_bytes, from_estimator,
                "byte-count formula must match estimate_tokens for {sample:?}"
            );
        }
    }
}