linesmith 0.1.3

A Rust status line for Claude Code and other AI coding CLIs
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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use std::io::Cursor;
use std::process::Command;
use std::str::FromStr;

const CLAUDE_MINIMAL: &str = include_str!("fixtures/claude_minimal.json");
const CLAUDE_WORKTREE: &str = include_str!("fixtures/claude_worktree.json");

/// Run `git <args>` inside `cwd` with an isolated config (global /
/// system configs bypassed, hooks disabled, signing off, default
/// branch pinned). Panics with the child's stderr + exit code on
/// failure so CI logs carry enough context to diagnose without
/// re-running locally.
fn run_git(cwd: &std::path::Path, args: &[&str]) {
    let out = Command::new("git")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .args(["-c", "commit.gpgsign=false"])
        .args(["-c", "core.hooksPath=/dev/null"])
        .args(["-c", "init.defaultBranch=main"])
        .args(["-c", "user.email=t@t", "-c", "user.name=t"])
        .arg("-C")
        .arg(cwd)
        .args(args)
        .output()
        .expect("spawn git");
    assert!(
        out.status.success(),
        "git {args:?} in {cwd:?} exited {:?}\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn renders_model_and_workspace_when_outside_worktree() {
    let mut out = Vec::new();
    linesmith_core::run(Cursor::new(CLAUDE_MINIMAL), &mut out).expect("run ok");
    assert_eq!(
        String::from_utf8(out).expect("utf8"),
        "Claude Sonnet 4.6 linesmith\n"
    );
}

#[test]
fn renders_full_payload_with_cost_effort_and_workspace() {
    // Rate-limit segments are opt-in, so a first-run user doesn't
    // trigger a Keychain prompt from the default line.
    let mut out = Vec::new();
    linesmith_core::run(Cursor::new(CLAUDE_WORKTREE), &mut out).expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");

    for substring in [
        "Claude Sonnet 4.6",
        "42% · 200k",
        "$1.23",
        "high",
        "linesmith",
    ] {
        assert!(
            rendered.contains(substring),
            "expected {substring:?} in {rendered:?}"
        );
    }
    // Guard: workspace sources worktree-name from gix discovery now,
    // not stdin. `run()` leaves cwd unset, so the hybrid form must
    // NOT appear here — even though the fixture carries a
    // `git_worktree` field.
    assert!(
        !rendered.contains("linesmith/"),
        "workspace must not emit hybrid form without a real linked-worktree cwd: {rendered:?}"
    );
    for absent in ["5h", "7d", "rate_limit"] {
        assert!(
            !rendered.contains(absent),
            "{absent:?} should not appear without explicit opt-in ({rendered:?})",
        );
    }
    assert!(rendered.ends_with('\n'));
}

#[test]
fn malformed_json_exits_zero_with_marker_line() {
    let mut out = Vec::new();
    linesmith_core::run(Cursor::new(b"{not json"), &mut out).expect("run should not error");
    assert_eq!(String::from_utf8(out).expect("utf8"), "?\n");
}

#[test]
fn narrow_terminal_drops_cost_and_effort_first() {
    // Budget chosen so the two highest drop-priorities (cost, effort)
    // drop before context_window or workspace get touched.
    let mut out = Vec::new();
    linesmith_core::run_with_width(Cursor::new(CLAUDE_WORKTREE), &mut out, 40).expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");
    assert!(!rendered.contains("$1.23"), "cost should drop first");
    assert!(!rendered.contains("high"), "effort should drop second");
    assert!(rendered.contains("42% · 200k"));
    assert!(rendered.contains("linesmith"));
    assert!(
        !rendered.contains("linesmith/"),
        "no worktree cwd here: {rendered:?}"
    );
}

#[test]
fn extreme_narrow_keeps_only_lowest_priority_segments() {
    // Budget tight enough that only workspace (lowest drop-priority)
    // survives, even though context_window would fit alone.
    let mut out = Vec::new();
    linesmith_core::run_with_width(Cursor::new(CLAUDE_WORKTREE), &mut out, 10).expect("run ok");
    assert_eq!(String::from_utf8(out).expect("utf8"), "linesmith\n");
}

#[test]
fn xdg_plugin_renders_via_full_driver_path() {
    // Pins the `cli_main → load_plugins → build_segments → RhaiSegment::render`
    // chain end-to-end with a real .rhai file under XDG.
    use std::fs;
    use tempfile::TempDir;

    let xdg = TempDir::new().expect("tempdir");
    let segments_dir = xdg.path().join("linesmith").join("segments");
    fs::create_dir_all(&segments_dir).expect("mkdir");

    fs::write(
        segments_dir.join("echo.rhai"),
        r#"
        const ID = "echo";
        fn render(ctx) {
            #{ runs: [#{ text: ctx.config.text }] }
        }
        "#,
    )
    .expect("write plugin");

    let config_dir = xdg.path().join("linesmith");
    fs::write(
        config_dir.join("config.toml"),
        r#"
            [line]
            segments = ["echo"]
            [segments.echo]
            text = "hi-from-plugin"
        "#,
    )
    .expect("write config");

    let mut env = linesmith::CliEnv::for_tests();
    env.xdg_config_home = Some(xdg.path().as_os_str().to_owned());

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&stderr));
    assert_eq!(String::from_utf8(stdout).expect("utf8"), "hi-from-plugin\n");
}

#[test]
fn git_branch_renders_unborn_head_via_full_driver_path() {
    // End-to-end through cli_main: a freshly init'd repo fixture has
    // no commits, so HEAD is unborn and the segment renders the
    // symbolic-ref target (whatever init.defaultBranch resolves to).
    use tempfile::TempDir;

    let repo_dir = TempDir::new().expect("tempdir");
    gix::init(repo_dir.path()).expect("gix::init");

    let mut env = linesmith::CliEnv::for_tests();
    env.cwd = Some(repo_dir.path().to_path_buf());

    // Scope the segment list to just `git_branch` so the assertion
    // doesn't couple to the rest of the default line.
    let xdg = TempDir::new().expect("tempdir");
    let config_dir = xdg.path().join("linesmith");
    std::fs::create_dir_all(&config_dir).expect("mkdir");
    std::fs::write(
        config_dir.join("config.toml"),
        r#"
            [line]
            segments = ["git_branch"]
        "#,
    )
    .expect("write config");
    env.xdg_config_home = Some(xdg.path().as_os_str().to_owned());

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&stderr));
    let rendered = String::from_utf8(stdout).expect("utf8");
    // gix's default branch is `main` unless init.defaultBranch is
    // configured; accept either.
    assert!(
        rendered.starts_with("main") || rendered.starts_with("master"),
        "expected branch name at start, got {rendered:?}"
    );
}

/// Set up a primary checkout + one linked worktree via `git worktree
/// add`, returning `(primary_tempdir, worktree_parent_tempdir,
/// worktree_path)`. Tempdirs are held by the caller so the worktree
/// stays live for the duration of the test.
fn linked_worktree_fixture(
    name: &str,
) -> (tempfile::TempDir, tempfile::TempDir, std::path::PathBuf) {
    use tempfile::TempDir;

    let primary = TempDir::new().expect("primary tempdir");
    let wt_parent = TempDir::new().expect("worktree tempdir");
    run_git(primary.path(), &["init", "--quiet"]);
    run_git(
        primary.path(),
        &["commit", "--allow-empty", "-m", "seed", "--quiet"],
    );
    let worktree_dir = wt_parent.path().join(name);
    run_git(
        primary.path(),
        &[
            "worktree",
            "add",
            "--quiet",
            "-b",
            name,
            worktree_dir.to_str().expect("utf8 path"),
        ],
    );
    (primary, wt_parent, worktree_dir)
}

fn cli_env_with_config(
    worktree_dir: std::path::PathBuf,
    config_toml: &str,
) -> (linesmith::CliEnv, tempfile::TempDir) {
    use tempfile::TempDir;

    let xdg = TempDir::new().expect("xdg tempdir");
    let config_dir = xdg.path().join("linesmith");
    std::fs::create_dir_all(&config_dir).expect("mkdir");
    std::fs::write(config_dir.join("config.toml"), config_toml).expect("write config");

    let mut env = linesmith::CliEnv::for_tests();
    env.cwd = Some(worktree_dir);
    env.xdg_config_home = Some(xdg.path().as_os_str().to_owned());
    (env, xdg)
}

#[test]
fn renders_worktree_hybrid_with_real_linked_worktree() {
    let (_primary, _wt_parent, worktree_dir) = linked_worktree_fixture("feat-segments");
    let (env, _xdg) = cli_env_with_config(
        worktree_dir,
        r#"
            [line]
            segments = ["workspace"]
        "#,
    );

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&stderr));
    assert_eq!(
        String::from_utf8(stdout).expect("utf8"),
        "linesmith/feat-segments\n"
    );
}

#[test]
fn workspace_and_git_branch_coexist_on_linked_worktree() {
    // Spec §Coordination: both segments render distinct payloads on a
    // linked worktree. `workspace` shows the worktree name, `git_branch`
    // shows the branch. No suppression.
    let (_primary, _wt_parent, worktree_dir) = linked_worktree_fixture("feat-segments");
    let (env, _xdg) = cli_env_with_config(
        worktree_dir,
        r#"
            [line]
            segments = ["workspace", "git_branch"]
        "#,
    );

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&stderr));
    let rendered = String::from_utf8(stdout).expect("utf8");
    assert!(
        rendered.contains("linesmith/feat-segments"),
        "workspace hybrid missing: {rendered:?}"
    );
    assert!(
        rendered.contains("feat-segments") && rendered.matches("feat-segments").count() >= 2,
        "git_branch should render the branch name alongside workspace: {rendered:?}"
    );
}

#[test]
fn git_branch_renders_per_worktree_branch_not_main() {
    // Verifies git_branch reads HEAD from the linked worktree's own gitdir,
    // not the primary's. `feat-wt-xyz` is unknown to the primary, so any
    // rendering of `main` is a definite bug.
    let (_primary, _wt_parent, worktree_dir) = linked_worktree_fixture("feat-wt-xyz");
    let (env, _xdg) = cli_env_with_config(
        worktree_dir,
        r#"
            [line]
            segments = ["git_branch"]
        "#,
    );

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&stderr));
    let rendered = String::from_utf8(stdout).expect("utf8");
    assert_eq!(
        rendered.trim_end(),
        "feat-wt-xyz",
        "git_branch must render the worktree branch, not main: {rendered:?}"
    );
}

#[test]
fn git_branch_hides_outside_repo() {
    use tempfile::TempDir;

    let cwd = TempDir::new().expect("tempdir");

    let mut env = linesmith::CliEnv::for_tests();
    env.cwd = Some(cwd.path().to_path_buf());

    let xdg = TempDir::new().expect("tempdir");
    let config_dir = xdg.path().join("linesmith");
    std::fs::create_dir_all(&config_dir).expect("mkdir");
    std::fs::write(
        config_dir.join("config.toml"),
        r#"
            [line]
            segments = ["git_branch", "model"]
        "#,
    )
    .expect("write config");
    env.xdg_config_home = Some(xdg.path().as_os_str().to_owned());

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let code = linesmith::cli_main(
        std::iter::empty::<&str>(),
        Cursor::new(CLAUDE_MINIMAL),
        &mut stdout,
        &mut stderr,
        &env,
    );
    assert_eq!(code, 0);
    let rendered = String::from_utf8(stdout).expect("utf8");
    // Only the model segment rendered; git_branch hid silently.
    assert_eq!(rendered, "Claude Sonnet 4.6\n");
}

#[test]
fn config_reorders_and_filters_segments() {
    // Config picks only model + workspace, in that custom order.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["workspace", "model"]
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let mut out = Vec::new();
    linesmith_core::run_with_segments_and_width(
        Cursor::new(CLAUDE_WORKTREE),
        &mut out,
        &segments,
        200,
    )
    .expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");
    assert_eq!(rendered, "linesmith Claude Sonnet 4.6\n");
}

#[test]
fn config_style_override_emits_sgr_bytes_end_to_end() {
    // TOML → SegmentOverride → parse_style → with_user_style → render_with_observers
    // pipeline: the model segment's rendered text should be wrapped in a
    // TrueColor-red + bold SGR prefix followed by a reset.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["model"]
            [segments.model]
            style = "fg:rgb(255, 0, 0) bold"
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let status_ctx = linesmith_core::input::parse(include_bytes!("fixtures/claude_minimal.json"))
        .expect("parse");
    let ctx = linesmith_core::data_context::DataContext::new(status_ctx);
    let mut warn = |_: &str| {};
    let mut observers = linesmith_core::layout::LayoutObservers::new(&mut warn);
    let line = linesmith_core::layout::render_with_observers(
        &segments,
        &ctx,
        200,
        &mut observers,
        linesmith_core::theme::default_theme(),
        linesmith_core::theme::Capability::TrueColor,
        false,
    );
    assert!(
        line.contains("\x1b[1;38;2;255;0;0m"),
        "expected bold + truecolor-red SGR prefix, got {line:?}"
    );
    assert!(line.contains("Claude Sonnet 4.6"));
    assert!(line.contains("\x1b[0m"), "expected SGR reset");
}

#[test]
fn config_style_override_invalid_warns_and_render_still_succeeds() {
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["model"]
            [segments.model]
            style = "role:mauve"
        "#,
    )
    .expect("parse");
    let mut warnings = Vec::new();
    let segments =
        linesmith_core::build_segments(Some(&cfg), None, |m| warnings.push(m.to_string()));
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].contains("segments.model.style"));
    assert!(warnings[0].contains("mauve"));
    let mut out = Vec::new();
    linesmith_core::run_with_segments_and_width(
        Cursor::new(CLAUDE_MINIMAL),
        &mut out,
        &segments,
        200,
    )
    .expect("run ok");
    // Render still succeeds; the bad override is skipped.
    assert!(String::from_utf8(out)
        .expect("utf8")
        .contains("Claude Sonnet 4.6"));
}

#[test]
fn model_format_compact_strips_context_word_end_to_end() {
    // Default `format = "compact"` strips the trailing word "context"
    // from `(X context)` parentheticals. Pins the from_extras wiring
    // (segments/mod.rs::built_in_by_id → ModelSegment::from_extras)
    // through the full Config → build_segments → render path.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["model"]
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let payload = br#"{
        "model": { "id": "claude-opus-4-7", "display_name": "Opus 4.7 (1M context)" },
        "session_id": "test-session",
        "cwd": "/home/dev/linesmith",
        "workspace": {
            "current_dir": ".",
            "project_dir": "/home/dev/linesmith",
            "added_dirs": [],
            "git_worktree": null
        }
    }"#;
    let mut out = Vec::new();
    linesmith_core::run_with_segments_and_width(
        Cursor::new(&payload[..]),
        &mut out,
        &segments,
        200,
    )
    .expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");
    assert!(rendered.contains("Opus 4.7 (1M)"), "got {rendered:?}");
    assert!(
        !rendered.contains("(1M context)"),
        "compact must drop the word: {rendered:?}"
    );
}

#[test]
fn model_format_full_preserves_anthropics_verbatim_string_end_to_end() {
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["model"]
            [segments.model]
            format = "full"
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let payload = br#"{
        "model": { "id": "claude-opus-4-7", "display_name": "Opus 4.7 (1M context)" },
        "session_id": "test-session",
        "cwd": "/home/dev/linesmith",
        "workspace": {
            "current_dir": ".",
            "project_dir": "/home/dev/linesmith",
            "added_dirs": [],
            "git_worktree": null
        }
    }"#;
    let mut out = Vec::new();
    linesmith_core::run_with_segments_and_width(
        Cursor::new(&payload[..]),
        &mut out,
        &segments,
        200,
    )
    .expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");
    assert!(
        rendered.contains("Opus 4.7 (1M context)"),
        "got {rendered:?}"
    );
}

#[test]
fn config_priority_override_flips_drop_order_under_pressure() {
    // With default priorities, a narrow terminal drops cost (192)
    // before model (64). Override model's priority to 250 and it drops
    // first instead.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["model", "cost"]
            [segments.model]
            priority = 250
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let mut out = Vec::new();
    // Budget tight enough to force one drop but fit the other.
    linesmith_core::run_with_segments_and_width(
        Cursor::new(CLAUDE_WORKTREE),
        &mut out,
        &segments,
        10,
    )
    .expect("run ok");
    let rendered = String::from_utf8(out).expect("utf8");
    // Model dropped; cost survived.
    assert!(!rendered.contains("Claude"));
    assert!(rendered.contains("$1.23"));
}

// Rate-limit pipeline end-to-end: pins TOML config → Config::from_str →
// build_segments → built_in_by_id → from_extras → render. A regression
// where built_in_by_id drops the `extras` arg on one arm would leave knobs
// silently inert: per-segment unit tests still pass, validate_keys still
// passes, and the segment renders with defaults.

fn ctx_with_endpoint_usage(
    api_json: serde_json::Value,
) -> linesmith_core::data_context::DataContext {
    let api: linesmith_core::data_context::UsageApiResponse =
        serde_json::from_value(api_json).expect("deserialize UsageApiResponse");
    let status_ctx = linesmith_core::input::parse(include_bytes!("fixtures/claude_minimal.json"))
        .expect("parse");
    let ctx = linesmith_core::data_context::DataContext::new(status_ctx);
    ctx.preseed_usage(Ok(linesmith_core::data_context::UsageData::Endpoint(
        api.into_endpoint_usage(),
    )))
    .expect("preseed_usage: cell already populated");
    ctx
}

fn render_rate_limit_line(
    segments: &[linesmith_core::segments::LineItem],
    ctx: &linesmith_core::data_context::DataContext,
) -> String {
    let mut warn = |_: &str| {};
    let mut observers = linesmith_core::layout::LayoutObservers::new(&mut warn);
    linesmith_core::layout::render_with_observers(
        segments,
        ctx,
        200,
        &mut observers,
        linesmith_core::theme::default_theme(),
        linesmith_core::theme::Capability::TrueColor,
        false,
    )
}

#[test]
fn rate_limit_5h_and_7d_progress_format_renders_block_chars_end_to_end() {
    // Threads `format = "progress"` through both percent-utilization
    // arms of built_in_by_id. Per-arm positional assertions catch a
    // one-arm extras-drop regression: line-wide `█`/`░` checks would
    // pass if either arm rendered a bar while the other fell back to
    // the percent default (`"7d: 30.0%"` is also a substring of a
    // valid progress line).
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["rate_limit_5h", "rate_limit_7d"]
            [segments.rate_limit_5h]
            format = "progress"
            [segments.rate_limit_7d]
            format = "progress"
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let ctx = ctx_with_endpoint_usage(serde_json::json!({
        "five_hour": { "utilization": 50.0 },
        "seven_day": { "utilization": 30.0 },
    }));
    let line = render_rate_limit_line(&segments, &ctx);
    let after_5h = line.split_once("5h: ").expect("5h label").1;
    assert!(
        after_5h.starts_with(''),
        "5h arm not in progress format: {line:?}"
    );
    let after_7d = line.split_once("7d: ").expect("7d label").1;
    assert!(
        after_7d.starts_with(''),
        "7d arm not in progress format: {line:?}"
    );
    assert!(
        line.contains(''),
        "bar should not be fully filled: {line:?}"
    );
    assert!(
        line.contains("50.0%"),
        "5h trailing percent missing in {line:?}"
    );
    assert!(
        line.contains("30.0%"),
        "7d trailing percent missing in {line:?}"
    );
}

#[test]
fn rate_limit_5h_and_7d_reset_progress_format_renders_progress_bar_end_to_end() {
    // The reset arms are separate from the utilization arms in
    // built_in_by_id and from each other (5h_reset and 7d_reset are
    // independent match arms). Per-arm positional assertions catch a
    // one-arm extras-drop on either. Progress exercises format_reset's
    // Progress branch via the spent-time fraction.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["rate_limit_5h_reset", "rate_limit_7d_reset"]
            [segments.rate_limit_5h_reset]
            format = "progress"
            [segments.rate_limit_7d_reset]
            format = "progress"
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    // Percent format rounds to 1 decimal, so microsecond drift between
    // these `now()` calls and the segment's own `now()` reads as 0.0%
    // — no slack needed (unlike the Duration format's minute-truncation).
    let five_h_resets_at = jiff::Timestamp::now() + jiff::SignedDuration::from_hours(2);
    let seven_d_resets_at = jiff::Timestamp::now() + jiff::SignedDuration::from_hours(48);
    let ctx = ctx_with_endpoint_usage(serde_json::json!({
        "five_hour": {
            "utilization": 50.0,
            "resets_at": five_h_resets_at.to_string(),
        },
        "seven_day": {
            "utilization": 30.0,
            "resets_at": seven_d_resets_at.to_string(),
        },
    }));
    let line = render_rate_limit_line(&segments, &ctx);
    let after_5h = line.split_once("5h reset: ").expect("5h reset label").1;
    assert!(
        after_5h.starts_with(''),
        "5h_reset arm not in progress format: {line:?}"
    );
    let after_7d = line.split_once("7d reset: ").expect("7d reset label").1;
    assert!(
        after_7d.starts_with(''),
        "7d_reset arm not in progress format: {line:?}"
    );
    assert!(
        line.contains(''),
        "bar should not be fully filled: {line:?}"
    );
}

#[test]
fn extra_usage_label_knob_applies_end_to_end() {
    // extra_usage is its own arm in built_in_by_id (not under the
    // rate_limit:: module). Pinning the label knob catches a dropped
    // extras arg here that the rate-limit tests above would miss.
    let cfg = linesmith_core::config::Config::from_str(
        r#"
            [line]
            segments = ["extra_usage"]
            [segments.extra_usage]
            label = "overage"
        "#,
    )
    .expect("parse");
    let segments = linesmith_core::build_segments(Some(&cfg), None, |_| {});
    let ctx = ctx_with_endpoint_usage(serde_json::json!({
        "extra_usage": {
            "is_enabled": true,
            "monthly_limit": 100.0,
            "used_credits": 40.0,
            "currency": "USD",
        },
    }));
    let line = render_rate_limit_line(&segments, &ctx);
    assert!(line.contains("overage: $60.00"), "{line:?}");
    assert!(
        !line.contains("extra:"),
        "default label leaked through: {line:?}"
    );
}