cmd-usage 0.7.0

Live Command Code (commandcode.ai) usage dashboard: credits, 5-hour and weekly windows, plan limits. Watch mode or one-shot.
Documentation
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
use super::render::*;
use crate::render::Snapshot;

// Plan-name/cap, money, compact, rel_time, and ISO cases are covered by the
// shared conformance vectors in core (conformance.json) — only presentation
// (bars, window lines, tables, templates) is asserted here.

#[test]
fn bar_boundaries() {
    // bar() embeds a colored % label; assert fill/empty chars
    let fill = |used: f64, cap: f64, w: usize| {
        let b = bar(used, cap, w);
        b.chars().filter(|c| *c == '━').count()
    };
    let empty = |used: f64, cap: f64, w: usize| {
        let b = bar(used, cap, w);
        b.chars().filter(|c| *c == '╱').count()
    };
    assert_eq!(fill(0.0, 10.0, 20), 0);
    assert_eq!(empty(0.0, 10.0, 20), 20);
    assert_eq!(fill(10.0, 10.0, 20), 20);
    assert_eq!(fill(0.0, 0.0, 20), 0); // no divide by zero
    assert_eq!(fill(50.0, 10.0, 20), 20); // clamp over-usage
    assert_eq!(fill(5.0, 10.0, 20), 10); // half fill rounds to 10
    assert_eq!(empty(5.0, 10.0, 20), 10);
    assert_eq!(fill(5.0, 10.0, 5), 3); // rounds to 3 of 5
    assert_eq!(empty(5.0, 10.0, 5), 2);
    assert!(bar(7.5, 10.0, 20).contains("75.0%"));
    assert!(bar(95.0, 10.0, 20).contains("100.0%")); // clamps at cap
}

#[test]
fn window_line_includes_elapsed_and_flag() {
    use crate::api::Window;
    let now = 1_000_000u64;
    let w = Window {
        used: 5.0,
        cap: 10.0,
        exceeded: false,
        reset_at: Some((now as f64 + 2.5 * 3600.0) * 1000.0),
    };
    let line = window_line("5-hour", &w, now, 20, Some(5 * 3600));
    assert!(line.contains("50%"));
    assert!(line.contains("$5.00 / $10.00"));
    assert!(line.contains("resets in"));

    let w_exceeded = Window {
        used: 15.0,
        cap: 10.0,
        exceeded: true,
        reset_at: None,
    };
    let line = window_line("Weekly", &w_exceeded, now, 20, Some(7 * 86400));
    assert!(line.contains("LIMIT EXCEEDED"));

    // no duration → no elapsed suffix
    let line = window_line("Monthly", &w, now, 20, None);
    assert!(!line.contains("elapsed"));
}

#[test]
fn pace_warns_only_after_10pct_elapsed() {
    use crate::api::Window;
    let now = 1_000_000u64;
    let d = 5 * 3600;

    // 5% elapsed, spend rate would hit cap → suppressed (too early).
    let start5 = now - d / 20;
    let w_early = Window {
        used: 5.0,
        cap: 10.0,
        exceeded: false,
        reset_at: Some((start5 + d) as f64 * 1000.0),
    };
    let line = window_line("5-hour", &w_early, now, 20, Some(d));
    assert!(
        !line.contains("on pace"),
        "must not warn at 5% elapsed: {line}"
    );

    // 10% elapsed, same spend rate → pace warning shown.
    let start10 = now - d / 10;
    let w_at = Window {
        used: 5.0,
        cap: 10.0,
        exceeded: false,
        reset_at: Some((start10 + d) as f64 * 1000.0),
    };
    let line = window_line("5-hour", &w_at, now, 20, Some(d));
    assert!(
        line.contains("on pace to hit cap in 30m"),
        "ETA must render the duration, not an absolute reset: {line}"
    );
    // importance order: pace before elapsed, so width-clipped watch frames
    // keep the warning and drop the informational elapsed share
    assert!(
        line.find("on pace").unwrap() < line.find("window 10%").unwrap(),
        "pace must precede elapsed: {line}"
    );
}

#[test]
fn plans_table_marks_current_by_exact_name() {
    let out = plans_table("individual-goat", false);
    assert!(out.contains("*GOAT"));
    assert!(
        !out.contains("*Go "),
        "substring 'go' must not mark Go: {out}"
    );
    assert!(
        !out.contains('\x1b'),
        "colors=false must emit no ANSI: {out:?}"
    );
    let out = plans_table("unknown-plan", false);
    assert!(!out.contains('*'), "no current plan → no mark: {out}");
    // colors=true bolds the current row
    let out = plans_table("individual-goat", true);
    assert!(out.contains("\x1b[1m*GOAT"));
}

#[test]
fn plans_json_marks_current() {
    let out = plans_json("individual-goat");
    assert!(out.starts_with('[') && out.ends_with(']'));
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    let arr = v.as_array().unwrap();
    let goat = arr.iter().find(|p| p["name"] == "GOAT").unwrap();
    assert_eq!(goat["price"], "$10");
    assert_eq!(goat["creditsMonthly"], "$70");
    assert_eq!(goat["fiveHour"], "$14");
    assert_eq!(goat["weekly"], "$35");
    assert_eq!(goat["current"], true);
    let go = arr.iter().find(|p| p["name"] == "Go").unwrap();
    assert_eq!(go["price"], "$1");
    assert_eq!(go["current"], false);
}

#[test]
fn render_json_is_valid_and_complete() {
    let s = snapshot_fixture();
    let out = render_json(&s);
    assert!(out.starts_with('{') && out.ends_with('}'));
    assert!(out.contains("\"plan\":\"GOAT\""));
    assert!(out.contains("\"fiveHour\":{"));
    assert!(out.contains("\"error\":null"));
    // parse round-trip
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["plan"], "GOAT");
    assert_eq!(v["monthlyCap"], 70.0);
}

#[test]
fn plain_render_contains_sections() {
    let s = snapshot_fixture();
    let out = render_plain(&s);
    assert!(out.contains("Command Code Usage"));
    assert!(out.contains("GOAT"));
    assert!(out.contains("Credits:"));
    assert!(out.contains("5-hour:"));
    assert!(out.contains("Weekly:"));
    assert!(out.contains("Monthly:"));
    assert!(out.contains("Period:"));
    // parity with the colored dashboard: monthly quota, period end, and
    // elapsed share of each window
    assert!(out.contains("/ $70.00 monthly"));
    assert!(out.contains("Period ends "));
    assert!(out.contains("window ") && out.contains("% elapsed"));
}

#[test]
fn ansi_render_contains_sections_and_quota() {
    let s = snapshot_fixture();
    let out = render(&s, 20);
    assert!(out.contains("Command Code Usage"));
    assert!(out.contains("GOAT"));
    assert!(out.contains("$61.44 / $70.00 monthly"));
    assert!(out.contains("Usage windows"));
    assert!(out.contains("Monthly"));
    assert!(out.contains("This billing period"));
    assert!(out.contains("Requests"));
    // error rendering
    let mut err_s = snapshot_fixture();
    err_s.err = Some("boom".into());
    let out = render(&err_s, 20);
    assert!(out.contains("error:"));
    assert!(out.contains("boom"));
}

#[test]
fn render_free_plan_no_monthly_cap() {
    let mut s = snapshot_fixture();
    s.sub.plan_id = "free".into();
    let out = render(&s, 20);
    assert!(!out.contains("/ $70.00"));
    assert!(out.contains("$61.44 monthly")); // remaining shown, no quota
    let out_plain = render_plain(&s);
    assert!(out_plain.contains("$61.44 monthly"));
}

#[test]
fn plain_window_line_has_elapsed_and_pace() {
    // 10% elapsed, spend rate on track to hit cap before reset — same shape
    // the colored window_line test pins, so the two renderers agree.
    let now = 1_000_000;
    let w = crate::api::Window {
        used: 5.0,
        cap: 10.0,
        exceeded: false,
        reset_at: Some(1_016_200_000.0),
    };
    let line = crate::render::plain_window_line("5-hour", &w, now, Some(18_000));
    assert!(line.contains("window 10% elapsed"), "{line}");
    assert!(line.contains("on pace to hit cap in"), "{line}");
    // importance order: pace (actionable) before elapsed (informational), so a
    // width-clipped watch frame drops elapsed first
    assert!(
        line.find("on pace").unwrap() < line.find("window 10%").unwrap(),
        "{line}"
    );
    assert!(
        !line.contains("\x1b"),
        "plain output must carry no SGR: {line}"
    );
}

#[test]
fn plain_window_line_flags_exceeded() {
    let now = 1_000_000;
    let w = crate::api::Window {
        used: 15.0,
        cap: 10.0,
        exceeded: true,
        reset_at: Some(1_016_200_000.0),
    };
    let line = crate::render::plain_window_line("Weekly", &w, now, None);
    assert!(line.contains("LIMIT EXCEEDED"), "{line}");
    assert!(
        !line.contains("elapsed"),
        "no duration → no elapsed: {line}"
    );
}

fn snapshot_fixture() -> Snapshot {
    Snapshot {
        sub: crate::api::SubData {
            status: "active".into(),
            plan_id: "individual-goat".into(),
            current_period_start: Some("2026-08-27T12:23:00.000Z".into()),
            current_period_end: Some("2026-09-27T12:23:00.000Z".into()),
        },
        credits: crate::api::CreditsResp {
            credits: crate::api::Credits {
                monthly_credits: 61.44,
                purchased_credits: 0.0,
                free_credits: 0.0,
            },
            window_limits: crate::api::WindowLimits {
                five_hour: Some(crate::api::Window {
                    used: 2.79,
                    cap: 14.0,
                    exceeded: false,
                    reset_at: Some(1_789_368_000_000.0),
                }),
                weekly: Some(crate::api::Window {
                    used: 2.79,
                    cap: 35.0,
                    exceeded: false,
                    reset_at: Some(1_789_912_000_000.0),
                }),
            },
        },
        summary: crate::api::UsageSummary {
            total_count: Some(733),
            total_cost: Some(9.25),
            success_rate: Some(100.0),
            total_tokens_in: Some(64_096_255),
            total_tokens_out: Some(236_706),
        },
        now: 1_789_368_000_000 / 1000,
        err: None,
    }
}

#[test]
fn statusline_templates() {
    use crate::report_render::{render_statusline, StatusData};
    let h5 = Some((2.79, 14.0));
    let wk = Some((3.61, 35.0));
    let d = |tpl_colors: bool, ascii: bool| StatusData {
        plan: "GOAT",
        monthly_remaining: 59.3,
        monthly_cap: 70.0,
        five_hour: &h5,
        weekly: &wk,
        five_hour_eta: None,
        weekly_eta: None,
        bar_width: 10,
        colors: tpl_colors,
        ascii,
    };

    // full template
    let d0 = d(true, false);
    let out = render_statusline("{plan} {credits}/{cap} · 5h {5h_bar} · wk {wk_bar}", &d0);
    assert!(out.contains("\x1b["));
    let plain = d(false, false);
    let out = render_statusline("{plan} {credits}/{cap} · 5h {5h_bar} · wk {wk_bar}", &plain);
    assert!(out.contains("GOAT"));
    assert!(out.contains("$59.30/$70.00"));
    assert!(out.contains("5h"));
    assert!(out.contains("wk"));
    assert!(!out.contains('\x1b'));

    // minimal: plan only
    let out = render_statusline("{plan}", &d0);
    assert_eq!(out, "GOAT");

    // pct placeholders
    let out = render_statusline("{5h_pct}|{wk_pct}", &d0);
    assert_eq!(out, "20%|10%");

    // used/cap
    let out = render_statusline("{5h_used} of {5h_cap}", &d0);
    assert_eq!(out, "$2.79 of $14.00");

    // credits_bar shows used % of monthly cap
    let out = render_statusline("{credits_bar}", &d0);
    assert!(out.contains("15.3%"));

    // unknown placeholders dropped
    let out = render_statusline("{plan} {bogus} end", &d0);
    assert_eq!(out, "GOAT  end");

    // unclosed brace passes through verbatim
    let out = render_statusline("{plan} {oops", &d0);
    assert_eq!(out, "GOAT {oops");

    // ascii bars
    let d1 = d(false, true);
    let out = render_statusline("{5h_bar}", &d1);
    assert!(out.contains('#'));
    assert!(out.contains('-'));
    assert!(!out.contains('━'));

    // colors stripped when colors=false
    let d2 = d(false, false);
    let out = render_statusline("{credits}", &d2);
    assert!(!out.contains('\x1b'));
    assert_eq!(out, "$59.30");

    // multi-line templates allowed
    let out = render_statusline("{plan}\n{credits_bar}", &d0);
    assert!(out.contains('\n'));

    // eta placeholders render when set, empty otherwise
    assert_eq!(render_statusline("{5h_eta}", &d0), "");
    let deta = StatusData {
        plan: "GOAT",
        monthly_remaining: 1.0,
        monthly_cap: 70.0,
        five_hour: &h5,
        weekly: &wk,
        five_hour_eta: Some("on pace to hit cap in 1h 2m".into()),
        weekly_eta: None,
        bar_width: 10,
        colors: false,
        ascii: false,
    };
    assert_eq!(
        render_statusline("{5h_eta}|{wk_eta}", &deta),
        "on pace to hit cap in 1h 2m|"
    );

    // zero-cap plan: bars show 0%, no divide-by-zero
    let h5z: Option<(f64, f64)> = None;
    let dz = StatusData {
        plan: "Free",
        monthly_remaining: 0.0,
        monthly_cap: 0.0,
        five_hour: &h5z,
        weekly: &h5z,
        five_hour_eta: None,
        weekly_eta: None,
        bar_width: 10,
        colors: true,
        ascii: false,
    };
    let out = render_statusline("{plan} {5h_pct} {wk_pct} {credits_bar}", &dz);
    assert!(out.contains("0%"));
}

#[test]
fn sparkline_small_deltas_visible() {
    // tiny recent delta next to a big old spike must not render as zero bar
    let out = sparkline(&[0.5, 0.0, 0.02]);
    assert_ne!(out.chars().last(), Some('▁'));
    // zero deltas still render as zero bar
    let out = sparkline(&[0.5, 0.0, 0.0]);
    assert_eq!(out.chars().last(), Some('▁'));
}

#[test]
fn sparkline_shapes() {
    // flat → all lowest bar
    assert_eq!(sparkline(&[1.0, 1.0, 1.0]), "███"); // flat values scale to full-height max
                                                    // rising trend
    assert_eq!(sparkline(&[0.0, 5.0, 10.0]), "▁▅█"); // 0/10→▁, 5/10→mid, 10/10→full
                                                     // fewer than 2 points → empty
    assert_eq!(sparkline(&[]), "");
    assert_eq!(sparkline(&[5.0]), "");
    // all zeros → all low bars, no NaN panic
    assert_eq!(sparkline(&[0.0, 0.0]), "▁▁");
}

#[test]
fn update_box_borders_align_and_wraps() {
    let b = crate::render::update_box("update available 0.6.7 → 0.6.8", None, false);
    let lines: Vec<&str> = b.lines().collect();
    assert_eq!(lines.len(), 3);
    let w = lines[0].chars().count();
    assert!(lines.iter().all(|l| l.chars().count() == w), "{b}");
    assert!(b.contains("update available"), "{b}");
    assert!(b.starts_with('╭') && b.trim_end().ends_with('╯'), "{b}");

    // narrow terminal wraps the body inside the box
    let narrow = crate::render::update_box("aaa bbb ccc ddd eee fff", Some(16), false);
    assert!(narrow.lines().count() > 3, "{narrow}");
    let nw = narrow.lines().next().unwrap().chars().count();
    assert!(narrow.lines().all(|l| l.chars().count() == nw), "{narrow}");

    // ANSI colouring keeps the same number of lines/borders
    let colored = crate::render::update_box("update available", None, true);
    assert_eq!(colored.lines().count(), 3, "{colored}");
    assert!(colored.contains("\x1b[33m") && colored.contains("update available"));
}