openlatch-client 0.6.0

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
//! The rail writer.
//!
//! ```text
//! ┌  Setting up this machine
//! │
//! ◇  Checked this machine · found Cline
//! │
//! ⠋  Connecting Cline…              ← the active block: the only thing ever redrawn
//! ```
//!
//! Finished lines are appended and never touched again, so scrollback stays
//! intact and a resize cannot smear them. Only the active block — a stage's
//! spinner (with the notes that arrived while it runs) or a select — is
//! cleared and redrawn. Notes and detail that arrive during a stage are held
//! and written under its result line once it closes, in arrival order.

use std::io::Write;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use super::card::{self, Card, Verdict};
use super::log::Transcript;
use super::select::{self, KeyState, LineRead, Select, SelectOutcome};
use super::term::{Caps, Mode};
use super::{paint, style, wrap};
use crate::error::OlError;

/// Where the rail's lines go.
pub enum Out {
    /// The real stderr.
    Term(console::Term),
    /// An in-memory screen, for tests: clearing removes lines from the end.
    Buffer(Arc<Mutex<Vec<String>>>),
}

impl Out {
    fn line(&self, text: &str) {
        match self {
            // A failed write to stderr has nowhere to be reported.
            Self::Term(t) => {
                let _ = t.write_line(text);
            }
            Self::Buffer(b) => lock(b).extend(text.split('\n').map(str::to_string)),
        }
    }

    /// Write without a newline (a prompt the cursor waits on).
    fn prompt(&self, text: &str) {
        match self {
            Self::Term(t) => {
                let mut t = t.clone();
                let _ = t.write_all(text.as_bytes());
                let _ = t.flush();
            }
            Self::Buffer(b) => lock(b).push(text.to_string()),
        }
    }

    fn clear(&self, n: usize) {
        match self {
            Self::Term(t) => {
                let _ = t.clear_last_lines(n);
            }
            Self::Buffer(b) => {
                let mut b = lock(b);
                let keep = b.len().saturating_sub(n);
                b.truncate(keep);
            }
        }
    }
}

fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// A line held while a stage runs.
enum Held {
    Note(String),
    /// Part of the active block only — a sign-in instruction, a link to open.
    /// Drawn dim under the spinner and gone once the stage closes; logged.
    Hint(String),
    /// A [`Held::Hint`] ending in a URL that is never wrapped, so it can be
    /// copied or clicked whole: `(lead, url)`.
    Link(String, String),
    Detail(String),
}

/// The stage currently running.
struct Stage {
    index: usize,
    /// What the stage is, for a failure: `Start OpenLatch` → `Start OpenLatch failed`.
    name: String,
    running: String,
    /// What the spinner shows: `running`, or the latest [`Rail::progress`].
    shown: String,
    done: String,
    held: Vec<Held>,
    /// Plain mode: the `[n/N] <running>...` line was written, because a note
    /// arrived before the stage closed and needed a heading.
    announced: bool,
    /// The latest [`Rail::meter`]: `(fraction, tail)`, drawn in Live mode.
    meter: Option<(Option<f64>, String)>,
    /// Append mode: the highest 25 % milestone already written.
    milestone: u8,
    spinner: Option<indicatif::ProgressBar>,
}

/// Columns of the byte bar a Live meter draws, and of the bar it falls back
/// to when the full one leaves no room.
const METER: usize = 24;
const METER_SHORT: usize = 10;

/// A rail over one command's run.
pub struct Rail {
    caps: Caps,
    out: Out,
    log: Option<Transcript>,
    total: usize,
    count: usize,
    stage: Option<Stage>,
}

impl Rail {
    /// A rail of `total` stages writing to `out`.
    pub fn new(caps: Caps, out: Out, log: Option<Transcript>, total: usize) -> Self {
        Self {
            caps,
            out,
            log,
            total,
            count: 0,
            stage: None,
        }
    }

    /// A rail on an in-memory screen, for tests. Returns the screen.
    pub fn buffer(caps: Caps, total: usize) -> (Self, Arc<Mutex<Vec<String>>>) {
        let screen = Arc::new(Mutex::new(Vec::new()));
        (
            Self::new(caps, Out::Buffer(screen.clone()), None, total),
            screen,
        )
    }

    /// The capabilities this rail draws with.
    pub fn caps(&self) -> &Caps {
        &self.caps
    }

    /// Where the transcript is written, if one could be opened.
    pub fn log_path(&self) -> Option<&std::path::Path> {
        self.log.as_ref().map(Transcript::path)
    }

    /// See [`Transcript::take_back`].
    pub fn take_back_log(&mut self, dest_dir: &std::path::Path) {
        if let Some(log) = self.log.as_mut() {
            log.take_back(dest_dir);
        }
    }

    fn record(&mut self, kind: &str, text: &str) {
        if let Some(log) = self.log.as_mut() {
            log.write(kind, text);
        }
    }

    /// Write one finished line, in the rail's glyph set: caller text may carry
    /// `·` or `…`, which an ASCII rail must not print.
    fn emit(&self, line: &str) {
        self.out.line(&super::fit_glyphs(line, &self.caps));
    }

    fn dim(&self, text: &str) -> String {
        paint::dim(text, self.caps.color)
    }

    fn white(&self, text: &str) -> String {
        paint::white(text, self.caps.color)
    }

    /// The gutter prefix for a line under a stage.
    pub(crate) fn gutter(&self) -> String {
        match self.caps.mode {
            Mode::Plain => "      ".to_string(),
            _ => format!("{}  ", self.dim(self.caps.glyphs().bar)),
        }
    }

    /// The gutter of the block waiting for the user: the bar in the accent
    /// colour, like its `◆`.
    fn active_gutter(&self) -> String {
        match self.caps.mode {
            Mode::Plain => "      ".to_string(),
            _ => format!(
                "{}  ",
                paint::accent(self.caps.glyphs().bar, self.caps.color)
            ),
        }
    }

    /// Wrap `text` to the rail width under the gutter.
    fn under(&self, text: &str, dim: bool) -> Vec<String> {
        let tone = |part: &str| {
            let part = style(part, self.caps.color);
            if dim {
                self.dim(&part)
            } else {
                part
            }
        };
        self.under_gutter(&self.gutter(), text, tone)
    }

    /// Wrap `text` to the rail width under `gutter`, painting each part.
    fn under_gutter(&self, gutter: &str, text: &str, tone: impl Fn(&str) -> String) -> Vec<String> {
        let room = self
            .caps
            .width
            .saturating_sub(console::measure_text_width(gutter));
        wrap(text, room)
            .into_iter()
            .map(|part| format!("{gutter}{}", tone(&part)))
            .collect()
    }

    /// `┌  Setting up this machine`.
    pub fn intro(&mut self, title: &str) {
        self.record("intro", title);
        let line = match self.caps.mode {
            Mode::Plain => title.to_string(),
            _ => format!(
                "{}  {}",
                self.dim(self.caps.glyphs().start),
                self.white(title)
            ),
        };
        self.emit(&line);
    }

    /// Open the next stage. `running` shows while it works (`Checking this
    /// machine`), `done` on its result line (`Checked this machine`). A stage
    /// still open is closed first, with no result.
    pub fn stage(&mut self, running: &str, done: &str) {
        self.stage_named(running, running, done);
    }

    /// [`Rail::stage`], naming what the stage is (`Start OpenLatch`) for the
    /// line a failure leaves: `✗  Start OpenLatch failed · …`.
    pub fn stage_named(&mut self, name: &str, running: &str, done: &str) {
        if self.stage.is_some() {
            self.done("");
        }
        self.count += 1;
        let index = self.count;
        self.record("stage", &format!("{index}/{} {running}", self.total));
        let g = self.caps.glyphs();
        let spinner = match self.caps.mode {
            Mode::Live => {
                self.emit(&self.dim(g.bar));
                self.spinner(&self.white(&format!("{running}{}", g.ellipsis)))
            }
            Mode::Append => {
                self.emit(g.bar);
                self.out
                    .line(&format!("{}  {running}{}", g.active, g.ellipsis));
                None
            }
            Mode::Plain => None,
        };
        self.stage = Some(Stage {
            index,
            name: name.to_string(),
            running: running.to_string(),
            shown: running.to_string(),
            done: done.to_string(),
            held: Vec::new(),
            announced: false,
            meter: None,
            milestone: 0,
            spinner,
        });
    }

    fn spinner(&self, message: &str) -> Option<indicatif::ProgressBar> {
        let Out::Term(term) = &self.out else {
            return None;
        };
        let g = self.caps.glyphs();
        let template = if self.caps.color {
            "{spinner:.cyan}  {msg}"
        } else {
            "{spinner}  {msg}"
        };
        let style = indicatif::ProgressStyle::with_template(template)
            .unwrap_or_else(|_| indicatif::ProgressStyle::default_spinner())
            .tick_strings(&[g.spinner, &[g.done]].concat());
        let pb = indicatif::ProgressBar::with_draw_target(
            None,
            indicatif::ProgressDrawTarget::term(term.clone(), 15),
        );
        pb.set_style(style);
        pb.set_message(message.to_string());
        pb.enable_steady_tick(Duration::from_millis(120));
        Some(pb)
    }

    /// Replace the running stage's label while it works
    /// (`Waiting for you to sign in · 4:52`). Not logged: it changes every tick.
    pub fn progress(&mut self, text: &str) {
        if let Some(stage) = self.stage.as_mut() {
            stage.shown = text.to_string();
        }
        self.refresh_block();
    }

    /// Show how far the running stage has got: `frac` of the way (clamped to
    /// 0–1; `None` when the total is unknown) and a free-text `tail`
    /// (`5.2 / 8.4 MB · 2.8 MB/s · 1s left`). Not logged: it changes every tick.
    ///
    /// Live redraws the bar in place — `⠹  Downloading 0.5.8  ━━━━━──── 62%
    /// 5.2 / 8.4 MB · …` — or, with no fraction, the tail after the label.
    /// Append writes one line per 25 / 50 / 75 / 100 % milestone crossed, never
    /// the same one twice; when a call jumps several, the tail rides on the
    /// last and the others are a bare `50%`. Plain
    /// writes the stage's `[n/N] <running>…` heading once, so a log never
    /// looks stuck. With no fraction, Append and Plain write nothing.
    pub fn meter(&mut self, frac: Option<f64>, tail: &str) {
        let frac = frac.filter(|f| f.is_finite()).map(|f| f.clamp(0.0, 1.0));
        let Some(stage) = self.stage.as_mut() else {
            return;
        };
        stage.meter = Some((frac, tail.to_string()));
        let Some(frac) = frac else {
            self.refresh_block();
            return;
        };
        match self.caps.mode {
            Mode::Live => self.refresh_block(),
            Mode::Append => {
                let pct = (frac * 100.0).floor() as u8;
                let last = stage.milestone;
                let marks: Vec<u8> = [25, 50, 75, 100]
                    .into_iter()
                    .filter(|m| *m > last && *m <= pct)
                    .collect();
                let Some(&top) = marks.last() else {
                    return;
                };
                stage.milestone = top;
                for mark in marks {
                    let text = if mark == top {
                        format!("{mark:>3}% {tail}")
                    } else {
                        format!("{mark:>3}%")
                    };
                    let line = format!("{}{}", self.gutter(), self.dim(text.trim_end()));
                    self.emit(&line);
                }
            }
            Mode::Plain => self.announce(),
        }
    }

    /// An always-visible line under the gutter: a URL to open, a per-agent
    /// warning, a remedy.
    pub fn note(&mut self, text: &str) {
        self.record("note", text);
        if self.holds() {
            if let Some(stage) = self.stage.as_mut() {
                stage.held.push(Held::Note(text.to_string()));
            }
            self.refresh_block();
            return;
        }
        self.announce();
        for line in self.under(text, false) {
            self.emit(&line);
        }
    }

    /// A dim line that belongs to the active block only: shown under the
    /// spinner while the stage runs, gone once it closes (`A browser window
    /// opened. Sign in there to continue.`). Plain mode writes it at once.
    pub fn hint(&mut self, text: &str) {
        self.transient(Held::Hint(text.to_string()), text);
    }

    /// A [`Rail::hint`] ending in a URL, which is never wrapped: a URL the user
    /// copies or clicks must stay one string, so the terminal soft-wraps it
    /// instead. `Didn't open? https://…`.
    pub fn link(&mut self, lead: &str, url: &str) {
        let held = Held::Link(lead.to_string(), url.to_string());
        self.transient(held, &format!("{lead}{url}"));
    }

    fn transient(&mut self, held: Held, text: &str) {
        self.record("note", text);
        if self.holds() {
            if let Some(stage) = self.stage.as_mut() {
                stage.held.push(held);
            }
            self.refresh_block();
            return;
        }
        self.announce();
        for line in self.held_lines(&held) {
            self.emit(&line);
        }
    }

    /// The screen lines of one held item.
    fn held_lines(&self, held: &Held) -> Vec<String> {
        match held {
            Held::Note(t) => self.under(t, false),
            Held::Hint(t) | Held::Detail(t) => self.under(t, true),
            Held::Link(lead, url) => vec![format!(
                "{}{}{}",
                self.gutter(),
                self.dim(lead),
                paint::link(url, self.caps.color)
            )],
        }
    }

    /// Change what the running stage says when it closes, for an outcome the
    /// label chosen at [`Rail::stage`] no longer describes (`Connected Claude
    /// Code and Codex CLI` when Codex CLI could not be wired after all).
    pub fn relabel(&mut self, done: &str) {
        if let Some(stage) = self.stage.as_mut() {
            stage.done = done.to_string();
        }
    }

    /// Plain mode writes nothing when a stage opens; a line that arrives before
    /// it closes gets the stage's heading first, so it is never read as part of
    /// the stage above. A caller announces a long stage itself so a log never
    /// looks stuck: `[5/6] Restarting the background service…`. Once per stage;
    /// a no-op in the other modes, which draw the stage as it opens.
    pub fn announce(&mut self) {
        if self.caps.mode != Mode::Plain {
            return;
        }
        let (total, ellipsis) = (self.total, self.caps.glyphs().ellipsis);
        let heading = match self.stage.as_mut() {
            Some(stage) if !stage.announced => {
                stage.announced = true;
                format!("[{}/{total}] {}{ellipsis}", stage.index, stage.running)
            }
            _ => return,
        };
        self.emit(&heading);
    }

    /// Engineering detail: always logged, shown only with `--verbose`.
    pub fn detail(&mut self, text: &str) {
        self.record("detail", text);
        if !self.caps.verbose {
            return;
        }
        if self.holds() {
            if let Some(stage) = self.stage.as_mut() {
                stage.held.push(Held::Detail(text.to_string()));
            }
            return;
        }
        self.announce();
        for line in self.under(text, true) {
            self.emit(&line);
        }
    }

    /// Whether lines are held for the active block instead of written now.
    fn holds(&self) -> bool {
        self.caps.mode == Mode::Live && self.stage.is_some()
    }

    /// Redraw the spinner's message with the notes held under it.
    fn refresh_block(&self) {
        let Some(stage) = &self.stage else { return };
        let Some(pb) = &stage.spinner else { return };
        pb.set_message(self.block_message(stage));
    }

    /// The active block after the spinner: the label (with its meter) and the
    /// notes held under it.
    fn block_message(&self, stage: &Stage) -> String {
        let mut message = match &stage.meter {
            Some((frac, tail)) => self.meter_line(&stage.shown, *frac, tail),
            None => self.white(&format!("{}{}", stage.shown, self.caps.glyphs().ellipsis)),
        };
        for held in stage.held.iter().filter(|h| !matches!(h, Held::Detail(_))) {
            for line in self.held_lines(held) {
                message.push('\n');
                message.push_str(&line);
            }
        }
        message
    }

    /// The meter's line, fitted to the rail width after the spinner's three
    /// columns. Trailing ` · ` parts of the tail go first, then the bar
    /// shortens; a bar that fits with no tail at all comes next, and a line
    /// too narrow for any bar reads `shown… · tail`.
    fn meter_line(&self, shown: &str, frac: Option<f64>, tail: &str) -> String {
        let (g, on) = (self.caps.glyphs(), self.caps.color);
        let fit = |t: &str| super::fit_glyphs(t, &self.caps);
        let width = |t: &str| console::measure_text_width(&fit(t));
        let room = self.caps.width.saturating_sub(3);
        let parts: Vec<&str> = tail.split(" · ").filter(|p| !p.is_empty()).collect();
        // The tail with its first `k` parts, longest first.
        let tails = || (0..=parts.len()).rev().map(|k| parts[..k].join(" · "));
        if let Some(frac) = frac {
            let pct = format!(" {:>3}%", (frac * 100.0).round() as u8);
            // Some of the tail beats a longer bar; a bar beats none.
            let tries = [
                (METER, true),
                (METER_SHORT, true),
                (METER, false),
                (METER_SHORT, false),
            ];
            for (bar, with_tail) in tries {
                let fixed = width(shown) + 2 + bar + pct.len();
                let Some(tail) = tails().find(|t| {
                    t.is_empty() != with_tail
                        && fixed + if t.is_empty() { 0 } else { 2 + width(t) } <= room
                }) else {
                    continue;
                };
                let full = (bar as f64 * frac).round() as usize;
                let tail = if tail.is_empty() {
                    String::new()
                } else {
                    self.dim(&fit(&format!("  {tail}")))
                };
                return format!(
                    "{}{}{}{}{tail}",
                    self.white(&format!("{shown}  ")),
                    paint::accent(&fit(&"━".repeat(full)), on),
                    self.dim(&fit(&"─".repeat(bar - full))),
                    self.white(&pct),
                );
            }
        }
        let label = format!("{shown}{}", g.ellipsis);
        let tail = tails()
            .find(|t| t.is_empty() || width(&label) + 3 + width(t) <= room)
            .unwrap_or_default();
        if tail.is_empty() {
            return self.white(&label);
        }
        format!(
            "{}{}",
            self.white(&label),
            self.dim(&fit(&format!(" {} {tail}", g.dot)))
        )
    }

    /// Close the running stage: `◇  Checked this machine · found Cline`.
    pub fn done(&mut self, result: &str) {
        let (glyph, on) = (self.caps.glyphs().done, self.caps.color);
        self.close(&paint::green(glyph, on), None, result, None, "done");
    }

    /// [`Rail::done`], with only the result in `tone`: `◇  Checked for updates
    /// · 0.5.7 → 0.5.8 · security fix` (the result red).
    pub fn done_toned(&mut self, result: &str, tone: paint::Tone) {
        let (glyph, on) = (self.caps.glyphs().done, self.caps.color);
        self.close(&paint::green(glyph, on), None, result, Some(tone), "done");
    }

    /// Close the running stage as needing the user: `!  Final checks · one
    /// thing left to do`.
    pub fn attention(&mut self, result: &str) {
        let (glyph, on) = (self.caps.glyphs().warn, self.caps.color);
        self.close(&paint::amber(glyph, on), None, result, None, "attention");
    }

    /// Close the running stage as the point the run stops at without an error:
    /// the whole line in amber — `!  Checked this machine · no AI agent found`.
    pub fn halt(&mut self, result: &str) {
        let (glyph, on) = (self.caps.glyphs().warn, self.caps.color);
        let glyph = paint::bold(&paint::amber(glyph, on), on);
        self.close(&glyph, Some(paint::amber), result, None, "halt");
    }

    /// Close the running stage as failed without an error of its own (a check
    /// that failed at the end): `✗  Final checks failed · 1 check failed`.
    pub fn failed(&mut self, result: &str) {
        if let Some(stage) = self.stage.as_mut() {
            stage.done = format!("{} failed", stage.name);
        }
        let (glyph, on) = (self.caps.glyphs().fail, self.caps.color);
        let glyph = paint::bold(&paint::red(glyph, on), on);
        self.close(&glyph, Some(paint::red), result, None, "failed");
    }

    fn close(
        &mut self,
        glyph: &str,
        tone: Option<fn(&str, bool) -> String>,
        result: &str,
        result_tone: Option<paint::Tone>,
        kind: &str,
    ) {
        let Some(stage) = self.stage.take() else {
            return;
        };
        if let Some(pb) = &stage.spinner {
            pb.finish_and_clear();
        }
        let text = if result.is_empty() {
            stage.done.clone()
        } else {
            format!("{} {} {result}", stage.done, self.caps.glyphs().dot)
        };
        self.record(kind, &format!("{}/{} {text}", stage.index, self.total));
        let line = match self.caps.mode {
            Mode::Plain => format!("[{}/{}] {text}", stage.index, self.total),
            _ => {
                let dot = self.caps.glyphs().dot;
                let tail = match result_tone {
                    _ if result.is_empty() => String::new(),
                    Some(t) => format!(
                        "{}{}",
                        self.dim(&format!(" {dot} ")),
                        t.paint(result, self.caps.color)
                    ),
                    None => self.dim(&format!(" {dot} {result}")),
                };
                let label = match tone {
                    Some(paint) => paint(&stage.done, self.caps.color),
                    None => self.white(&stage.done),
                };
                format!("{glyph}  {label}{tail}")
            }
        };
        self.emit(&line);
        self.flush_held(stage.held);
    }

    /// Write what a closing stage held: notes and (with `--verbose`) detail.
    /// Hints and links belonged to the active block and go with it.
    fn flush_held(&mut self, held: Vec<Held>) {
        for item in held
            .iter()
            .filter(|h| matches!(h, Held::Note(_) | Held::Detail(_)))
        {
            for line in self.held_lines(item) {
                self.emit(&line);
            }
        }
    }

    /// Report an error. On a terminal the running stage closes as one line —
    /// `✗  Start OpenLatch failed · the service stopped right after it started`
    /// — and the card that follows carries the rest; in plain mode the error
    /// block is written under the stage. With no stage running the block stands
    /// on its own. Every line is visible — an error is never detail — and the
    /// whole error is logged.
    pub fn fail(&mut self, error: &OlError) {
        let (g, on) = (self.caps.glyphs(), self.caps.color);
        let headline = format!("{} ({})", error.message, error.code);
        self.record("error", &headline);
        if let Some(s) = &error.suggestion {
            self.record("error", s);
        }
        if let Some(d) = &error.docs_url {
            self.record("error", &format!("Docs: {d}"));
        }
        let mut block = Vec::new();
        match self.stage.take() {
            Some(stage) => {
                if let Some(pb) = &stage.spinner {
                    pb.finish_and_clear();
                }
                let line = match self.caps.mode {
                    Mode::Plain => {
                        format!(
                            "[{}/{}] {} {} failed",
                            stage.index, self.total, stage.running, g.dot
                        )
                    }
                    _ => format!(
                        "{}  {}{}",
                        paint::bold(&paint::red(g.fail, on), on),
                        paint::red(&format!("{} failed", stage.name), on),
                        self.dim(&format!(" {} {}", g.dot, reason(&error.message)))
                    ),
                };
                self.emit(&line);
                self.flush_held(stage.held);
                if self.caps.mode != Mode::Plain {
                    return;
                }
                block.extend(self.under(&headline, false));
            }
            None => {
                let lead = match self.caps.mode {
                    Mode::Plain => format!("{} ", g.fail),
                    _ => format!("{}  ", paint::bold(&paint::red(g.fail, on), on)),
                };
                block.push(format!("{lead}{headline}"));
            }
        }
        if let Some(s) = &error.suggestion {
            block.extend(self.under(s, false));
        }
        if let Some(d) = &error.docs_url {
            block.extend(self.under(&format!("Docs: {d}"), true));
        }
        for line in block {
            self.emit(&line);
        }
    }

    /// Close the rail: `└  Done.`
    pub fn outro(&mut self, text: &str) {
        if self.stage.is_some() {
            self.done("");
        }
        self.record("outro", text);
        let g = self.caps.glyphs();
        match self.caps.mode {
            Mode::Plain => self.emit(text),
            _ => {
                self.emit(&self.dim(g.bar));
                self.emit(&format!("{}  {}", self.dim(g.end), self.white(text)));
            }
        }
    }

    /// Draw the result card after a blank line.
    pub fn card(&mut self, card: &Card) {
        self.card_with_warnings(card, &[]);
    }

    /// [`Rail::card`], with amber warning lines heading its footer (see
    /// [`card::render_with_warnings`]).
    pub fn card_with_warnings(&mut self, card: &Card, warnings: &[String]) {
        let lines = card::render_with_warnings(card, warnings, &self.caps);
        for line in &lines {
            self.record("card", line);
        }
        self.emit("");
        for line in lines {
            self.emit(&line);
        }
    }

    /// The `result=` line, written in plain mode only (a terminal has the card).
    /// Always logged.
    pub fn result_line(&mut self, verdict: Verdict, exit_code: i32, fields: &[(&str, &str)]) {
        self.write_result(card::result_line(verdict, exit_code, fields));
    }

    /// [`Rail::result_line`] with a command's own token (see
    /// [`card::result_line_token`]).
    pub fn result_line_token(&mut self, token: &str, exit_code: i32, fields: &[(&str, &str)]) {
        self.write_result(card::result_line_token(token, exit_code, fields));
    }

    fn write_result(&mut self, line: String) {
        self.record("result", &line);
        if self.caps.mode == Mode::Plain {
            self.emit(&line);
        }
    }

    /// Run `f` with the active block out of the way, for output the rail does
    /// not own (a third-party prompt). The spinner is redrawn afterwards.
    pub fn suspend<R>(&self, f: impl FnOnce() -> R) -> R {
        match self.stage.as_ref().and_then(|s| s.spinner.as_ref()) {
            Some(pb) => pb.suspend(f),
            None => f(),
        }
    }

    /// Ask a two-option question under the running stage (or on its own). The
    /// block is erased once answered where the terminal allows it; the caller
    /// then closes the stage with the answer (`◇  Usage data · sharing`).
    pub fn select(&mut self, q: &Select<'_>) -> SelectOutcome {
        use std::io::IsTerminal;
        self.record("ask", q.question);
        if let Some(pb) = self.stage.as_mut().and_then(|s| s.spinner.take()) {
            pb.finish_and_clear();
        }
        select::discard_typeahead();
        let keys = self.caps.mode == Mode::Live
            && matches!(self.out, Out::Term(_))
            && std::io::stdin().is_terminal();
        let outcome = if keys {
            self.select_keys(q)
        } else {
            self.select_line(q, select::read_stdin_line)
        };
        self.record("answer", &format!("{outcome:?}"));
        outcome
    }

    /// `◆  Usage data`, the question in bold, then the dim lines — all under
    /// the accent gutter of the block waiting for the user.
    fn select_head(&self, q: &Select<'_>) -> Vec<String> {
        let (g, on) = (self.caps.glyphs(), self.caps.color);
        let gutter = self.active_gutter();
        let mut lines = Vec::new();
        if self.caps.mode != Mode::Plain {
            lines.push(format!(
                "{}  {}",
                paint::accent(g.active, on),
                self.white(q.title)
            ));
        }
        lines.extend(self.under_gutter(&gutter, q.question, |part| {
            paint::bold(&self.white(part), on)
        }));
        for l in q.lines {
            lines.extend(self.under_gutter(&gutter, l, |part| self.dim(&style(part, on))));
        }
        lines
    }

    /// `│  › ● Yes, share    ○ No thanks      ← → then Enter`: the highlighted
    /// option bold in the highlight colour, the other dim, and the `›` only
    /// before the first option while it is the highlighted one.
    fn options_line(&self, q: &Select<'_>, state: KeyState) -> String {
        let (g, on) = (self.caps.glyphs(), self.caps.color);
        let pick = |label: &str, selected: bool| {
            if selected {
                paint::bold(&paint::highlight(&format!("{} {label}", g.on), on), on)
            } else {
                self.dim(&format!("{} {label}", g.off))
            }
        };
        let lead = if state.yes {
            format!("{} ", paint::accent(g.arrow, on))
        } else {
            " ".repeat(console::measure_text_width(g.arrow) + 1)
        };
        let keys = if self.caps.unicode {
            "← → then Enter"
        } else {
            "<- -> then Enter"
        };
        format!(
            "{}{lead}{}    {}      {}",
            self.active_gutter(),
            pick(q.yes, state.yes),
            pick(q.no, !state.yes),
            self.dim(keys)
        )
    }

    fn select_keys(&mut self, q: &Select<'_>) -> SelectOutcome {
        let Out::Term(term) = &self.out else {
            unreachable!("key select runs on a terminal only")
        };
        let term = term.clone();
        let head = self.select_head(q);
        for line in &head {
            self.emit(line);
        }
        let first = KeyState { yes: q.default_yes };
        self.emit(&self.options_line(q, first));
        let _ = term.hide_cursor();
        let outcome = select::ask_keys(
            q.default_yes,
            || term.read_key(),
            |state| {
                self.out.clear(1);
                self.emit(&self.options_line(q, state));
            },
        );
        let _ = term.show_cursor();
        self.out.clear(head.len() + 1);
        outcome
    }

    /// The line path; `read` is injectable for tests.
    pub(crate) fn select_line(
        &mut self,
        q: &Select<'_>,
        read: impl FnMut(Option<Duration>) -> LineRead,
    ) -> SelectOutcome {
        for line in self.select_head(q) {
            self.emit(&line);
        }
        let hint = if q.default_yes { "[Y/n]" } else { "[y/N]" };
        let arrow = self.caps.glyphs().arrow;
        let prompt = format!(
            "{}{} / {}  {hint} {arrow} ",
            self.active_gutter(),
            q.yes,
            q.no
        );
        let prompt = super::fit_glyphs(&prompt, &self.caps);
        self.out.prompt(&prompt);
        let out = &self.out;
        let outcome = select::ask_line(q.default_yes, q.timeout, read, || out.prompt(&prompt));
        if !matches!(outcome, SelectOutcome::Answered(_)) {
            // The cursor still sits after the prompt; end that line.
            self.emit("");
        }
        outcome
    }
}

/// An error message as the tail of a failed stage line: `The service stopped`
/// → `the service stopped`, trailing full stop dropped. An acronym or a name
/// (`OPENLATCH_PORT=…`, `OL-…`) keeps its case.
fn reason(message: &str) -> String {
    let message = message.trim().trim_end_matches('.');
    let mut chars = message.chars();
    match (chars.next(), chars.next()) {
        (Some(first), Some(second)) if first.is_uppercase() && second.is_lowercase() => first
            .to_lowercase()
            .chain(message.chars().skip(1))
            .collect(),
        _ => message.to_string(),
    }
}

impl Drop for Rail {
    fn drop(&mut self) {
        if let Some(pb) = self.stage.as_ref().and_then(|s| s.spinner.as_ref()) {
            pb.finish_and_clear();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::ui::card::{Row, Section};

    fn rail(mode: Mode, verbose: bool) -> (Rail, Arc<Mutex<Vec<String>>>) {
        Rail::buffer(Caps::new(mode, false, verbose, 80), 6)
    }

    fn screen(s: &Arc<Mutex<Vec<String>>>) -> Vec<String> {
        lock(s).clone()
    }

    #[test]
    fn test_live_rail_lines() {
        let (mut r, s) = rail(Mode::Live, false);
        r.intro("Setting up this machine");
        r.stage("Checking this machine", "Checked this machine");
        r.detail("Reclaimed daemon (PID 42)");
        r.done("found Cline");
        r.stage("Waiting for you to sign in", "Signed in");
        r.note("Open https://app.openlatch.ai/device to sign in");
        r.done("SuperAdmin");
        r.outro("Done.");
        assert_eq!(
            screen(&s),
            vec![
                "┌  Setting up this machine",
                "│",
                "◇  Checked this machine · found Cline",
                "│",
                "◇  Signed in · SuperAdmin",
                "│  Open https://app.openlatch.ai/device to sign in",
                "│",
                "└  Done.",
            ]
        );
    }

    #[test]
    fn test_verbose_shows_detail_dim_under_the_stage() {
        let (mut r, s) = rail(Mode::Live, true);
        r.stage("Checking this machine", "Checked this machine");
        r.detail("Reclaimed daemon (PID 42)");
        r.done("");
        assert_eq!(
            screen(&s),
            vec![
                "│",
                "◇  Checked this machine",
                "│  Reclaimed daemon (PID 42)"
            ]
        );
    }

    #[test]
    fn test_ascii_append_mode() {
        let (mut r, s) = rail(Mode::Append, false);
        r.intro("Setting up this machine");
        r.stage("Checking this machine", "Checked this machine");
        r.note("a note");
        r.attention("no agent yet");
        r.outro("Paused.");
        let lines = screen(&s);
        assert_eq!(
            lines,
            vec![
                "+  Setting up this machine",
                "|",
                ">  Checking this machine...",
                "|  a note",
                "!  Checked this machine - no agent yet",
                "|",
                "+  Paused.",
            ]
        );
        assert!(lines.iter().all(|l| l.is_ascii()));
    }

    #[test]
    fn test_plain_mode_numbers_stages_and_hides_detail() {
        let (mut r, s) = rail(Mode::Plain, false);
        r.intro("Setting up this machine");
        r.stage("Checking this machine", "Checked this machine");
        r.detail("hidden without --verbose");
        r.done("found Cline");
        r.stage("Waiting for you to sign in", "Signed in");
        r.note("Open the URL");
        r.done("SuperAdmin");
        r.result_line(Verdict::Live, 0, &[("org", "SuperAdmin")]);
        assert_eq!(
            screen(&s),
            vec![
                "Setting up this machine",
                "[1/6] Checked this machine - found Cline",
                "[2/6] Waiting for you to sign in...",
                "      Open the URL",
                "[2/6] Signed in - SuperAdmin",
                "result=live org=SuperAdmin exit=0",
            ]
        );
    }

    #[test]
    fn test_result_line_is_plain_mode_only() {
        let (mut r, s) = rail(Mode::Live, false);
        r.result_line(Verdict::Live, 0, &[]);
        assert!(screen(&s).is_empty());
    }

    fn service_error() -> OlError {
        OlError::new("OL-1502", "The service stopped right after it started.")
            .with_suggestion("Run `openlatch init` again.")
            .with_docs("https://docs.openlatch.ai/errors/OL-1502")
    }

    /// A terminal gets one line — the card carries the rest.
    #[test]
    fn test_fail_closes_the_stage_as_one_line() {
        let (mut r, s) = rail(Mode::Live, false);
        r.stage_named("Start OpenLatch", "Starting OpenLatch", "Started OpenLatch");
        r.note("kept: a note is not the active block");
        r.hint("dropped: a hint is");
        r.fail(&service_error());
        assert_eq!(
            screen(&s),
            vec![
                "│",
                "✗  Start OpenLatch failed · the service stopped right after it started",
                "│  kept: a note is not the active block",
            ]
        );
    }

    /// Plain mode keeps the whole error under the stage.
    #[test]
    fn test_fail_in_plain_mode_writes_the_error_block() {
        let (mut r, s) = rail(Mode::Plain, false);
        r.stage("Starting OpenLatch", "Started OpenLatch");
        r.fail(&service_error());
        assert_eq!(
            screen(&s),
            vec![
                "[1/6] Starting OpenLatch - failed",
                "      The service stopped right after it started. (OL-1502)",
                "      Run openlatch init again.",
                "      Docs: https://docs.openlatch.ai/errors/OL-1502",
            ]
        );
    }

    /// The playground's renderRail, span for span, in colour.
    #[test]
    fn test_live_rail_spans_match_the_playground() {
        let (mut r, s) = Rail::buffer(Caps::new(Mode::Live, true, false, 80), 6);
        r.intro("Setting up this machine");
        r.stage("Checking this machine", "Checked this machine");
        r.done("found Cline");
        r.stage_named(
            "Check this machine",
            "Checking this machine",
            "Checked this machine",
        );
        r.halt("no AI agent found");
        r.stage("Running final checks", "Final checks");
        r.attention("one thing left to do");
        r.stage_named("Start OpenLatch", "Starting OpenLatch", "Started OpenLatch");
        r.fail(&service_error());
        r.outro("Done.");
        let dim_bar = "\x1b[90m│\x1b[0m";
        assert_eq!(
            screen(&s),
            vec![
                "\x1b[90m┌\x1b[0m  \x1b[97mSetting up this machine\x1b[0m".to_string(),
                dim_bar.to_string(),
                "\x1b[92m◇\x1b[0m  \x1b[97mChecked this machine\x1b[0m\x1b[90m · found Cline\x1b[0m".to_string(),
                dim_bar.to_string(),
                "\x1b[1m\x1b[33m!\x1b[0m\x1b[22m  \x1b[33mChecked this machine\x1b[0m\x1b[90m · no AI agent found\x1b[0m".to_string(),
                dim_bar.to_string(),
                "\x1b[33m!\x1b[0m  \x1b[97mFinal checks\x1b[0m\x1b[90m · one thing left to do\x1b[0m".to_string(),
                dim_bar.to_string(),
                "\x1b[1m\x1b[91m✗\x1b[0m\x1b[22m  \x1b[91mStart OpenLatch failed\x1b[0m\x1b[90m · the service stopped right after it started\x1b[0m".to_string(),
                dim_bar.to_string(),
                "\x1b[90m└\x1b[0m  \x1b[97mDone.\x1b[0m".to_string(),
            ]
        );
    }

    /// The sign-in block is part of the active stage: under the spinner while
    /// it runs, gone from the finished rail; the URL is never wrapped.
    #[test]
    fn test_hints_and_links_leave_with_their_stage() {
        let url = format!("https://app.openlatch.ai/cli-auth?{}", "x".repeat(120));
        let (mut r, s) = rail(Mode::Live, false);
        r.stage("Waiting for you to sign in", "Signed in");
        r.hint("A browser window opened. Sign in there to continue.");
        r.link("Didn't open? ", &url);
        r.done("Acme Corp");
        assert_eq!(screen(&s), vec!["│", "◇  Signed in · Acme Corp"]);

        let (mut r, s) = rail(Mode::Plain, false);
        r.stage("Waiting for you to sign in", "Signed in");
        r.hint("A browser window opened. Sign in there to continue.");
        r.link("Didn't open? ", &url);
        r.done("Acme Corp");
        assert_eq!(
            screen(&s),
            vec![
                "[1/6] Waiting for you to sign in...".to_string(),
                "      A browser window opened. Sign in there to continue.".to_string(),
                format!("      Didn't open? {url}"),
                "[1/6] Signed in - Acme Corp".to_string(),
            ]
        );
    }

    /// Only the result carries the tone: glyph green, label white, dot dim.
    #[test]
    fn test_done_toned_paints_only_the_result() {
        let (mut r, s) = Rail::buffer(Caps::new(Mode::Live, true, false, 80), 6);
        r.stage("Checking for updates", "Checked for updates");
        r.done_toned("0.5.7 → 0.5.8 · security fix", paint::Tone::Fail);
        assert_eq!(
            screen(&s)[1],
            "\x1b[92m◇\x1b[0m  \x1b[97mChecked for updates\x1b[0m\x1b[90m · \x1b[0m\x1b[91m0.5.7 → 0.5.8 · security fix\x1b[0m"
        );

        let (mut r, s) = rail(Mode::Append, false);
        r.stage("Checking for updates", "Checked for updates");
        r.done_toned("0.5.7 → 0.5.8", paint::Tone::Warn);
        assert_eq!(screen(&s)[2], "+  Checked for updates - 0.5.7 -> 0.5.8");

        let (mut r, s) = rail(Mode::Plain, false);
        r.stage("Checking for updates", "Checked for updates");
        r.done_toned("0.5.7 → 0.5.8", paint::Tone::Success);
        assert_eq!(
            screen(&s),
            vec!["[1/6] Checked for updates - 0.5.7 -> 0.5.8"]
        );
    }

    /// The playground's download line, span for span: label and percentage
    /// bright white, the filled bar accent, the rest of it and the tail dim.
    /// Nothing is appended: the active block is redrawn in place.
    #[test]
    fn test_live_meter_redraws_the_active_block() {
        let (mut r, s) = Rail::buffer(Caps::new(Mode::Live, true, false, 80), 6);
        r.stage("Downloading 0.5.8", "Downloaded");
        r.meter(Some(0.5), "4.2 / 8.4 MB · 2.8 MB/s · 1s left");
        let stage = r.stage.as_ref().expect("running");
        assert_eq!(
            r.block_message(stage),
            format!(
                "\x1b[97mDownloading 0.5.8  \x1b[0m\x1b[36m{}\x1b[0m\x1b[90m{}\x1b[0m\
                 \x1b[97m  50%\x1b[0m\x1b[90m  4.2 / 8.4 MB · 2.8 MB/s\x1b[0m",
                "━".repeat(12),
                "─".repeat(12)
            )
        );
        r.meter(Some(7.0), "done");
        let stage = r.stage.as_ref().expect("running");
        assert!(
            r.block_message(stage).contains(&"━".repeat(METER)),
            "clamped"
        );
        assert!(r.block_message(stage).contains("100%"));
        r.done("8.4 MB in 2.9s");
        assert_eq!(
            screen(&s),
            vec![
                "\x1b[90m│\x1b[0m",
                "\x1b[92m◇\x1b[0m  \x1b[97mDownloaded\x1b[0m\x1b[90m · 8.4 MB in 2.9s\x1b[0m"
            ]
        );
    }

    /// The meter fits the rail width with the spinner's three columns: tail
    /// parts go from the end, then the bar shortens, and a width too narrow
    /// for any bar keeps the label and what of the tail fits.
    #[test]
    fn test_live_meter_fits_the_width() {
        let tail = "4.2 / 8.4 MB · 2.8 MB/s · 1s left";
        let line = |width: usize| {
            let caps = Caps {
                width,
                ..Caps::new(Mode::Live, false, false, 80)
            };
            let (mut r, _) = Rail::buffer(caps, 6);
            r.stage("Downloading 0.5.8", "Downloaded");
            r.meter(Some(0.5), tail);
            let stage = r.stage.as_ref().expect("running");
            r.block_message(stage)
        };
        let bar = |n: usize| format!("{}{}", "━".repeat(n / 2), "─".repeat(n / 2));
        assert_eq!(
            line(80),
            format!(
                "Downloading 0.5.8  {}  50%  4.2 / 8.4 MB · 2.8 MB/s",
                bar(24)
            )
        );
        assert_eq!(
            line(60),
            format!("Downloading 0.5.8  {}  50%  4.2 / 8.4 MB", bar(10))
        );
        assert_eq!(line(40), format!("Downloading 0.5.8  {}  50%", bar(10)));
        assert_eq!(line(24), "Downloading 0.5.8…");
        for width in [24, 40, 60, 80, 100] {
            let first = line(width);
            assert!(
                3 + console::measure_text_width(&first) <= width,
                "{width}: {first}"
            );
        }
        // Caps clamps a real terminal to 60 columns at the narrowest.
        let (mut r, _) = Rail::buffer(Caps::new(Mode::Live, false, false, 30), 6);
        r.stage("Downloading 0.5.8", "Downloaded");
        r.meter(Some(0.5), tail);
        let stage = r.stage.as_ref().expect("running");
        assert_eq!(r.block_message(stage), line(60));
    }

    /// Unknown total: the tail rides after the label, the spinner says the rest.
    #[test]
    fn test_live_meter_without_a_fraction() {
        let (mut r, _) = rail(Mode::Live, false);
        r.stage("Restarting the background service", "Restarted");
        r.meter(None, "draining in-flight events · 3s");
        let stage = r.stage.as_ref().expect("running");
        assert_eq!(
            r.block_message(stage),
            "Restarting the background service… · draining in-flight events · 3s"
        );
        r.meter(Some(f64::NAN), "");
        let stage = r.stage.as_ref().expect("running");
        assert_eq!(r.block_message(stage), "Restarting the background service…");
    }

    /// A Live rail on a console that refused Unicode draws the bar in ASCII.
    #[test]
    fn test_live_meter_ascii() {
        let caps = Caps {
            unicode: false,
            ..Caps::new(Mode::Live, false, false, 80)
        };
        let (mut r, _) = Rail::buffer(caps, 6);
        r.stage("Downloading", "Downloaded");
        r.meter(Some(0.25), "2.1 / 8.4 MB · 2.8 MB/s");
        let stage = r.stage.as_ref().expect("running");
        assert_eq!(
            r.block_message(stage),
            format!(
                "Downloading  {}{}  25%  2.1 / 8.4 MB - 2.8 MB/s",
                "#".repeat(6),
                "-".repeat(18)
            )
        );
    }

    /// One line per milestone crossed, never the same one twice; a jump
    /// writes every mark it passed, the tail on the last; no fraction writes
    /// nothing.
    #[test]
    fn test_append_meter_writes_each_milestone_once() {
        let (mut r, s) = rail(Mode::Append, false);
        r.stage("Downloading 0.5.8", "Downloaded");
        for (frac, tail) in [
            (Some(0.1), "0.8 / 8.4 MB"),
            (Some(0.3), "2.5 / 8.4 MB · 2.8 MB/s"),
            (Some(0.4), "3.4 / 8.4 MB"),
            (None, "unknown"),
            (Some(0.9), "7.6 / 8.4 MB"),
            (Some(0.8), "6.7 / 8.4 MB"),
            (Some(1.0), "8.4 / 8.4 MB"),
            (Some(1.0), "8.4 / 8.4 MB"),
        ] {
            r.meter(frac, tail);
        }
        r.done("8.4 MB in 2.9s");
        assert_eq!(
            screen(&s),
            vec![
                "|",
                ">  Downloading 0.5.8...",
                "|   25% 2.5 / 8.4 MB - 2.8 MB/s",
                "|   50%",
                "|   75% 7.6 / 8.4 MB",
                "|  100% 8.4 / 8.4 MB",
                "+  Downloaded - 8.4 MB in 2.9s",
            ]
        );
    }

    /// Plain mode: the stage's heading once, then nothing until it closes; a
    /// meter with no fraction writes nothing at all.
    #[test]
    fn test_plain_meter_writes_one_heading() {
        let (mut r, s) = rail(Mode::Plain, false);
        r.stage("Downloading 8.4 MB", "Downloaded");
        r.meter(None, "starting");
        assert!(screen(&s).is_empty());
        for frac in [0.1, 0.5, 1.0] {
            r.meter(Some(frac), "x / 8.4 MB");
        }
        r.done("8.4 MB in 2.9s");
        r.stage(
            "Restarting the background service",
            "Restarted the background service",
        );
        r.announce();
        r.announce();
        r.done("back in 5.4s");
        assert_eq!(
            screen(&s),
            vec![
                "[1/6] Downloading 8.4 MB...",
                "[1/6] Downloaded - 8.4 MB in 2.9s",
                "[2/6] Restarting the background service...",
                "[2/6] Restarted the background service - back in 5.4s",
            ]
        );
    }

    #[test]
    fn test_append_meter_jump_writes_every_mark() {
        let (mut r, s) = rail(Mode::Append, false);
        r.stage("Downloading 0.5.8", "Downloaded");
        r.meter(Some(1.0), "8.4 / 8.4 MB");
        assert_eq!(
            screen(&s)[2..],
            ["|   25%", "|   50%", "|   75%", "|  100% 8.4 / 8.4 MB"]
        );
    }

    #[test]
    fn test_meter_without_a_stage_is_a_no_op() {
        for mode in [Mode::Live, Mode::Append, Mode::Plain] {
            let (mut r, s) = rail(mode, false);
            r.meter(Some(0.5), "x");
            r.announce();
            assert!(screen(&s).is_empty());
        }
    }

    #[test]
    fn test_result_line_token_is_plain_mode_only() {
        let (mut r, s) = rail(Mode::Plain, false);
        r.result_line_token("up_to_date", 0, &[("version", "0.5.8")]);
        assert_eq!(screen(&s), vec!["result=up_to_date version=0.5.8 exit=0"]);
        let (mut r, s) = rail(Mode::Live, false);
        r.result_line_token("up_to_date", 0, &[]);
        assert!(screen(&s).is_empty());
    }

    #[test]
    fn test_reason_lowers_a_sentence_and_keeps_a_name() {
        assert_eq!(reason("The service stopped."), "the service stopped");
        assert_eq!(
            reason("OPENLATCH_PORT=7443 is already in use"),
            "OPENLATCH_PORT=7443 is already in use"
        );
        assert_eq!(reason("cannot reach http://x"), "cannot reach http://x");
    }

    #[test]
    fn test_fail_without_a_stage_stands_alone() {
        let (mut r, s) = rail(Mode::Plain, false);
        r.fail(&OlError::new("OL-1400", "No supported agent"));
        assert_eq!(screen(&s), vec!["x No supported agent (OL-1400)"]);
    }

    #[test]
    fn test_notes_wrap_to_the_rail_width() {
        let (mut r, s) = rail(Mode::Live, false);
        r.note(&"word ".repeat(40));
        let lines = screen(&s);
        assert!(lines.len() > 1);
        assert!(lines.iter().all(|l| console::measure_text_width(l) <= 80));
        assert!(lines.iter().all(|l| l.starts_with("│  ")));
    }

    #[test]
    fn test_card_after_rail_fits_80_columns() {
        let (mut r, s) = rail(Mode::Live, false);
        r.outro("Done.");
        r.card(&Card {
            verdict: Verdict::NoAgent,
            title: "No AI agent to connect on this machine yet".into(),
            rows: vec![Row::new("Looked for", "Claude Code · Codex CLI · Cline")],
            sections: vec![Section::new(
                "To finish",
                vec!["Install one of them, then run `openlatch init` again.".into()],
            )],
            footer: vec![],
        });
        let lines = screen(&s);
        assert_eq!(lines[2], "");
        assert!(lines.iter().all(|l| console::measure_text_width(l) <= 80));
        assert!(lines.iter().any(|l| l.contains("!  No AI agent")));
    }

    fn q(timeout: Option<Duration>) -> Select<'static> {
        Select {
            title: "Usage data",
            question: "Share anonymous usage data to help improve OpenLatch?",
            lines: &["Never prompts, code, or secrets."],
            yes: "Yes, share",
            no: "No thanks",
            default_yes: true,
            timeout,
        }
    }

    #[test]
    fn test_select_line_path() {
        let (mut r, s) = rail(Mode::Append, false);
        let outcome = r.select_line(&q(None), |_| LineRead::Line("n\n".into()));
        assert_eq!(outcome, SelectOutcome::Answered(false));
        assert_eq!(
            screen(&s),
            vec![
                ">  Usage data",
                "|  Share anonymous usage data to help improve OpenLatch?",
                "|  Never prompts, code, or secrets.",
                "|  Yes, share / No thanks  [Y/n] > ",
            ]
        );
    }

    #[test]
    fn test_select_line_reports_eof_and_ends_the_prompt_line() {
        let (mut r, s) = rail(Mode::Plain, false);
        let outcome = r.select_line(&q(None), |_| LineRead::Eof);
        assert_eq!(outcome, SelectOutcome::Eof);
        assert_eq!(screen(&s).last().map(String::as_str), Some(""));
    }

    #[test]
    fn test_options_line_without_colour() {
        let (r, _) = rail(Mode::Live, false);
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: true }),
            "│  › ● Yes, share    ○ No thanks      ← → then Enter"
        );
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: false }),
            "│    ○ Yes, share    ● No thanks      ← → then Enter"
        );
    }

    /// A console that refused Unicode keeps the layout, in ASCII.
    #[test]
    fn test_options_line_ascii() {
        let caps = Caps {
            unicode: false,
            ..Caps::new(Mode::Live, false, false, 80)
        };
        let (r, _) = Rail::buffer(caps, 6);
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: true }),
            "|  > (*) Yes, share    ( ) No thanks      <- -> then Enter"
        );
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: false }),
            "|    ( ) Yes, share    (*) No thanks      <- -> then Enter"
        );
    }

    /// The playground's consentBlock, span for span: accent `◆` and gutter,
    /// bold white question, dim body, the highlighted option bold bright cyan.
    #[test]
    fn test_select_block_spans_match_the_playground() {
        let (r, _) = Rail::buffer(Caps::new(Mode::Live, true, false, 80), 6);
        let bar = "\x1b[36m│\x1b[0m  ";
        assert_eq!(
            r.select_head(&q(None)),
            vec![
                "\x1b[36m◆\x1b[0m  \x1b[97mUsage data\x1b[0m".to_string(),
                format!("{bar}\x1b[1m\x1b[97mShare anonymous usage data to help improve OpenLatch?\x1b[0m\x1b[22m"),
                format!("{bar}\x1b[90mNever prompts, code, or secrets.\x1b[0m"),
            ]
        );
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: true }),
            format!(
                "{bar}\x1b[36m›\x1b[0m \x1b[1m\x1b[96m● Yes, share\x1b[0m\x1b[22m    \
                 \x1b[90m○ No thanks\x1b[0m      \x1b[90m← → then Enter\x1b[0m"
            )
        );
        assert_eq!(
            r.options_line(&q(None), KeyState { yes: false }),
            format!(
                "{bar}  \x1b[90m○ Yes, share\x1b[0m    \x1b[1m\x1b[96m● No thanks\x1b[0m\x1b[22m      \
                 \x1b[90m← → then Enter\x1b[0m"
            )
        );
    }
}