nanospinner 0.3.2

A minimal, zero-dependency terminal spinner for Rust CLI applications
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
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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
use crate::shared::{format_finalize_plain, BLUE, CLEAR_LINE, FRAMES, GREEN, RED, RESET, YELLOW};

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

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum LineStatus {
    /// Still animating.
    Active,
    /// Finalized with success (green ✔).
    Succeeded,
    /// Finalized with a replacement success message.
    SucceededWith(String),
    /// Finalized with failure (red ✖).
    Failed,
    /// Finalized with a replacement failure message.
    FailedWith(String),
    /// Finalized with warning (yellow ⚠).
    Warned,
    /// Finalized with a replacement warning message.
    WarnedWith(String),
    /// Finalized with info (blue ℹ).
    Informed,
    /// Finalized with a replacement info message.
    InformedWith(String),
    /// Silently dismissed — produces no output.
    Cleared,
}

#[derive(Clone)]
pub(crate) struct SpinnerLine {
    pub(crate) message: String,
    pub(crate) status: LineStatus,
}

/// A builder for a multi-spinner group that manages multiple concurrent
/// spinners on separate terminal lines.
///
/// Mirrors the [`crate::Spinner`] construction pattern: call [`MultiSpinner::new`]
/// for stdout, or [`MultiSpinner::with_writer`] / [`MultiSpinner::with_writer_tty`]
/// for custom writers.
pub struct MultiSpinner<W: io::Write + Send + 'static = io::Stdout> {
    writer: W,
    is_tty: bool,
}

impl Default for MultiSpinner<io::Stdout> {
    fn default() -> Self {
        Self::new()
    }
}

impl MultiSpinner {
    /// Create a new multi-spinner writing to stdout with automatic TTY detection.
    #[must_use]
    pub fn new() -> MultiSpinner<io::Stdout> {
        MultiSpinner {
            writer: io::stdout(),
            is_tty: io::stdout().is_terminal(),
        }
    }
}

impl<W: io::Write + Send + 'static> MultiSpinner<W> {
    /// Create a new multi-spinner with a custom writer. `is_tty` defaults to `false`.
    pub fn with_writer(writer: W) -> Self {
        MultiSpinner {
            writer,
            is_tty: false,
        }
    }

    /// Create a new multi-spinner with a custom writer and an explicit TTY flag.
    pub fn with_writer_tty(writer: W, is_tty: bool) -> Self {
        MultiSpinner { writer, is_tty }
    }

    /// Start the multi-spinner group and return a handle for managing spinners.
    ///
    /// Consumes the `MultiSpinner` builder. In plain mode (`is_tty` is false),
    /// no background thread is spawned. In TTY mode, a render-loop thread will
    /// be started (added in a later task).
    #[must_use]
    pub fn start(self) -> MultiSpinnerHandle {
        let writer: Arc<Mutex<Box<dyn io::Write + Send>>> =
            Arc::new(Mutex::new(Box::new(self.writer)));
        let lines: Arc<Mutex<Vec<SpinnerLine>>> = Arc::new(Mutex::new(Vec::new()));
        let stop_flag = Arc::new(AtomicBool::new(false));
        let last_visible_count = Arc::new(AtomicUsize::new(0));
        let is_tty = self.is_tty;

        let thread = if is_tty {
            let t_stop = Arc::clone(&stop_flag);
            let t_lines = Arc::clone(&lines);
            let t_writer = Arc::clone(&writer);
            let t_visible = Arc::clone(&last_visible_count);

            Some(thread::spawn(move || {
                multi_spin_loop(
                    FRAMES,
                    Duration::from_millis(80),
                    &t_stop,
                    &t_lines,
                    &t_writer,
                    &t_visible,
                );
            }))
        } else {
            stop_flag.store(true, Ordering::Release);
            None
        };

        MultiSpinnerHandle {
            lines,
            writer,
            stop_flag,
            thread: Mutex::new(thread),
            is_tty,
            last_visible_count,
        }
    }
}

/// Handle returned by [`MultiSpinner::start`] for managing a running
/// multi-spinner group.
pub struct MultiSpinnerHandle {
    lines: Arc<Mutex<Vec<SpinnerLine>>>,
    writer: Arc<Mutex<Box<dyn io::Write + Send>>>,
    stop_flag: Arc<AtomicBool>,
    thread: Mutex<Option<JoinHandle<()>>>,
    is_tty: bool,
    last_visible_count: Arc<AtomicUsize>,
}

impl MultiSpinnerHandle {
    /// Add a new spinner line with the given message and return a handle to
    /// control it.
    ///
    /// In plain mode no output is produced until the returned
    /// [`SpinnerLineHandle`] is finalized.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn add(&self, message: impl Into<String>) -> SpinnerLineHandle {
        let mut lines = self.lines.lock().unwrap();
        lines.push(SpinnerLine {
            message: message.into(),
            status: LineStatus::Active,
        });
        let index = lines.len() - 1;
        SpinnerLineHandle {
            index,
            lines: Arc::clone(&self.lines),
            writer: Arc::clone(&self.writer),
            is_tty: self.is_tty,
        }
    }

    /// Stop the multi-spinner group: signal the render loop to stop, join the
    /// background thread, and finalize any still-active lines.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn stop(self) {
        self.shutdown();
    }

    fn shutdown(&self) {
        self.stop_flag.store(true, Ordering::Release);
        let thread = self.thread.lock().unwrap().take();
        if let Some(thread) = thread {
            let _ = thread.join();
            self.render_final();
        }
    }

    fn render_final(&self) {
        if !self.is_tty {
            return;
        }
        let Ok(snapshot) = self.lines.lock().map(|g| g.clone()) else {
            return;
        };
        let visible = self.last_visible_count.load(Ordering::Relaxed);
        if visible == 0 {
            return;
        }
        let Ok(mut w) = self.writer.lock() else {
            return;
        };
        let _ = write!(w, "\x1b[{visible}A");
        let mut final_visible: usize = 0;
        for line in &snapshot {
            match &line.status {
                LineStatus::Active => {
                    let _ = write!(w, "\r{CLEAR_LINE}\n");
                    final_visible += 1;
                }
                LineStatus::Succeeded => {
                    let _ = write!(w, "\r{}{}{} {}\n", CLEAR_LINE, GREEN, RESET, line.message);
                    final_visible += 1;
                }
                LineStatus::SucceededWith(msg) => {
                    let _ = write!(w, "\r{CLEAR_LINE}{GREEN}{RESET} {msg}\n");
                    final_visible += 1;
                }
                LineStatus::Failed => {
                    let _ = write!(w, "\r{}{}{} {}\n", CLEAR_LINE, RED, RESET, line.message);
                    final_visible += 1;
                }
                LineStatus::FailedWith(msg) => {
                    let _ = write!(w, "\r{CLEAR_LINE}{RED}{RESET} {msg}\n");
                    final_visible += 1;
                }
                LineStatus::Warned => {
                    let _ = write!(w, "\r{}{}{} {}\n", CLEAR_LINE, YELLOW, RESET, line.message);
                    final_visible += 1;
                }
                LineStatus::WarnedWith(msg) => {
                    let _ = write!(w, "\r{CLEAR_LINE}{YELLOW}{RESET} {msg}\n");
                    final_visible += 1;
                }
                LineStatus::Informed => {
                    let _ = write!(w, "\r{}{}{} {}\n", CLEAR_LINE, BLUE, RESET, line.message);
                    final_visible += 1;
                }
                LineStatus::InformedWith(msg) => {
                    let _ = write!(w, "\r{CLEAR_LINE}{BLUE}{RESET} {msg}\n");
                    final_visible += 1;
                }
                LineStatus::Cleared => { /* skip — no output */ }
            }
        }
        for _ in 0..visible.saturating_sub(final_visible) {
            let _ = write!(w, "\r{CLEAR_LINE}\n");
        }
        let _ = w.flush();
    }
}

impl Drop for MultiSpinnerHandle {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// Handle for controlling a single spinner line within a multi-spinner group.
///
/// `SpinnerLineHandle` is [`Send`] so it can be moved to worker threads.
pub struct SpinnerLineHandle {
    index: usize,
    lines: Arc<Mutex<Vec<SpinnerLine>>>,
    writer: Arc<Mutex<Box<dyn io::Write + Send>>>,
    is_tty: bool,
}

impl SpinnerLineHandle {
    /// Update the message for this spinner line.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn update(&self, message: impl Into<String>) {
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].message = message.into();
    }

    /// Finalize this spinner line with a green ✔ and the current message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn success(self) {
        let mut lines = self.lines.lock().unwrap();
        let message = lines[self.index].message.clone();
        lines[self.index].status = LineStatus::Succeeded;
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &message)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a green ✔ and a replacement message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn success_with(self, message: impl Into<String>) {
        let msg = message.into();
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].status = LineStatus::SucceededWith(msg.clone());
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &msg)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a red ✖ and the current message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn fail(self) {
        let mut lines = self.lines.lock().unwrap();
        let message = lines[self.index].message.clone();
        lines[self.index].status = LineStatus::Failed;
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &message)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a red ✖ and a replacement message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn fail_with(self, message: impl Into<String>) {
        let msg = message.into();
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].status = LineStatus::FailedWith(msg.clone());
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &msg)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a yellow ⚠ and the current message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn warn(self) {
        let mut lines = self.lines.lock().unwrap();
        let message = lines[self.index].message.clone();
        lines[self.index].status = LineStatus::Warned;
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &message)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a yellow ⚠ and a replacement message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn warn_with(self, message: impl Into<String>) {
        let msg = message.into();
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].status = LineStatus::WarnedWith(msg.clone());
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &msg)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a blue ℹ and the current message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn info(self) {
        let mut lines = self.lines.lock().unwrap();
        let message = lines[self.index].message.clone();
        lines[self.index].status = LineStatus::Informed;
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &message)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Finalize this spinner line with a blue ℹ and a replacement message.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn info_with(self, message: impl Into<String>) {
        let msg = message.into();
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].status = LineStatus::InformedWith(msg.clone());
        drop(lines);
        if !self.is_tty {
            let mut w = self.writer.lock().unwrap();
            write!(w, "{}", format_finalize_plain("", &msg)).unwrap();
            w.flush().unwrap();
        }
    }

    /// Silently dismiss this spinner line.
    ///
    /// The line disappears from the terminal on the next render frame
    /// (TTY mode) or produces no output at all (plain mode). Remaining
    /// lines collapse together with no gap.
    ///
    /// This consumes the handle, preventing further updates.
    ///
    /// # Panics
    /// Panics if the internal mutex is poisoned.
    pub fn clear(self) {
        let mut lines = self.lines.lock().unwrap();
        lines[self.index].status = LineStatus::Cleared;
        // No writer interaction — the line is silently dismissed.
    }
}

fn multi_spin_loop(
    frames: &[char],
    interval: Duration,
    stop_flag: &Arc<AtomicBool>,
    lines: &Arc<Mutex<Vec<SpinnerLine>>>,
    writer: &Arc<Mutex<Box<dyn io::Write + Send>>>,
    last_visible_count: &Arc<AtomicUsize>,
) {
    let mut frame_idx: usize = 0;
    let mut prev_line_count: usize = 0;

    while !stop_flag.load(Ordering::Acquire) {
        // 1-2-3: Lock, clone state, release.
        let snapshot = lines.lock().unwrap().clone();

        if !snapshot.is_empty() {
            let mut w = writer.lock().unwrap();

            // 4: Move cursor up to overwrite previous frame (skip on first frame).
            if prev_line_count > 0 {
                write!(w, "\x1b[{prev_line_count}A").unwrap();
            }

            // 5: Redraw each visible line.
            let frame_char = frames[frame_idx % frames.len()];
            let mut visible_count: usize = 0;
            for line in &snapshot {
                match &line.status {
                    LineStatus::Active => {
                        write!(w, "\r{}{} {}\n", CLEAR_LINE, frame_char, line.message).unwrap();
                        visible_count += 1;
                    }
                    LineStatus::Succeeded => {
                        write!(w, "\r{}{}{} {}\n", CLEAR_LINE, GREEN, RESET, line.message)
                            .unwrap();
                        visible_count += 1;
                    }
                    LineStatus::SucceededWith(msg) => {
                        write!(w, "\r{CLEAR_LINE}{GREEN}{RESET} {msg}\n").unwrap();
                        visible_count += 1;
                    }
                    LineStatus::Failed => {
                        write!(w, "\r{}{}{} {}\n", CLEAR_LINE, RED, RESET, line.message).unwrap();
                        visible_count += 1;
                    }
                    LineStatus::FailedWith(msg) => {
                        write!(w, "\r{CLEAR_LINE}{RED}{RESET} {msg}\n").unwrap();
                        visible_count += 1;
                    }
                    LineStatus::Warned => {
                        write!(w, "\r{}{}{} {}\n", CLEAR_LINE, YELLOW, RESET, line.message)
                            .unwrap();
                        visible_count += 1;
                    }
                    LineStatus::WarnedWith(msg) => {
                        write!(w, "\r{CLEAR_LINE}{YELLOW}{RESET} {msg}\n").unwrap();
                        visible_count += 1;
                    }
                    LineStatus::Informed => {
                        write!(w, "\r{}{}{} {}\n", CLEAR_LINE, BLUE, RESET, line.message).unwrap();
                        visible_count += 1;
                    }
                    LineStatus::InformedWith(msg) => {
                        write!(w, "\r{CLEAR_LINE}{BLUE}{RESET} {msg}\n").unwrap();
                        visible_count += 1;
                    }
                    LineStatus::Cleared => { /* skip — no output */ }
                }
            }

            // 6: Erase vacated rows left by cleared lines.
            let vacated = prev_line_count.saturating_sub(visible_count);
            for _ in 0..vacated {
                write!(w, "\r{CLEAR_LINE}\n").unwrap();
            }
            // Move cursor back up past the vacated rows so it sits right
            // after the visible lines — keeps prev_line_count correct.
            if vacated > 0 {
                write!(w, "\x1b[{vacated}A").unwrap();
            }

            // 7: Flush the writer.
            w.flush().unwrap();
            prev_line_count = visible_count;
            last_visible_count.store(visible_count, Ordering::Relaxed);
        }

        // 6: Advance the global frame counter.
        frame_idx = frame_idx.wrapping_add(1);
        thread::sleep(interval);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::tests::TestWriter;
    use proptest::prelude::*;

    fn _assert_send() {
        fn assert_send<T: Send>() {}
        assert_send::<SpinnerLineHandle>();
    }

    #[test]
    fn test_multi_spinner_tty_single_spinner_renders() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer_tty(writer, true).start();
        let line = handle.add("Compiling crate");
        thread::sleep(Duration::from_millis(200));
        line.success();
        thread::sleep(Duration::from_millis(100));
        handle.stop();

        let output = reader.output();

        // Verify braille animation frames were rendered
        let braille_frames = ['', '', '', '', '', '', '', '', '', ''];
        assert!(
            braille_frames.iter().any(|&c| output.contains(c)),
            "TTY output must contain braille animation frames"
        );
        // Verify green ✔ for success
        assert!(
            output.contains(GREEN),
            "TTY output must contain GREEN ANSI code"
        );
        assert!(output.contains(""), "TTY output must contain ✔");
        // Verify the message is present
        assert!(
            output.contains("Compiling crate"),
            "TTY output must contain the spinner message"
        );
        // Verify ANSI escape codes are present
        assert!(
            output.contains("\x1b["),
            "TTY output must contain ANSI escape codes"
        );
    }

    #[test]
    fn test_multi_spinner_tty_add_after_finalize() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer_tty(writer, true).start();

        // Add spinner A and finalize it
        let line_a = handle.add("Task A");
        thread::sleep(Duration::from_millis(200));
        line_a.success();

        // Add spinner B after A is finalized
        let line_b = handle.add("Task B");
        thread::sleep(Duration::from_millis(200));
        line_b.fail();

        thread::sleep(Duration::from_millis(100));
        handle.stop();

        let output = reader.output();

        // Both messages should appear in the output
        assert!(
            output.contains("Task A"),
            "output must contain Task A message"
        );
        assert!(
            output.contains("Task B"),
            "output must contain Task B message"
        );
        // ✔ for A (success) and ✖ for B (fail)
        assert!(output.contains(""), "output must contain ✔ for Task A");
        assert!(output.contains(""), "output must contain ✖ for Task B");
    }

    #[test]
    fn test_multi_spinner_drop_renders_same_as_stop() {
        // Run with stop()
        let (writer, buf_stop) = TestWriter::new();
        let reader_stop = writer.clone();
        let handle = MultiSpinner::with_writer_tty(writer, true).start();
        let a = handle.add("Alpha");
        let b = handle.add("Beta");
        thread::sleep(Duration::from_millis(150));
        a.success_with("Alpha done.");
        b.fail_with("Beta failed.");
        thread::sleep(Duration::from_millis(100));
        handle.stop();
        let len_stop = buf_stop.lock().unwrap().len();

        // Run with drop (no stop)
        let (writer, buf_drop) = TestWriter::new();
        let reader_drop = writer.clone();
        let handle = MultiSpinner::with_writer_tty(writer, true).start();
        let a = handle.add("Alpha");
        let b = handle.add("Beta");
        thread::sleep(Duration::from_millis(150));
        a.success_with("Alpha done.");
        b.fail_with("Beta failed.");
        thread::sleep(Duration::from_millis(100));
        drop(handle);
        let len_drop = buf_drop.lock().unwrap().len();

        // Both should have produced final render output (not just animation).
        // Exact byte equality is fragile due to timing, but both should contain
        // the final status symbols.
        let out_stop = reader_stop.output();
        let out_drop = reader_drop.output();
        assert!(out_stop.contains(""), "stop output must contain ✔");
        assert!(out_stop.contains(""), "stop output must contain ✖");
        assert!(out_drop.contains(""), "drop output must contain ✔");
        assert!(out_drop.contains(""), "drop output must contain ✖");
        // Both should have written more than just animation frames
        assert!(len_stop > 0, "stop must produce output");
        assert!(len_drop > 0, "drop must produce output");
    }

    #[test]
    fn test_spinner_line_handle_send_to_thread() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer(writer).start();
        let line_handle = handle.add("Task from another thread");

        // Move the SpinnerLineHandle to another thread and finalize it there
        let t = thread::spawn(move || {
            line_handle.success();
        });
        t.join().expect("thread must not panic");

        let output = reader.output();
        assert_eq!(output, "✔ Task from another thread\n");
    }

    #[test]
    fn test_multiple_handles_finalized_from_different_threads() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer(writer).start();
        let h1 = handle.add("alpha");
        let h2 = handle.add("beta");
        let h3 = handle.add("gamma");

        // Move each handle to a different thread and finalize concurrently
        let threads: Vec<thread::JoinHandle<()>> = vec![
            thread::spawn(move || {
                h1.success();
            }),
            thread::spawn(move || {
                h2.fail();
            }),
            thread::spawn(move || {
                h3.success_with("gamma done");
            }),
        ];

        for t in threads {
            t.join()
                .expect("thread must not panic during concurrent finalization");
        }

        let output = reader.output();
        let output_lines: Vec<&str> = output.split('\n').filter(|l| !l.is_empty()).collect();

        // All three lines must appear exactly once
        assert_eq!(output_lines.len(), 3, "must have exactly 3 output lines");
        assert!(
            output_lines.contains(&"✔ alpha"),
            "output must contain '✔ alpha'"
        );
        assert!(
            output_lines.contains(&"✖ beta"),
            "output must contain '✖ beta'"
        );
        assert!(
            output_lines.contains(&"✔ gamma done"),
            "output must contain '✔ gamma done'"
        );
    }

    #[test]
    fn test_stop_finalization_clear_one_among_others() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer_tty(writer, true).start();

        let line1 = handle.add("first-line");
        let line2 = handle.add("second-line");
        let line3 = handle.add("third-line");

        // Let the render loop run a few frames
        thread::sleep(Duration::from_millis(200));

        line1.success();
        line2.clear();
        line3.fail();

        // Let the render loop pick up finalized statuses
        thread::sleep(Duration::from_millis(100));

        handle.stop();

        let output = reader.output();

        // Extract the final frame: everything from the last cursor-up sequence onward
        let last_cursor_up_pos = {
            let bytes = output.as_bytes();
            let mut last_pos = None;
            for i in 0..bytes.len().saturating_sub(3) {
                if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                    let mut j = i + 2;
                    while j < bytes.len() && bytes[j].is_ascii_digit() {
                        j += 1;
                    }
                    if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                        last_pos = Some(i);
                    }
                }
            }
            last_pos
        };

        let final_frame = last_cursor_up_pos
            .map(|pos| &output[pos..])
            .expect("TTY output must contain at least one cursor-up sequence");

        // Cleared line must NOT appear in the final frame
        assert!(
            !final_frame.contains("second-line"),
            "cleared line 'second-line' must NOT appear in the final frame"
        );
        // Succeeded line must appear
        assert!(
            final_frame.contains("first-line"),
            "succeeded line 'first-line' must appear in the final frame"
        );
        // Failed line must appear
        assert!(
            final_frame.contains("third-line"),
            "failed line 'third-line' must appear in the final frame"
        );
        // Final frame must contain ✔ and ✖
        assert!(final_frame.contains(""), "final frame must contain ✔");
        assert!(final_frame.contains(""), "final frame must contain ✖");
    }

    #[test]
    fn test_stop_finalization_all_cleared() {
        let (writer, buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer_tty(writer, true).start();

        let line1 = handle.add("alpha");
        let line2 = handle.add("beta");
        let line3 = handle.add("gamma");

        // Let the render loop run a few frames
        thread::sleep(Duration::from_millis(200));

        line1.clear();
        line2.clear();
        line3.clear();

        // Let the render loop pick up the cleared statuses
        thread::sleep(Duration::from_millis(100));

        // Capture buffer length before stop
        let len_before_stop = buf.lock().unwrap().len();

        handle.stop();

        let output = reader.output();
        let output_after_stop = &output[len_before_stop..];

        // When all lines are cleared, last_visible_count is 0, so stop()
        // should NOT write any cursor-up escape or final redraw.
        let has_cursor_up_after_stop = {
            let bytes = output_after_stop.as_bytes();
            let mut found = false;
            for i in 0..bytes.len().saturating_sub(3) {
                if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                    let mut j = i + 2;
                    while j < bytes.len() && bytes[j].is_ascii_digit() {
                        j += 1;
                    }
                    if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                        found = true;
                        break;
                    }
                }
            }
            found
        };

        assert!(
            !has_cursor_up_after_stop,
            "stop() must NOT write a cursor-up escape when all lines are cleared"
        );

        // The cleared messages must not appear in any final redraw
        assert!(
            !output_after_stop.contains("alpha"),
            "cleared message 'alpha' must not appear in stop output"
        );
        assert!(
            !output_after_stop.contains("beta"),
            "cleared message 'beta' must not appear in stop output"
        );
        assert!(
            !output_after_stop.contains("gamma"),
            "cleared message 'gamma' must not appear in stop output"
        );
    }

    proptest! {
        #[test]
        fn property_add_grows_line_list(msg in ".*") {
            let (writer, _buf) = TestWriter::new();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg.clone());

            let lines = handle.lines.lock().unwrap();
            prop_assert_eq!(lines.len(), 1, "line count must be 1 after a single add()");
            prop_assert_eq!(lines[0].message.clone(), msg, "stored message must match the input");
            prop_assert_eq!(lines[0].status.clone(), LineStatus::Active, "new line must be Active");

            drop(line_handle);
        }

        #[test]
        fn property_plain_mode_defers_output(msg in ".*") {
            let (writer, buf) = TestWriter::new();

            // with_writer defaults is_tty to false, so this is plain mode
            let handle = MultiSpinner::with_writer(writer).start();
            let _line_handle = handle.add(msg);

            let output = buf.lock().unwrap();
            prop_assert_eq!(output.len(), 0, "add() in plain mode must produce zero bytes of output");
        }

        #[test]
        fn property_update_changes_message(initial in ".*", updated in ".*") {
            let (writer, _buf) = TestWriter::new();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(initial);
            line_handle.update(updated.clone());

            let lines = handle.lines.lock().unwrap();
            prop_assert_eq!(lines[0].message.clone(), updated, "message must match the updated value after update()");
        }

        #[test]
        fn property_plain_mode_success_output(msg in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg.clone());
            line_handle.success();

            let output = reader.output();
            let expected = format!("{}\n", msg);
            prop_assert_eq!(output.clone(), expected, "success() output must be '✔ {{message}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_success_with_output(original in "\\PC*", replacement in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(original);
            line_handle.success_with(replacement.clone());

            let output = reader.output();
            let expected = format!("{}\n", replacement);
            prop_assert_eq!(output.clone(), expected, "success_with() output must be '✔ {{replacement}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_fail_output(msg in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg.clone());
            line_handle.fail();

            let output = reader.output();
            let expected = format!("{}\n", msg);
            prop_assert_eq!(output.clone(), expected, "fail() output must be '✖ {{message}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_fail_with_output(original in "\\PC*", replacement in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(original);
            line_handle.fail_with(replacement.clone());

            let output = reader.output();
            let expected = format!("{}\n", replacement);
            prop_assert_eq!(output.clone(), expected, "fail_with() output must be '✖ {{replacement}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_finalization_order(messages in prop::collection::vec("\\PC+", 2..8)) {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();

            // Add all spinners, collecting their handles
            let handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Finalize in reverse order to prove output follows finalization order, not add order
            let reversed_messages: Vec<String> = messages.iter().rev().cloned().collect();
            for line_handle in handles.into_iter().rev() {
                line_handle.success();
            }

            let output = reader.output();
            let output_lines: Vec<&str> = output.split('\n').filter(|l| !l.is_empty()).collect();

            // Build expected lines in finalization (reverse) order
            let expected: Vec<String> = reversed_messages
                .iter()
                .map(|msg| format!("{}", msg))
                .collect();

            prop_assert_eq!(
                output_lines.len(),
                expected.len(),
                "number of output lines must match number of finalized spinners"
            );

            for (i, (actual, exp)) in output_lines.iter().zip(expected.iter()).enumerate() {
                prop_assert_eq!(
                    *actual,
                    exp.as_str(),
                    "output line {} must match finalization order (reversed add order)",
                    i
                );
            }
        }

        #[test]
        fn property_concurrent_finalization_safety(messages in prop::collection::vec("\\PC+", 2..8)) {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();

            // Add N spinners, collecting their handles
            let line_handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Move each handle to a separate thread and finalize concurrently
            let threads: Vec<thread::JoinHandle<()>> = line_handles
                .into_iter()
                .map(|lh| {
                    thread::spawn(move || {
                        lh.success();
                    })
                })
                .collect();

            // Join all threads — verify no panics occurred
            for t in threads {
                t.join().expect("thread must not panic during concurrent finalization");
            }

            let output = reader.output();
            let output_lines: Vec<&str> = output.split('\n').filter(|l| !l.is_empty()).collect();

            // Every finalized line must appear in output exactly once
            prop_assert_eq!(
                output_lines.len(),
                messages.len(),
                "number of output lines must equal number of finalized spinners"
            );

            for msg in &messages {
                let expected = format!("{}", msg);
                let output_count = output_lines.iter().filter(|&&l| l == expected.as_str()).count();
                let input_count = messages.iter().filter(|m| *m == msg).count();
                prop_assert_eq!(
                    output_count,
                    input_count,
                    "message '{}' appears {} times in input but {} times in output",
                    msg,
                    input_count,
                    output_count
                );
            }
        }

        #[test]
        fn property_clear_transitions_status_to_cleared(msg in ".*") {
            let (writer, _buf) = TestWriter::new();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg);
            line_handle.clear();

            let lines = handle.lines.lock().unwrap();
            prop_assert_eq!(
                lines[0].status.clone(),
                LineStatus::Cleared,
                "clear() must set status to Cleared"
            );
        }

        #[test]
        fn property_clear_produces_no_output_plain_mode(
            messages in prop::collection::vec("\\PC+", 1..=10),
            clear_flags in prop::collection::vec(any::<bool>(), 1..=10),
        ) {
            // Align lengths: use the shorter of the two vecs
            let count = messages.len().min(clear_flags.len());
            let messages = &messages[..count];
            let clear_flags = &clear_flags[..count];

            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();

            let handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Finalize each line: clear if flag is true, success otherwise
            for (lh, &should_clear) in handles.into_iter().zip(clear_flags.iter()) {
                if should_clear {
                    lh.clear();
                } else {
                    lh.success();
                }
            }

            let output = reader.output();
            let output_lines: Vec<&str> = output.split('\n').filter(|l| !l.is_empty()).collect();

            // Count expected success lines (non-cleared)
            let expected_count = clear_flags.iter().filter(|&&f| !f).count();
            prop_assert_eq!(
                output_lines.len(),
                expected_count,
                "output line count must equal number of non-cleared lines"
            );

            // Every output line must be a success-formatted line for a non-cleared message
            for line in &output_lines {
                prop_assert!(
                    line.starts_with(""),
                    "every output line must be a success line, got: '{}'",
                    line
                );
            }
        }

        // Feature: warn-info-finalization, Property 3: Multi-spinner LineStatus transition correctness
        #[test]
        fn property_plain_mode_warn_output(msg in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg.clone());
            line_handle.warn();

            let output = reader.output();
            let expected = format!("{}\n", msg);
            prop_assert_eq!(output.clone(), expected, "warn() output must be '⚠ {{message}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_warn_with_output(original in "\\PC*", replacement in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(original);
            line_handle.warn_with(replacement.clone());

            let output = reader.output();
            let expected = format!("{}\n", replacement);
            prop_assert_eq!(output.clone(), expected, "warn_with() output must be '⚠ {{replacement}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_info_output(msg in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(msg.clone());
            line_handle.info();

            let output = reader.output();
            let expected = format!("{}\n", msg);
            prop_assert_eq!(output.clone(), expected, "info() output must be 'ℹ {{message}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }

        #[test]
        fn property_plain_mode_info_with_output(original in "\\PC*", replacement in "\\PC*") {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer(writer).start();
            let line_handle = handle.add(original);
            line_handle.info_with(replacement.clone());

            let output = reader.output();
            let expected = format!("{}\n", replacement);
            prop_assert_eq!(output.clone(), expected, "info_with() output must be 'ℹ {{replacement}}\\n'");
            prop_assert!(!output.contains("\x1b["), "output must contain no ANSI escape codes");
            prop_assert!(!output.contains('\r'), "output must contain no carriage returns");
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(20))]

        #[test]
        fn property_tty_render_loop_output(
            success_msg in "[a-zA-Z0-9 ]{1,30}",
            fail_msg in "[a-zA-Z0-9 ]{1,30}"
        ) {
            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add two spinner lines
            let line1 = handle.add(success_msg.clone());
            let line2 = handle.add(fail_msg.clone());

            // Sleep to allow a few render cycles (80ms interval)
            thread::sleep(Duration::from_millis(200));

            // Finalize: one success, one fail
            line1.success();
            line2.fail();

            // Sleep briefly to let the render loop pick up the finalized state
            thread::sleep(Duration::from_millis(100));

            handle.stop();

            let output = reader.output();

            // Verify ANSI cursor-up sequences for repositioning
            let has_cursor_up = output.contains("\x1b[") && {
                // Look for \x1b[{n}A pattern
                let bytes = output.as_bytes();
                let mut found = false;
                for i in 0..bytes.len().saturating_sub(3) {
                    if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                        // Check if followed by digit(s) and 'A'
                        let mut j = i + 2;
                        while j < bytes.len() && bytes[j].is_ascii_digit() {
                            j += 1;
                        }
                        if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                            found = true;
                            break;
                        }
                    }
                }
                found
            };
            prop_assert!(has_cursor_up, "TTY multi-spinner output must contain ANSI cursor-up sequences (\\x1b[{{n}}A)");

            // Verify braille animation frame characters are present
            let braille_frames = ['', '', '', '', '', '', '', '', '', ''];
            let has_braille = braille_frames.iter().any(|&c| output.contains(c));
            prop_assert!(has_braille, "TTY multi-spinner output must contain braille animation frame characters");

            // Verify green ✔ with ANSI color codes for success-finalized lines
            prop_assert!(output.contains(GREEN), "TTY multi-spinner output must contain GREEN ANSI code for success");
            prop_assert!(output.contains(""), "TTY multi-spinner output must contain ✔ for success");

            // Verify red ✖ with ANSI color codes for fail-finalized lines
            prop_assert!(output.contains(RED), "TTY multi-spinner output must contain RED ANSI code for failure");
            prop_assert!(output.contains(""), "TTY multi-spinner output must contain ✖ for failure");

            // Verify messages are present in the output
            prop_assert!(output.contains(&success_msg), "TTY multi-spinner output must contain the success message");
            prop_assert!(output.contains(&fail_msg), "TTY multi-spinner output must contain the fail message");
        }

        #[test]
        fn property_cleared_lines_produce_no_rendered_output(
            messages in prop::collection::vec("[a-zA-Z0-9]{3,15}", 2..=5),
            clear_flags in prop::collection::vec(any::<bool>(), 2..=5),
        ) {
            // Align lengths: use the shorter of the two vecs
            let count = messages.len().min(clear_flags.len());
            let messages = &messages[..count];
            let clear_flags = &clear_flags[..count];

            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add all lines
            let handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Sleep briefly to let the render loop run a few frames
            thread::sleep(Duration::from_millis(200));

            // Finalize each line: clear if flag is true, success otherwise
            for (lh, &should_clear) in handles.into_iter().zip(clear_flags.iter()) {
                if should_clear {
                    lh.clear();
                } else {
                    lh.success();
                }
            }

            // Sleep briefly to let the render loop pick up finalized statuses
            thread::sleep(Duration::from_millis(100));

            handle.stop();

            let output = reader.output();

            // Cleared messages must NOT appear in the final stop output.
            // The stop finalization is the last redraw — we check the output
            // after the last cursor-up sequence for the final frame.
            // Find the last cursor-up sequence to isolate the final redraw.
            let last_cursor_up_pos = {
                let bytes = output.as_bytes();
                let mut last_pos = None;
                for i in 0..bytes.len().saturating_sub(3) {
                    if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                        let mut j = i + 2;
                        while j < bytes.len() && bytes[j].is_ascii_digit() {
                            j += 1;
                        }
                        if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                            last_pos = Some(i);
                        }
                    }
                }
                last_pos
            };

            if let Some(pos) = last_cursor_up_pos {
                let final_frame = &output[pos..];

                // Cleared messages must not appear in the final frame
                for (i, msg) in messages.iter().enumerate() {
                    if clear_flags[i] {
                        prop_assert!(
                            !final_frame.contains(msg.as_str()),
                            "cleared message '{}' must NOT appear in the final rendered frame",
                            msg
                        );
                    }
                }

                // Non-cleared (succeeded) messages must appear in the final frame
                for (i, msg) in messages.iter().enumerate() {
                    if !clear_flags[i] {
                        prop_assert!(
                            final_frame.contains(msg.as_str()),
                            "non-cleared message '{}' must appear in the final rendered frame",
                            msg
                        );
                    }
                }
            }
        }

        #[test]
        fn property_visible_line_count_equals_total_minus_cleared(
            messages in prop::collection::vec("[a-zA-Z0-9]{3,15}", 2..=5),
            clear_flags in prop::collection::vec(any::<bool>(), 2..=5),
        ) {
            // Align lengths: use the shorter of the two vecs
            let count = messages.len().min(clear_flags.len());
            let messages = &messages[..count];
            let clear_flags = &clear_flags[..count];

            let (writer, _buf) = TestWriter::new();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add all lines
            let handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Sleep briefly to let the render loop run a few frames
            thread::sleep(Duration::from_millis(200));

            // Finalize each line: clear if flag is true, success otherwise
            let cleared_count = clear_flags.iter().filter(|&&f| f).count();
            let expected_visible = count - cleared_count;

            for (lh, &should_clear) in handles.into_iter().zip(clear_flags.iter()) {
                if should_clear {
                    lh.clear();
                } else {
                    lh.success();
                }
            }

            // Sleep briefly to let the render loop pick up finalized statuses
            thread::sleep(Duration::from_millis(200));

            // Read last_visible_count from the handle (accessible since we're in the same module)
            let visible = handle.last_visible_count.load(Ordering::Relaxed);

            handle.stop();

            prop_assert_eq!(
                visible,
                expected_visible,
                "last_visible_count ({}) must equal total ({}) minus cleared ({})",
                visible,
                count,
                cleared_count
            );
        }
    }

    /// Helper: count non-overlapping occurrences of `needle` in `haystack`.
    fn count_occurrences(haystack: &str, needle: &str) -> usize {
        haystack.matches(needle).count()
    }

    /// Helper: find the byte position of the last cursor-up sequence (\x1b[{n}A)
    /// in the output, returning the position and the cursor-up value.
    fn find_last_cursor_up(output: &str) -> Option<(usize, usize)> {
        let bytes = output.as_bytes();
        let mut last: Option<(usize, usize)> = None;
        for i in 0..bytes.len().saturating_sub(3) {
            if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                let mut j = i + 2;
                while j < bytes.len() && bytes[j].is_ascii_digit() {
                    j += 1;
                }
                if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                    let n: usize = std::str::from_utf8(&bytes[i + 2..j])
                        .unwrap()
                        .parse()
                        .unwrap();
                    last = Some((i, n));
                }
            }
        }
        last
    }

    /// Helper: split output into frames by finding cursor-up sequences.
    /// Each frame starts at a cursor-up sequence and ends before the next one.
    fn find_all_frames(output: &str) -> Vec<&str> {
        let bytes = output.as_bytes();
        let mut positions: Vec<usize> = Vec::new();
        for i in 0..bytes.len().saturating_sub(3) {
            if bytes[i] == b'\x1b' && bytes[i + 1] == b'[' {
                let mut j = i + 2;
                while j < bytes.len() && bytes[j].is_ascii_digit() {
                    j += 1;
                }
                if j > i + 2 && j < bytes.len() && bytes[j] == b'A' {
                    positions.push(i);
                }
            }
        }
        let mut frames = Vec::new();
        for (idx, &pos) in positions.iter().enumerate() {
            let end = if idx + 1 < positions.len() {
                positions[idx + 1]
            } else {
                output.len()
            };
            frames.push(&output[pos..end]);
        }
        frames
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(20))]

        #[test]
        fn property_ghost_lines_render_loop(
            total_lines in 2usize..=8,
            clear_seed in prop::collection::vec(any::<bool>(), 2..=8),
        ) {
            // Ensure at least one line is cleared and at least one remains visible
            // (so we have a bug condition: prev_line_count > visible_count > 0)
            let count = total_lines.min(clear_seed.len());
            let clear_flags: Vec<bool> = clear_seed[..count].to_vec();
            let cleared_count = clear_flags.iter().filter(|&&f| f).count();
            let visible_count = count - cleared_count;

            // Skip cases where nothing is cleared (no bug condition) or all cleared
            // (visible_count == 0, render loop won't produce a frame to check)
            prop_assume!(cleared_count > 0 && visible_count > 0);

            let (writer, buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add all spinner lines
            let handles: Vec<SpinnerLineHandle> = (0..count)
                .map(|i| handle.add(format!("line-{}", i)))
                .collect();

            // Let the render loop establish prev_line_count = count (all lines visible)
            thread::sleep(Duration::from_millis(250));

            // Record buffer position before clearing
            let pos_before_clear = buf.lock().unwrap().len();

            // Clear the chosen subset of lines
            for (lh, &should_clear) in handles.into_iter().zip(clear_flags.iter()) {
                if should_clear {
                    lh.clear();
                } else {
                    lh.success();
                }
            }

            // Let the render loop run at least one frame after the clears
            thread::sleep(Duration::from_millis(250));

            handle.stop();

            let full_output = reader.output();
            let post_clear_output = &full_output[pos_before_clear..];

            // Find ALL frames in post-clear output and check if any has enough CLEAR_LINE.
            // The frame that first renders after the clear should have cursor-up = count
            // (the prev_line_count from before the clear) and should emit CLEAR_LINE
            // for ALL count rows: visible_count content lines + vacated rows.
            //
            // On unfixed code, only visible_count CLEAR_LINE sequences appear per frame,
            // so the vacated rows are NOT erased.
            let frames = find_all_frames(post_clear_output);
            let has_frame_with_vacated_erasure = frames.iter().any(|frame| {
                let cl_count = count_occurrences(frame, CLEAR_LINE);
                // The frame must have CLEAR_LINE for visible lines + vacated rows
                cl_count >= count
            });

            let best_frame_cl = frames.iter()
                .map(|frame| count_occurrences(frame, CLEAR_LINE))
                .max()
                .unwrap_or(0);

            prop_assert!(
                has_frame_with_vacated_erasure,
                "After clearing {} of {} lines, at least one render frame must contain \
                 >= {} CLEAR_LINE sequences (visible={} + vacated={}), but best frame had {}. \
                 This confirms ghost lines are NOT erased.",
                cleared_count, count, count, visible_count, cleared_count,
                best_frame_cl
            );
        }

        #[test]
        fn property_ghost_lines_stop_path(
            total_lines in 2usize..=8,
            clear_seed in prop::collection::vec(any::<bool>(), 2..=8),
        ) {
            let count = total_lines.min(clear_seed.len());
            let clear_flags: Vec<bool> = clear_seed[..count].to_vec();
            let cleared_count = clear_flags.iter().filter(|&&f| f).count();
            let visible_count = count - cleared_count;

            // Need at least one cleared and at least one visible for the stop() path test
            prop_assume!(cleared_count > 0 && visible_count > 0);

            let (writer, buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add all spinner lines
            let handles: Vec<SpinnerLineHandle> = (0..count)
                .map(|i| handle.add(format!("stopline-{}", i)))
                .collect();

            // Let the render loop establish prev_line_count = count
            thread::sleep(Duration::from_millis(250));

            // Clear chosen lines right before stop — minimize time for render loop
            // to process the clear, so stop() must handle the vacated rows
            for (lh, &should_clear) in handles.into_iter().zip(clear_flags.iter()) {
                if should_clear {
                    lh.clear();
                } else {
                    lh.success();
                }
            }

            // Record position just before stop
            let pos_before_stop = buf.lock().unwrap().len();

            // Stop immediately — the render loop may or may not have processed the clear
            handle.stop();

            let full_output = reader.output();
            let stop_output = &full_output[pos_before_stop..];

            // The stop() output should contain a cursor-up and then render visible lines
            // plus erase vacated rows. Total CLEAR_LINE in stop output should be >= cursor_up_val
            // because stop() must erase all rows it moved up over.
            //
            // On unfixed code, stop() only renders visible_count lines and doesn't erase
            // vacated rows, so CLEAR_LINE count will be < cursor_up_val when
            // last_visible_count > visible_count.

            if let Some((_last_up_pos, cursor_up_val)) = find_last_cursor_up(stop_output) {
                let stop_frame = &stop_output[_last_up_pos..];
                let clear_line_count = count_occurrences(stop_frame, CLEAR_LINE);

                // The stop frame should erase all rows it moved up over.
                prop_assert!(
                    clear_line_count >= cursor_up_val,
                    "stop() frame moved cursor up by {} but only emitted {} CLEAR_LINE sequences. \
                     Expected at least {} to erase all rows (visible={}, vacated={}). \
                     Ghost lines remain in the stop output.",
                    cursor_up_val, clear_line_count, cursor_up_val,
                    visible_count, cleared_count
                );
            }
            // If no cursor-up in stop output, the render loop already processed
            // the clear and set last_visible_count to visible_count. In that case,
            // the render loop should have erased the vacated rows (tested above).
        }
    }

    /// Helper: extract the cursor-up value from a frame string.
    /// Returns the N from \x1b[NA at the start of the frame.
    fn extract_cursor_up_value(frame: &str) -> Option<usize> {
        let bytes = frame.as_bytes();
        if bytes.len() >= 4 && bytes[0] == b'\x1b' && bytes[1] == b'[' {
            let mut j = 2;
            while j < bytes.len() && bytes[j].is_ascii_digit() {
                j += 1;
            }
            if j > 2 && j < bytes.len() && bytes[j] == b'A' {
                return std::str::from_utf8(&bytes[2..j])
                    .ok()
                    .and_then(|s| s.parse().ok());
            }
        }
        None
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(20))]

        #[test]
        fn property_preservation_render_no_clears(
            num_spinners in 1usize..=8,
        ) {
            let (writer, buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add N spinner lines (all remain Active — no clears, no finalization)
            let _handles: Vec<SpinnerLineHandle> = (0..num_spinners)
                .map(|i| handle.add(format!("preserve-{}", i)))
                .collect();

            // Let the render loop run several frames
            thread::sleep(Duration::from_millis(350));

            // Capture output from the render loop BEFORE stop
            let render_output_len = buf.lock().unwrap().len();

            // Drop handles to avoid consuming them (they stay Active)
            drop(_handles);

            handle.stop();

            let full_output = reader.output();
            // Only analyze render loop output (before stop), since stop() clears
            // Active lines with just CLEAR_LINE (no message content).
            let render_output = &full_output[..render_output_len];
            let frames = find_all_frames(render_output);

            // We need at least one frame with cursor-up (i.e., not the first frame)
            prop_assert!(
                frames.len() >= 2,
                "Expected at least 2 render frames for {} spinners, got {}",
                num_spinners, frames.len()
            );

            // Check frames after the first one (which has cursor-up)
            for (idx, frame) in frames.iter().enumerate().skip(1) {
                // Each frame should have cursor-up = num_spinners
                if let Some(up_val) = extract_cursor_up_value(frame) {
                    prop_assert_eq!(
                        up_val, num_spinners,
                        "Frame {} cursor-up should be {} (num_spinners), got {}",
                        idx, num_spinners, up_val
                    );
                }

                // Each frame should have exactly num_spinners CLEAR_LINE sequences
                // (one per visible line, no extras for vacated rows since none are cleared)
                let cl_count = count_occurrences(frame, CLEAR_LINE);
                prop_assert_eq!(
                    cl_count, num_spinners,
                    "Frame {} should have exactly {} CLEAR_LINE sequences (one per line), got {}",
                    idx, num_spinners, cl_count
                );

                // Each frame should contain all spinner messages
                for i in 0..num_spinners {
                    let msg = format!("preserve-{}", i);
                    prop_assert!(
                        frame.contains(&msg),
                        "Frame {} must contain message '{}' (no lines cleared)",
                        idx, msg
                    );
                }
            }
        }

        #[test]
        fn property_preservation_stop_no_clears(
            num_spinners in 1usize..=8,
            finalize_pattern in prop::collection::vec(0u8..4, 1..=8),
        ) {
            let count = num_spinners.min(finalize_pattern.len());

            let (writer, buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add spinner lines
            let handles: Vec<SpinnerLineHandle> = (0..count)
                .map(|i| handle.add(format!("stopkeep-{}", i)))
                .collect();

            // Let the render loop run a few frames
            thread::sleep(Duration::from_millis(250));

            // Finalize all lines with non-clear methods only
            // 0 = success, 1 = fail, 2 = success_with, 3 = fail_with
            for (lh, &pattern) in handles.into_iter().zip(finalize_pattern.iter()) {
                match pattern % 4 {
                    0 => lh.success(),
                    1 => lh.fail(),
                    2 => lh.success_with("custom-success"),
                    3 => lh.fail_with("custom-fail"),
                    _ => unreachable!(),
                }
            }

            // Let the render loop pick up finalized statuses
            thread::sleep(Duration::from_millis(100));

            // Record position before stop
            let pos_before_stop = buf.lock().unwrap().len();

            handle.stop();

            let full_output = reader.output();
            let stop_output = &full_output[pos_before_stop..];

            // stop() should move cursor up by count (all lines visible, none cleared)
            if let Some((_, cursor_up_val)) = find_last_cursor_up(stop_output) {
                prop_assert_eq!(
                    cursor_up_val, count,
                    "stop() cursor-up should be {} (all lines visible, none cleared), got {}",
                    count, cursor_up_val
                );
            }

            // stop() should emit exactly count CLEAR_LINE sequences (one per visible line)
            // No extra CLEAR_LINE for vacated rows since nothing was cleared
            if let Some((last_up_pos, _)) = find_last_cursor_up(stop_output) {
                let stop_frame = &stop_output[last_up_pos..];
                let cl_count = count_occurrences(stop_frame, CLEAR_LINE);
                prop_assert_eq!(
                    cl_count, count,
                    "stop() frame should have exactly {} CLEAR_LINE sequences, got {}",
                    count, cl_count
                );
            }
        }

        #[test]
        fn property_preservation_finalized_lines_visible(
            num_spinners in 2usize..=8,
            finalize_pattern in prop::collection::vec(0u8..4, 2..=8),
        ) {
            let count = num_spinners.min(finalize_pattern.len());

            let (writer, _buf) = TestWriter::new();
            let reader = writer.clone();

            let handle = MultiSpinner::with_writer_tty(writer, true).start();

            // Add spinner lines with unique messages
            let messages: Vec<String> = (0..count)
                .map(|i| format!("finmsg-{}", i))
                .collect();

            let handles: Vec<SpinnerLineHandle> = messages
                .iter()
                .map(|msg| handle.add(msg.clone()))
                .collect();

            // Let the render loop run a few frames
            thread::sleep(Duration::from_millis(250));

            // Finalize all lines with non-clear methods
            let patterns: Vec<u8> = finalize_pattern[..count].to_vec();
            for (lh, &pattern) in handles.into_iter().zip(patterns.iter()) {
                match pattern % 4 {
                    0 => lh.success(),
                    1 => lh.fail(),
                    2 => lh.success_with(format!("custom-{}", "ok")),
                    3 => lh.fail_with(format!("custom-{}", "err")),
                    _ => unreachable!(),
                }
            }

            // Let the render loop pick up finalized statuses
            thread::sleep(Duration::from_millis(100));

            handle.stop();

            let output = reader.output();

            // Find the final frame (stop() output)
            if let Some((last_up_pos, _)) = find_last_cursor_up(&output) {
                let final_frame = &output[last_up_pos..];

                // All lines should be visible in the final frame (none cleared)
                // Check that the correct symbol appears for each finalization type
                let mut success_count = 0usize;
                let mut fail_count = 0usize;

                for &pattern in &patterns {
                    match pattern % 4 {
                        0 | 2 => success_count += 1,
                        1 | 3 => fail_count += 1,
                        _ => unreachable!(),
                    }
                }

                // Final frame must contain the right number of success/fail symbols
                let checkmark_count = count_occurrences(final_frame, "");
                let cross_count = count_occurrences(final_frame, "");

                prop_assert_eq!(
                    checkmark_count, success_count,
                    "Final frame should have {} ✔ symbols, got {}",
                    success_count, checkmark_count
                );
                prop_assert_eq!(
                    cross_count, fail_count,
                    "Final frame should have {} ✖ symbols, got {}",
                    fail_count, cross_count
                );

                // Total visible lines = count (none cleared)
                let total_symbols = checkmark_count + cross_count;
                prop_assert_eq!(
                    total_symbols, count,
                    "Final frame should have {} total finalized lines, got {}",
                    count, total_symbols
                );

                // For success/fail (not _with), original messages should appear
                for (i, &pattern) in patterns.iter().enumerate() {
                    match pattern % 4 {
                        0 | 1 => {
                            prop_assert!(
                                final_frame.contains(&messages[i]),
                                "Final frame must contain original message '{}' for line {}",
                                messages[i], i
                            );
                        }
                        2 => {
                            prop_assert!(
                                final_frame.contains("custom-ok"),
                                "Final frame must contain replacement message 'custom-ok' for success_with line {}",
                                i
                            );
                        }
                        3 => {
                            prop_assert!(
                                final_frame.contains("custom-err"),
                                "Final frame must contain replacement message 'custom-err' for fail_with line {}",
                                i
                            );
                        }
                        _ => unreachable!(),
                    }
                }
            }
        }
    }

    #[test]
    fn test_multi_spinner_tty_warn_info_all() {
        let (writer, _buf) = TestWriter::new();
        let reader = writer.clone();

        let handle = MultiSpinner::with_writer_tty(writer, true).start();

        let warn_line = handle.add("Task W");
        let warn_with_line = handle.add("checking W");
        let info_line = handle.add("Task I");
        let info_with_line = handle.add("checking I");

        thread::sleep(Duration::from_millis(200));

        warn_line.warn();
        warn_with_line.warn_with("warned result");
        info_line.info();
        info_with_line.info_with("informed result");

        thread::sleep(Duration::from_millis(100));
        handle.stop();

        let output = reader.output();

        // Warn color and symbol
        assert!(
            output.contains(YELLOW),
            "TTY output must contain YELLOW ANSI code"
        );
        assert!(output.contains(""), "TTY output must contain ⚠");

        // Info color and symbol
        assert!(
            output.contains(BLUE),
            "TTY output must contain BLUE ANSI code"
        );
        assert!(output.contains(""), "TTY output must contain ℹ");

        // warn() keeps original message
        assert!(
            output.contains("Task W"),
            "TTY output must contain warn original message"
        );
        // warn_with() uses replacement message
        assert!(
            output.contains("warned result"),
            "TTY output must contain warn_with replacement message"
        );
        // info() keeps original message
        assert!(
            output.contains("Task I"),
            "TTY output must contain info original message"
        );
        // info_with() uses replacement message
        assert!(
            output.contains("informed result"),
            "TTY output must contain info_with replacement message"
        );
    }
}