cruise 0.1.62

YAML-driven coding agent workflow orchestrator
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
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
use std::fmt;
use std::io::Write;

use console::style;
use inquire::InquireError;
use serde::Serialize;

use crate::cli::{DEFAULT_MAX_RETRIES, DEFAULT_RATE_LIMIT_RETRIES, ListArgs};
use crate::error::{CruiseError, Result};
use crate::multiline_input::{InputResult, prompt_multiline};
use crate::session::{SessionManager, SessionPhase, SessionState, WorkspaceMode};
use crate::workflow::{list_skippable_after_pr_steps, list_skippable_steps};

/// CLI-only DTO for JSON output. Stable machine-readable form of `SessionState`.
/// `phase` is always a plain string; `phase_error` carries the failure message for Failed sessions.
#[derive(Debug, Serialize)]
struct ListSessionJson {
    id: String,
    base_dir: String,
    phase: &'static str,
    phase_error: Option<String>,
    plan_error: Option<String>,
    config_source: String,
    input: String,
    title: Option<String>,
    current_step: Option<String>,
    created_at: String,
    completed_at: Option<String>,
    worktree_path: Option<String>,
    worktree_branch: Option<String>,
    workspace_mode: WorkspaceMode,
    target_branch: Option<String>,
    pr_url: Option<String>,
    config_path: Option<String>,
    updated_at: Option<String>,
    awaiting_input: bool,
    plan_available: bool,
}

/// `Failed(msg)` is normalized to `phase = "Failed"` + `phase_error = Some(msg)`.
#[cfg(test)]
fn session_to_json(session: SessionState) -> ListSessionJson {
    session_to_json_with_plan_availability(session, false)
}

fn session_to_json_with_plan_availability(
    session: SessionState,
    plan_available: bool,
) -> ListSessionJson {
    let (phase, phase_error): (&'static str, Option<String>) = match session.phase {
        SessionPhase::Draft => ("Draft", None),
        SessionPhase::AwaitingInput => ("AwaitingInput", None),
        SessionPhase::AwaitingApproval => ("AwaitingApproval", None),
        SessionPhase::Planned => ("Planned", None),
        SessionPhase::Running => ("Running", None),
        SessionPhase::Completed => ("Completed", None),
        SessionPhase::Failed(msg) => ("Failed", Some(msg)),
        SessionPhase::Suspended => ("Suspended", None),
    };
    ListSessionJson {
        id: session.id,
        base_dir: session.base_dir.to_string_lossy().into_owned(),
        phase,
        phase_error,
        plan_error: session.plan_error,
        config_source: session.config_source,
        input: session.input,
        title: session.title,
        current_step: session.current_step,
        created_at: session.created_at,
        completed_at: session.completed_at,
        worktree_path: session
            .worktree_path
            .map(|p| p.to_string_lossy().into_owned()),
        worktree_branch: session.worktree_branch,
        workspace_mode: session.workspace_mode,
        target_branch: session.target_branch,
        pr_url: session.pr_url,
        config_path: session
            .config_path
            .map(|p| p.to_string_lossy().into_owned()),
        updated_at: session.updated_at,
        awaiting_input: session.awaiting_input,
        plan_available,
    }
}

/// Serialize a list of sessions to a JSON array (pretty-printed) followed by a newline.
#[cfg(test)]
fn write_sessions_json<W: Write>(mut writer: W, sessions: Vec<SessionState>) -> Result<()> {
    let dtos: Vec<ListSessionJson> = sessions.into_iter().map(session_to_json).collect();
    serde_json::to_writer_pretty(&mut writer, &dtos)
        .map_err(|e| CruiseError::Other(format!("JSON serialization error: {e}")))?;
    writer
        .write_all(b"\n")
        .map_err(|e| CruiseError::Other(format!("write error: {e}")))?;
    Ok(())
}

fn write_sessions_json_with_manager<W: Write>(
    mut writer: W,
    sessions: Vec<SessionState>,
    manager: &SessionManager,
) -> Result<()> {
    let dtos: Vec<ListSessionJson> = sessions
        .into_iter()
        .map(|session| {
            let plan_available = plan_available_for_session(&session, manager);
            session_to_json_with_plan_availability(session, plan_available)
        })
        .collect();
    serde_json::to_writer_pretty(&mut writer, &dtos)
        .map_err(|e| CruiseError::Other(format!("JSON serialization error: {e}")))?;
    writer
        .write_all(b"\n")
        .map_err(|e| CruiseError::Other(format!("write error: {e}")))?;
    Ok(())
}

#[expect(
    clippy::too_many_lines,
    reason = "interactive session picker with multiple action branches"
)]
pub async fn run(args: ListArgs) -> Result<()> {
    let manager = SessionManager::new(crate::paths::data_dir()?);

    if args.json {
        let mut sessions = manager.list()?;
        for s in &mut sessions {
            let _ = manager.reconcile_running_phase(s, false);
        }
        write_sessions_json_with_manager(
            std::io::BufWriter::new(std::io::stdout()),
            sessions,
            &manager,
        )?;
        return Ok(());
    }

    loop {
        let Some(mut session) = pick_session(&manager)? else {
            return Ok(());
        };

        loop {
            let plan_available = plan_available_for_session(&session, &manager);

            // Show plan.md content.
            let plan_path = session.plan_path(&manager.sessions_dir());
            if let Ok(content) = std::fs::read_to_string(&plan_path) {
                crate::display::print_bordered(&content, Some("plan.md"));
            }

            // Action menu.
            let actions = session_actions_with_plan_availability(&session, plan_available);

            // Re-shown after Generate Plan / Replan (SDK turns), which may have
            // left the terminal's foreground process group dead.
            crate::platform::reclaim_terminal_foreground();
            let action = match inquire::Select::new("Action:", actions).prompt() {
                Ok(a) => a,
                Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => "Back",
                Err(e) => return Err(CruiseError::Other(format!("selection error: {e}"))),
            };

            match action {
                "Generate Plan" => {
                    match crate::plan_cmd::generate_plan_for_draft_session(
                        &manager,
                        &mut session,
                        DEFAULT_RATE_LIMIT_RETRIES,
                    )
                    .await
                    {
                        Ok(()) => {
                            session = manager.load(&session.id)?;
                        }
                        Err(e) => {
                            eprintln!("{} Plan generation failed: {e}", style("").red());
                            if let Ok(reloaded) = manager.load(&session.id) {
                                session = reloaded;
                            }
                        }
                    }
                }
                "Approve" => {
                    if !plan_available || session.plan_error.is_some() {
                        eprintln!("{} plan is not ready for approval yet", style("!").yellow());
                        continue;
                    }
                    if let Err(err) =
                        crate::metadata::refresh_session_title_from_session(&manager, &mut session)
                    {
                        eprintln!("warning: failed to refresh session title: {err}");
                    }
                    session.approve();
                    crate::repo_clone::cleanup_after_approval(&manager, &mut session);
                    manager.save(&session)?;
                    eprintln!(
                        "{} Session {} approved. Run with: {}",
                        style("v").green(),
                        session.id,
                        style(format!("cruise run {}", session.id)).cyan()
                    );
                }
                "Run" | "Resume" => {
                    let run_args = crate::cli::RunArgs {
                        session: Some(session.id.clone()),
                        all: false,
                        max_retries: DEFAULT_MAX_RETRIES,
                        rate_limit_retries: DEFAULT_RATE_LIMIT_RETRIES,
                        dry_run: false,
                        cleanup_after_pr: false,
                        no_cleanup_after_pr: false,
                    };
                    return crate::run_cmd::run(run_args).await;
                }
                "Replan" => {
                    let text = match prompt_multiline("Describe the changes needed:")? {
                        InputResult::Submitted(t) => t,
                        InputResult::Cancelled => continue,
                    };
                    crate::plan_cmd::replan_session(
                        &manager,
                        &mut session,
                        text,
                        DEFAULT_RATE_LIMIT_RETRIES,
                    )
                    .await?;
                    // Re-load so subsequent session_actions(&session) uses fresh state.
                    session = manager.load(&session.id)?;
                }
                "Open PR" => {
                    let url = session.pr_url.as_deref().ok_or_else(|| {
                        CruiseError::Other("Open PR action requires pr_url".into())
                    })?;
                    match open_pr_in_browser(url) {
                        Ok(()) => {
                            eprintln!("{} Opening PR in browser...", style("v").green());
                        }
                        Err(e) => {
                            eprintln!("{} {e}", style("x").red());
                        }
                    }
                }
                "Edit Settings" => {
                    match edit_session_settings_interactive(
                        &manager,
                        &mut session,
                        DEFAULT_RATE_LIMIT_RETRIES,
                    )
                    .await
                    {
                        Ok(()) => {
                            if let Ok(reloaded) = manager.load(&session.id) {
                                session = reloaded;
                            }
                        }
                        Err(e) => {
                            eprintln!("{} Edit settings failed: {e}", style("").red());
                            if let Ok(reloaded) = manager.load(&session.id) {
                                session = reloaded;
                            }
                        }
                    }
                }
                "Reset to Planned" => {
                    session.reset_to_planned();
                    manager.save(&session)?;
                    eprintln!(
                        "{} Session {} reset to Planned.",
                        style("v").green(),
                        session.id
                    );
                }
                "Delete" => {
                    if session.repo.is_some() {
                        crate::repo_clone::cleanup_session_workspace(&manager, &session);
                    }
                    manager.delete(&session.id)?;
                    eprintln!("{} Session {} deleted.", style("v").green(), session.id);
                    break;
                }
                _ => {
                    // "Back" -- return to the session list.
                    break;
                }
            }
        }
    }
}

/// Prompts the user to select a session from the list.
/// Returns `Ok(None)` if the list is empty or the user cancels.
fn pick_session(manager: &crate::session::SessionManager) -> Result<Option<SessionState>> {
    let sessions = manager.list()?;
    if sessions.is_empty() {
        eprintln!("No sessions found.");
        return Ok(None);
    }
    let labels: Vec<String> = sessions
        .iter()
        .map(|session| {
            format_session_label_with_plan_availability(
                session,
                plan_available_for_session(session, manager),
            )
        })
        .collect();
    let label_refs: Vec<&str> = labels.iter().map(std::string::String::as_str).collect();
    crate::platform::reclaim_terminal_foreground();
    let selected = match inquire::Select::new("Select a session:", label_refs).prompt() {
        Ok(s) => s,
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
            return Ok(None);
        }
        Err(e) => return Err(CruiseError::Other(format!("selection error: {e}"))),
    };
    let Some(idx) = labels.iter().position(|l| l.as_str() == selected) else {
        return Err(CruiseError::Other(format!(
            "selected label not found: {selected}"
        )));
    };
    Ok(Some(sessions[idx].clone()))
}

/// Returns the action menu items available for the given session.
/// "Run"/"Resume" appears for runnable phases; "Replan" only for Planned.
/// "Open PR" appears for Completed sessions that have a PR URL.
/// "Reset to Planned" appears for Running, Failed, Completed, and Suspended.
/// "Delete" and "Back" are always present (in that order) at the end.
#[cfg(test)]
fn session_actions(session: &SessionState) -> Vec<&'static str> {
    let plan_available =
        !matches!(session.phase, SessionPhase::AwaitingApproval) || session.plan_error.is_none();
    session_actions_with_plan_availability(session, plan_available)
}

fn session_actions_with_plan_availability(
    session: &SessionState,
    plan_available: bool,
) -> Vec<&'static str> {
    let mut actions = vec![];
    match &session.phase {
        SessionPhase::Draft | SessionPhase::AwaitingInput => {
            actions.push("Generate Plan");
        }
        SessionPhase::AwaitingApproval => {
            if plan_available && session.plan_error.is_none() {
                actions.push("Approve");
            }
            actions.push("Edit Settings");
        }
        SessionPhase::Planned => {
            actions.push("Run");
            actions.push("Edit Settings");
            actions.push("Replan");
        }
        SessionPhase::Running => {
            actions.push("Resume");
            actions.push("Reset to Planned");
        }
        SessionPhase::Suspended => {
            actions.push("Resume");
            actions.push("Edit Settings");
            actions.push("Reset to Planned");
        }
        SessionPhase::Failed(_) => {
            actions.push("Run");
            actions.push("Edit Settings");
            actions.push("Reset to Planned");
        }
        SessionPhase::Completed => {
            if session.pr_url.is_some() {
                actions.push("Open PR");
            }
            actions.push("Reset to Planned");
        }
    }
    actions.push("Delete");
    actions.push("Back");
    actions
}

fn plan_available_for_session(session: &SessionState, manager: &SessionManager) -> bool {
    let plan_path = session.plan_path(&manager.sessions_dir());
    crate::metadata::plan_markdown_available(&plan_path)
}

/// Displayable choice for a skip-step multi-select.
struct StepChoice {
    label: String,
    expanded_id: String,
}

impl fmt::Display for StepChoice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.label)
    }
}

/// Edit session settings interactively.
#[expect(clippy::too_many_lines, reason = "interactive UI with many branches")]
async fn edit_session_settings_interactive(
    manager: &SessionManager,
    session: &mut crate::session::SessionState,
    rate_limit_retries: usize,
) -> crate::error::Result<()> {
    use crate::session_edit::{CurrentStepUpdate, SessionSettingsUpdate, update_session_settings};

    // Load config to enumerate available step names for the multi-select.
    // Main-phase steps and after-pr steps are kept separate: after-pr IDs are
    // labelled so the user can tell them apart, and current_step is restricted
    // to main-phase expanded IDs (after-pr steps are not valid resume points).
    let (main_nodes, after_pr_nodes) = match manager.load_config(session) {
        Ok(config) => {
            let main = list_skippable_steps(&config).unwrap_or_default();
            let after = list_skippable_after_pr_steps(&config).unwrap_or_default();
            (main, after)
        }
        Err(_) => (Vec::new(), Vec::new()),
    };
    let main_ids: Vec<String> = main_nodes
        .iter()
        .flat_map(|n| n.expanded_step_ids.clone())
        .collect();
    let after_ids: Vec<String> = after_pr_nodes
        .iter()
        .flat_map(|n| n.expanded_step_ids.clone())
        .collect();

    let choices: Vec<StepChoice> = main_ids
        .iter()
        .map(|id| StepChoice {
            label: id.clone(),
            expanded_id: id.clone(),
        })
        .chain(after_ids.iter().map(|id| StepChoice {
            label: format!("[after-pr] {id}"),
            expanded_id: id.clone(),
        }))
        .collect();

    let skipped_steps = if choices.is_empty() {
        eprintln!("(no steps available from config — skipped_steps unchanged)");
        session.skipped_steps.clone()
    } else {
        let defaults: Vec<usize> = choices
            .iter()
            .enumerate()
            .filter(|(_, choice)| session.skipped_steps.contains(&choice.expanded_id))
            .map(|(i, _)| i)
            .collect();
        match inquire::MultiSelect::new("Steps to skip:", choices)
            .with_default(&defaults)
            .prompt()
        {
            Ok(selected) => selected.into_iter().map(|c| c.expanded_id).collect(),
            Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
                return Ok(());
            }
            Err(e) => {
                return Err(CruiseError::Other(format!("selection error: {e}")));
            }
        }
    };

    // For Failed/Suspended sessions, allow changing current_step interactively.
    // Only main-phase expanded IDs are valid resume points.
    let current_step_update = if matches!(
        &session.phase,
        SessionPhase::Failed(_) | SessionPhase::Suspended
    ) && !main_ids.is_empty()
    {
        let keep = format!(
            "Keep ({})",
            session.current_step.as_deref().unwrap_or("from beginning")
        );
        let clear = "From beginning (clear)".to_string();
        let mut choices = vec![keep.clone(), clear.clone()];
        choices.extend(main_ids);
        match inquire::Select::new("Resume from step:", choices).prompt() {
            Ok(choice) if choice == keep => CurrentStepUpdate::Unchanged,
            Ok(choice) if choice == clear => CurrentStepUpdate::Clear,
            Ok(step_name) => CurrentStepUpdate::Set(step_name),
            Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
                return Ok(());
            }
            Err(e) => {
                return Err(CruiseError::Other(format!("selection error: {e}")));
            }
        }
    } else {
        CurrentStepUpdate::Unchanged
    };

    // Keep the current explicit config path; changing config is not yet
    // supported from the interactive picker.
    let config_path = session
        .config_path
        .as_ref()
        .map(|p| p.to_string_lossy().into_owned());

    let (updated, config_changed) = update_session_settings(
        manager,
        &session.id,
        SessionSettingsUpdate {
            config_path,
            skipped_steps,
            current_step_update,
        },
    )?;
    *session = updated;

    if config_changed {
        eprintln!("{} Config changed — regenerating plan…", style("->").cyan());
        crate::platform::reclaim_terminal_foreground();
        if let Err(e) =
            crate::plan_cmd::regenerate_plan_for_session(manager, session, rate_limit_retries).await
        {
            eprintln!("{} Plan regeneration failed: {e}", style("").red());
            if let Ok(reloaded) = manager.load(&session.id) {
                *session = reloaded;
            }
        } else if let Ok(reloaded) = manager.load(&session.id) {
            *session = reloaded;
        }
    } else {
        eprintln!("{} Settings updated.", style("v").green());
    }

    Ok(())
}

fn open_pr_in_browser(pr_url: &str) -> crate::error::Result<()> {
    let status = std::process::Command::new("gh")
        .args(["pr", "view", pr_url, "--web"])
        .status()
        .map_err(|e| CruiseError::Other(format!("failed to run gh: {e}")))?;
    if !status.success() {
        return Err(CruiseError::Other(format!(
            "gh pr view --web exited with {status}"
        )));
    }
    Ok(())
}

#[cfg(test)]
fn format_session_label(s: &SessionState) -> String {
    let plan_available =
        !matches!(s.phase, SessionPhase::AwaitingApproval) || s.plan_error.is_none();
    format_session_label_with_plan_availability(s, plan_available)
}

fn format_session_label_with_plan_availability(s: &SessionState, plan_available: bool) -> String {
    let (icon, phase_str) = match &s.phase {
        SessionPhase::Draft => (style("").dim(), style("Draft").dim()),
        SessionPhase::AwaitingInput => (style("?").yellow(), style("Awaiting Input").yellow()),
        SessionPhase::AwaitingApproval if s.plan_error.is_some() => {
            (style("").red(), style("Plan Failed").red())
        }
        SessionPhase::AwaitingApproval if !plan_available => {
            (style("-").yellow(), style("Planning").yellow())
        }
        SessionPhase::AwaitingApproval => {
            (style("o").magenta(), style("Awaiting Approval").magenta())
        }
        SessionPhase::Planned => (style("o").cyan(), style("Planned").cyan()),
        SessionPhase::Running => (style(">").yellow(), style("Running").yellow()),
        SessionPhase::Completed => (style("v").green(), style("Completed").green()),
        SessionPhase::Failed(_) => (style("x").red(), style("Failed").red()),
        SessionPhase::Suspended => (style("||").yellow(), style("Suspended").yellow()),
    };
    let date = format_session_date(&s.id);
    let suffix = format_suffix(s);
    let input_preview = crate::display::truncate(s.title_or_input(), 60);
    format!("{icon} {date} {phase_str} {input_preview}{suffix}")
}

/// "`YYYYMMDDHHmmss`" -> "MM/DD HH:MM"
fn format_session_date(id: &str) -> String {
    let (Some(month), Some(day), Some(hour), Some(min)) =
        (id.get(4..6), id.get(6..8), id.get(8..10), id.get(10..12))
    else {
        return id.to_string();
    };
    format!("{month}/{day} {hour}:{min}")
}

/// Returns " \[`step_name`\]" for Running/Suspended, or " PR#N" for Completed with PR URL.
fn format_suffix(s: &SessionState) -> String {
    match &s.phase {
        SessionPhase::Running | SessionPhase::Suspended => s
            .current_step
            .as_ref()
            .map(|step| format!(" [{step}]"))
            .unwrap_or_default(),
        SessionPhase::Completed => s
            .pr_url
            .as_ref()
            .map(|url| {
                let num = url.trim_end_matches('/').rsplit('/').next().unwrap_or("");
                format!(" PR#{num}")
            })
            .unwrap_or_default(),
        _ => String::new(),
    }
}

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

    // -----------------------------------------------------------------------
    // session_actions
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_planned_has_run_and_replan() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: contains "Run" and "Replan"; also contains "Delete" and "Back"
        assert!(
            actions.contains(&"Run"),
            "Planned should have Run: {actions:?}"
        );
        assert!(
            actions.contains(&"Replan"),
            "Planned should have Replan: {actions:?}"
        );
        assert!(
            actions.contains(&"Delete"),
            "should always have Delete: {actions:?}"
        );
        assert!(
            actions.contains(&"Back"),
            "should always have Back: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_has_no_resume() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: "Resume" is absent (Run is used for a fresh start, not Resume)
        assert!(
            !actions.contains(&"Resume"),
            "Planned should NOT have Resume: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_running_has_resume_not_replan() {
        // Given: Running phase
        let session = make_session("20260306143000", "task", SessionPhase::Running);

        // When
        let actions = session_actions(&session);

        // Then: "Resume" is present but "Replan" is absent
        assert!(
            actions.contains(&"Resume"),
            "Running should have Resume: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Running should NOT have Replan: {actions:?}"
        );
        assert!(
            !actions.contains(&"Run"),
            "Running should NOT have Run (use Resume): {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_failed_has_run_not_replan() {
        // Given: Failed phase
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("some error".to_string()),
        );

        // When
        let actions = session_actions(&session);

        // Then: "Run" is present but "Replan" is absent
        assert!(
            actions.contains(&"Run"),
            "Failed should have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Failed should NOT have Replan: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_completed_has_no_run_no_replan_has_reset() {
        // Given: Completed phase, no pr_url
        let session = make_session("20260306143000", "task", SessionPhase::Completed);

        // When
        let actions = session_actions(&session);

        // Then: "Run", "Resume", and "Replan" are absent; "Reset to Planned" is present
        assert!(
            !actions.contains(&"Run"),
            "Completed should NOT have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Resume"),
            "Completed should NOT have Resume: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Completed should NOT have Replan: {actions:?}"
        );
        assert!(
            actions.contains(&"Reset to Planned"),
            "Completed should have Reset to Planned: {actions:?}"
        );
        assert!(
            actions.contains(&"Delete"),
            "should always have Delete: {actions:?}"
        );
        assert!(
            actions.contains(&"Back"),
            "should always have Back: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_run_before_replan() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: "Run" appears before "Replan" (primary action first)
        let run_pos = actions
            .iter()
            .position(|&a| a == "Run")
            .unwrap_or_else(|| panic!("unexpected None"));
        let replan_pos = actions
            .iter()
            .position(|&a| a == "Replan")
            .unwrap_or_else(|| panic!("unexpected None"));
        assert!(
            run_pos < replan_pos,
            "Run should come before Replan in actions list"
        );
    }

    #[test]
    fn test_session_actions_delete_and_back_always_at_end() {
        // Given: Delete and Back are the last two entries across all phases
        let sessions = [
            make_session("20260306143000", "task", SessionPhase::AwaitingApproval),
            make_session("20260306143000", "task", SessionPhase::Planned),
            make_session("20260306143000", "task", SessionPhase::Running),
            make_session("20260306143000", "task", SessionPhase::Completed),
            make_session(
                "20260306143000",
                "task",
                SessionPhase::Failed("err".to_string()),
            ),
        ];

        for session in &sessions {
            let phase = &session.phase;
            // When
            let actions = session_actions(session);
            let len = actions.len();

            // Then: Back is last, Delete is second-to-last
            assert!(
                len >= 2,
                "actions must have at least 2 items for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 1],
                "Back",
                "Back should be last for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 2],
                "Delete",
                "Delete should be second-to-last for {phase:?}: {actions:?}"
            );
        }
    }

    fn make_session(id: &str, input: &str, phase: SessionPhase) -> SessionState {
        let mut s = SessionState::new(
            id.to_string(),
            PathBuf::from("/tmp"),
            "cruise.yaml".to_string(),
            input.to_string(),
        );
        s.phase = phase;
        s
    }

    // -----------------------------------------------------------------------
    // format_session_date
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_session_date_standard_id_returns_mm_dd_hh_mm() {
        // Given: standard 14-digit session ID
        let id = "20260306143000";

        // When
        let result = format_session_date(id);

        // Then: converted to "MM/DD HH:MM" format
        assert_eq!(result, "03/06 14:30");
    }

    #[test]
    fn test_format_session_date_twelve_digit_id_is_accepted() {
        // Given: 12-digit (no seconds) ID
        let id = "202603061430";

        // When
        let result = format_session_date(id);

        // Then: converted to "03/06 14:30"
        assert_eq!(result, "03/06 14:30");
    }

    #[test]
    fn test_format_session_date_midnight() {
        // Given: session at midnight (00:00)
        let id = "20260101000000";

        // When
        let result = format_session_date(id);

        // Then
        assert_eq!(result, "01/01 00:00");
    }

    // -----------------------------------------------------------------------
    // format_suffix
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_suffix_running_with_step_returns_step_bracket() {
        // Given: Running phase, current_step present
        let mut s = make_session("20260306143000", "add feature", SessionPhase::Running);
        s.current_step = Some("implement".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "[implement]" format
        assert_eq!(result, " [implement]");
    }

    #[test]
    fn test_format_suffix_running_without_step_returns_empty() {
        // Given: Running phase, no current_step
        let s = make_session("20260306143000", "add feature", SessionPhase::Running);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_completed_with_pr_url_returns_pr_number() {
        // Given: Completed phase, PR URL present
        let mut s = make_session("20260306143000", "add feature", SessionPhase::Completed);
        s.pr_url = Some("https://github.com/owner/repo/pull/42".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "PR#42" format
        assert_eq!(result, " PR#42");
    }

    #[test]
    fn test_format_suffix_completed_without_pr_url_returns_empty() {
        // Given: Completed phase, no PR URL
        let s = make_session("20260306143000", "add feature", SessionPhase::Completed);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_planned_returns_empty() {
        // Given: Planned phase
        let s = make_session("20260306143000", "add feature", SessionPhase::Planned);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_failed_returns_empty() {
        // Given: Failed phase
        let s = make_session(
            "20260306143000",
            "add feature",
            SessionPhase::Failed("timeout".to_string()),
        );

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    // -----------------------------------------------------------------------
    // format_session_label (expected values for new format)
    // -----------------------------------------------------------------------

    /// Helper to strip ANSI escapes and verify label content.
    fn strip(s: &str) -> String {
        console::strip_ansi_codes(s).to_string()
    }

    #[test]
    fn test_format_session_label_planned_contains_icon_date_phase_input() {
        // Given: Planned session
        let s = make_session(
            "20260306143000",
            "add hello world feature",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains icon, date, phase, and input
        assert!(label.contains('o'), "should contain o icon: {label}");
        assert!(
            label.contains("03/06 14:30"),
            "should contain date: {label}"
        );
        assert!(label.contains("Planned"), "should contain phase: {label}");
        assert!(
            label.contains("add hello world feature"),
            "should contain input: {label}"
        );
    }

    #[test]
    fn test_format_session_label_running_contains_running_icon_and_step() {
        // Given: Running phase, current_step present
        let mut s = make_session("20260307150000", "implement auth", SessionPhase::Running);
        s.current_step = Some("test".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains > icon and step info
        assert!(label.contains('>'), "should contain > icon: {label}");
        assert!(label.contains("Running"), "should contain Running: {label}");
        assert!(label.contains("[test]"), "should contain step: {label}");
    }

    #[test]
    fn test_format_session_label_completed_with_pr_contains_checkmark_and_pr() {
        // Given: Completed phase, PR URL present
        let mut s = make_session("20260307090000", "refactor db", SessionPhase::Completed);
        s.pr_url = Some("https://github.com/owner/repo/pull/42".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains v icon and PR number
        assert!(label.contains('v'), "should contain v icon: {label}");
        assert!(
            label.contains("Completed"),
            "should contain Completed: {label}"
        );
        assert!(label.contains("PR#42"), "should contain PR#42: {label}");
    }

    #[test]
    fn test_format_session_label_failed_contains_cross_icon() {
        // Given: Failed phase
        let s = make_session(
            "20260307103000",
            "fix login bug",
            SessionPhase::Failed("exit 1".to_string()),
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains x icon
        assert!(label.contains('x'), "should contain x icon: {label}");
        assert!(label.contains("Failed"), "should contain Failed: {label}");
    }

    #[test]
    fn test_format_session_label_long_input_is_truncated() {
        // Given: very long input
        let long_input = "a".repeat(200);
        let s = make_session("20260306143000", &long_input, SessionPhase::Planned);

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains ellipsis "..." and total label length is 200 chars or less
        assert!(
            label.contains("..."),
            "long input should be truncated: {label}"
        );
    }

    #[test]
    fn test_format_session_label_prefers_title_over_input() {
        // Given: a session with both raw input and a generated title
        let mut s = make_session(
            "20260306143000",
            "raw task input that should not be the primary label",
            SessionPhase::Planned,
        );
        s.title = Some("Generated session title".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: the generated title is shown instead of the raw input
        assert!(
            label.contains("Generated session title"),
            "should contain generated title: {label}"
        );
        assert!(
            !label.contains("raw task input that should not be the primary label"),
            "should not contain raw input when title is present: {label}"
        );
    }

    #[test]
    fn test_format_session_label_falls_back_to_input_when_title_missing() {
        // Given: a session without a generated title
        let s = make_session(
            "20260306143000",
            "raw task input remains visible",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: the raw input remains the visible fallback
        assert!(
            label.contains("raw task input remains visible"),
            "should contain raw input fallback: {label}"
        );
    }

    // -----------------------------------------------------------------------
    // session_actions -- Reset to Planned coverage
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // session_actions -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_suspended_exact() {
        // Given / When / Then: Suspended action list matches expectations
        assert_eq!(
            session_actions(&make_session("test", "test", SessionPhase::Suspended)),
            vec![
                "Resume",
                "Edit Settings",
                "Reset to Planned",
                "Delete",
                "Back"
            ]
        );
    }

    // -----------------------------------------------------------------------
    // format_suffix -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_suffix_suspended_with_step_returns_step_bracket() {
        // Given: Suspended phase, current_step present
        let mut s = make_session("20260310143000", "add feature", SessionPhase::Suspended);
        s.current_step = Some("implement".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "[implement]" format
        assert_eq!(result, " [implement]");
    }

    #[test]
    fn test_format_suffix_suspended_without_step_returns_empty() {
        // Given: Suspended phase, no current_step
        let s = make_session("20260310143000", "add feature", SessionPhase::Suspended);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    // -----------------------------------------------------------------------
    // format_session_label -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_session_label_suspended_contains_phase_and_step() {
        // Given: Suspended phase, current_step present
        let mut s = make_session("20260310150000", "fix auth", SessionPhase::Suspended);
        s.current_step = Some("test".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains "Suspended" phase and the suspended step name
        assert!(
            label.contains("Suspended"),
            "should contain Suspended: {label}"
        );
        assert!(label.contains("[test]"), "should contain step: {label}");
    }

    // -----------------------------------------------------------------------
    // session_actions -- Delete/Back tail check (all phases including Suspended)
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_delete_and_back_always_at_end_including_suspended() {
        // Given: all phases including Suspended
        let phases = [
            SessionPhase::Planned,
            SessionPhase::Running,
            SessionPhase::Completed,
            SessionPhase::Failed("err".to_string()),
            SessionPhase::Suspended,
        ];

        for phase in &phases {
            // When
            let actions = session_actions(&make_session("test", "test", phase.clone()));
            let len = actions.len();

            // Then: Back is last, Delete is second-to-last
            assert!(
                len >= 2,
                "actions must have at least 2 items for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 1],
                "Back",
                "Back should be last for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 2],
                "Delete",
                "Delete should be second-to-last for {phase:?}: {actions:?}"
            );
        }
    }

    #[test]
    fn test_session_actions_planned_exact() {
        let session = make_session("20260306143000", "task", SessionPhase::Planned);
        assert_eq!(
            session_actions(&session),
            vec!["Run", "Edit Settings", "Replan", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_running_has_reset_to_planned() {
        let session = make_session("20260306143000", "task", SessionPhase::Running);
        assert_eq!(
            session_actions(&session),
            vec!["Resume", "Reset to Planned", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_completed_has_reset_to_planned() {
        // Given: Completed + no pr_url
        let session = make_session("20260306143000", "task", SessionPhase::Completed);
        assert_eq!(
            session_actions(&session),
            vec!["Reset to Planned", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_failed_has_run_and_reset_to_planned() {
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("exit 1".to_string()),
        );
        assert_eq!(
            session_actions(&session),
            vec!["Run", "Edit Settings", "Reset to Planned", "Delete", "Back"]
        );
    }

    // -----------------------------------------------------------------------
    // session_actions -- Open PR coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_completed_with_pr_url_exact_order() {
        // Given: Completed + pr_url present
        let mut session = make_session("20260306143000", "task", SessionPhase::Completed);
        session.pr_url = Some("https://github.com/owner/repo/pull/10".to_string());

        // When
        let actions = session_actions(&session);

        // Then: order is ["Open PR", "Reset to Planned", "Delete", "Back"]
        assert_eq!(
            actions,
            vec!["Open PR", "Reset to Planned", "Delete", "Back"]
        );
    }

    // -----------------------------------------------------------------------
    // open_pr_in_browser
    // -----------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn test_open_pr_in_browser_calls_gh_view_web() {
        use std::os::unix::fs::PermissionsExt;
        use std::{fs, io::Read};

        let tmp = tempfile::tempdir().unwrap_or_else(|e| panic!("{e:?}"));
        let bin_dir = tmp.path().join("bin");
        fs::create_dir_all(&bin_dir).unwrap_or_else(|e| panic!("{e:?}"));
        let log_path = tmp.path().join("gh.log");

        // fake gh: records args to log file then exits 0
        let script_path = bin_dir.join("gh");
        fs::write(
            &script_path,
            format!(
                "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"{}\"\n",
                log_path.display()
            ),
        )
        .unwrap_or_else(|e| panic!("{e:?}"));
        let mut perms = fs::metadata(&script_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap_or_else(|e| panic!("{e:?}"));

        let _guard = crate::test_binary_support::PathEnvGuard::prepend(&bin_dir);

        let url = "https://github.com/owner/repo/pull/42";
        let result = open_pr_in_browser(url);

        assert!(result.is_ok(), "should succeed: {result:?}");

        // Verify log: "pr view <url> --web" was passed
        let mut log_content = String::new();
        fs::File::open(&log_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .read_to_string(&mut log_content)
            .unwrap_or_else(|e| panic!("{e:?}"));
        assert!(
            log_content.contains("pr view"),
            "gh should receive 'pr view': {log_content}"
        );
        assert!(
            log_content.contains(url),
            "gh should receive the PR url: {log_content}"
        );
        assert!(
            log_content.contains("--web"),
            "gh should receive '--web': {log_content}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_open_pr_in_browser_gh_failure_returns_error() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap_or_else(|e| panic!("{e:?}"));
        let bin_dir = tmp.path().join("bin");
        fs::create_dir_all(&bin_dir).unwrap_or_else(|e| panic!("{e:?}"));

        // fake gh: always exits 1
        let script_path = bin_dir.join("gh");
        fs::write(&script_path, "#!/bin/sh\nexit 1\n").unwrap_or_else(|e| panic!("{e:?}"));
        let mut perms = fs::metadata(&script_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap_or_else(|e| panic!("{e:?}"));

        let _guard = crate::test_binary_support::PathEnvGuard::prepend(&bin_dir);

        let result = open_pr_in_browser("https://github.com/owner/repo/pull/1");

        assert!(result.is_err(), "should fail when gh exits non-zero");
    }

    // -----------------------------------------------------------------------
    // AwaitingApproval phase -- actions and labels
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_awaiting_approval_has_approve() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions(&session);

        // Then: contains "Approve" action
        assert!(
            actions.contains(&"Approve"),
            "AwaitingApproval should have Approve: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_has_no_run_no_resume() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions(&session);

        // Then: neither "Run" nor "Resume" since it is not yet approved
        assert!(
            !actions.contains(&"Run"),
            "AwaitingApproval should NOT have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Resume"),
            "AwaitingApproval should NOT have Resume: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_exact_order() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When / Then: order is Approve -> Edit Settings -> Delete -> Back
        assert_eq!(
            session_actions(&session),
            vec!["Approve", "Edit Settings", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_with_plan_error_hides_approve() {
        // Given: background planning failed before approval
        let mut session = make_session("20260311100002", "task", SessionPhase::AwaitingApproval);
        session.plan_error = Some("model error".to_string());

        // When
        let actions = session_actions(&session);

        // Then: approval stays gated until planning succeeds again; Edit Settings still present
        assert_eq!(actions, vec!["Edit Settings", "Delete", "Back"]);
    }

    #[test]
    fn test_session_actions_awaiting_approval_without_plan_hides_approve() {
        // Given: background planning is still in progress
        let session = make_session("20260311100004", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions_with_plan_availability(&session, false);

        // Then: approval stays hidden until a real plan exists; Edit Settings still present
        assert_eq!(actions, vec!["Edit Settings", "Delete", "Back"]);
    }

    #[test]
    fn test_format_session_label_awaiting_approval_contains_phase_text() {
        // Given: AwaitingApproval phase session
        let s = make_session(
            "20260311100000",
            "pending task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains "Awaiting Approval" text and icon
        assert!(
            label.contains("Awaiting Approval"),
            "label should contain 'Awaiting Approval': {label}"
        );
        assert!(label.contains('o'), "label should contain o icon: {label}");
        assert!(
            label.contains("pending task"),
            "label should contain input: {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_not_planned_text() {
        // Given: AwaitingApproval phase session
        let s = make_session(
            "20260311100001",
            "some task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: "Planned" text is absent (to avoid phase confusion)
        assert!(
            !label.contains("Planned"),
            "AwaitingApproval label should NOT contain 'Planned': {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_with_plan_error_shows_plan_failed() {
        // Given: background planning failed before approval
        let mut s = make_session(
            "20260311100003",
            "some task",
            SessionPhase::AwaitingApproval,
        );
        s.plan_error = Some("model error".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: the list surfaces the failure instead of looking approval-ready
        assert!(
            label.contains("Plan Failed"),
            "label should show Plan Failed: {label}"
        );
        assert!(
            !label.contains("Awaiting Approval"),
            "label should not look approval-ready: {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_without_plan_shows_planning() {
        // Given: background planning has started but plan.md is not ready yet
        let s = make_session(
            "20260311100005",
            "some task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label_with_plan_availability(&s, false));

        // Then: the list shows an in-progress label instead of approval-ready text
        assert!(
            label.contains("Planning"),
            "label should show Planning: {label}"
        );
        assert!(
            !label.contains("Awaiting Approval"),
            "label should not show Awaiting Approval: {label}"
        );
    }

    // -- format_session_label: multiline input ---------------------------------

    #[test]
    fn test_format_session_label_multiline_input_shows_first_line_only() {
        // Given: session.input contains multiple lines (e.g. input with embedded newlines)
        let s = make_session(
            "20260306143000",
            "line1\nline2\nline3",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: only the first line appears in the label; remaining lines are absent
        assert!(
            label.contains("line1"),
            "label must contain first line: {label}"
        );
        assert!(
            !label.contains("line2"),
            "label must NOT contain second line: {label}"
        );
        assert!(
            !label.contains("line3"),
            "label must NOT contain third line: {label}"
        );
    }

    #[test]
    fn test_format_session_label_multiline_input_does_not_contain_newline_char() {
        // Given: multi-line input
        let s = make_session(
            "20260306143000",
            "implement feature\nwith extra detail",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: label contains no newline characters (displayable as a single list row)
        assert!(
            !label.contains('\n'),
            "label must not contain newline character: {label:?}"
        );
    }

    // -----------------------------------------------------------------------
    // session_to_json
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_to_json_failed_phase_has_phase_string_and_error() {
        // Given: a session in Failed phase with an error message
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("db error".to_string()),
        );

        // When
        let dto = session_to_json(session);

        // Then: phase is "Failed" and phase_error contains the message
        assert_eq!(dto.phase, "Failed");
        assert_eq!(dto.phase_error, Some("db error".to_string()));
    }

    #[test]
    fn test_session_to_json_all_non_failed_phases_have_null_phase_error() {
        // Given: all non-Failed phases
        let cases = [
            (SessionPhase::AwaitingApproval, "AwaitingApproval"),
            (SessionPhase::Planned, "Planned"),
            (SessionPhase::Running, "Running"),
            (SessionPhase::Completed, "Completed"),
            (SessionPhase::Suspended, "Suspended"),
        ];

        for (phase, expected_str) in cases {
            // When
            let session = make_session("20260306143000", "task", phase);
            let dto = session_to_json(session);

            // Then: phase string matches and phase_error is None
            assert_eq!(
                dto.phase, expected_str,
                "phase string mismatch for {expected_str}"
            );
            assert_eq!(
                dto.phase_error, None,
                "phase_error should be None for {expected_str}"
            );
        }
    }

    #[test]
    fn test_session_to_json_awaiting_approval_plan_error_is_preserved() {
        // Given: a session whose background planning failed before approval
        let mut session = make_session("20260306143000", "task", SessionPhase::AwaitingApproval);
        session.plan_error = Some("planner exited 1".to_string());

        // When
        let dto = session_to_json(session);
        let value =
            serde_json::to_value(&dto).unwrap_or_else(|e| panic!("serialization failed: {e}"));

        // Then: the durable planning error is exposed separately from run-phase failures
        assert_eq!(value["phase"], "AwaitingApproval");
        assert_eq!(value["phase_error"], serde_json::Value::Null);
        assert_eq!(value["plan_error"], "planner exited 1");
        assert_eq!(value["plan_available"], false);
    }

    #[test]
    fn test_session_to_json_with_plan_availability_sets_flag() {
        // Given: an AwaitingApproval session whose plan.md is ready
        let session = make_session("20260306143001", "task", SessionPhase::AwaitingApproval);

        // When
        let dto = session_to_json_with_plan_availability(session, true);
        let value =
            serde_json::to_value(&dto).unwrap_or_else(|e| panic!("serialization failed: {e}"));

        // Then
        assert_eq!(value["plan_available"], true);
    }

    #[test]
    fn test_session_to_json_path_fields_are_strings() {
        // Given: session with base_dir and optional path fields set
        let mut session = make_session("20260306143000", "task", SessionPhase::Planned);
        session.worktree_path = Some(PathBuf::from("/tmp/worktree"));
        session.config_path = Some(PathBuf::from("/home/user/config.yaml"));

        // When
        let dto = session_to_json(session);

        // Then: path fields are serialized as strings
        assert_eq!(dto.base_dir, "/tmp");
        assert_eq!(dto.worktree_path, Some("/tmp/worktree".to_string()));
        assert_eq!(dto.config_path, Some("/home/user/config.yaml".to_string()));
    }

    #[test]
    fn test_session_to_json_null_optional_paths_are_none() {
        let session = make_session("20260306143000", "task", SessionPhase::Planned);
        let dto = session_to_json(session);
        assert_eq!(dto.worktree_path, None);
        assert_eq!(dto.config_path, None);
    }

    #[test]
    fn test_session_to_json_id_and_input_are_preserved() {
        let session = make_session(
            "20260306143000",
            "my task description",
            SessionPhase::Planned,
        );
        let dto = session_to_json(session);
        assert_eq!(dto.id, "20260306143000");
        assert_eq!(dto.input, "my task description");
    }

    // -----------------------------------------------------------------------
    // write_sessions_json
    // -----------------------------------------------------------------------

    #[test]
    fn test_write_sessions_json_empty_list_produces_empty_json_array() {
        // Given: an empty session list
        let sessions: Vec<SessionState> = vec![];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: output parses as a JSON array with 0 entries
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        assert!(value.is_array(), "output should be a JSON array");
        assert_eq!(
            value
                .as_array()
                .unwrap_or_else(|| panic!("expected JSON array"))
                .len(),
            0,
            "empty input should produce an empty array"
        );
    }

    #[test]
    fn test_write_sessions_json_multiple_sessions_produces_array_with_correct_ids() {
        // Given: two sessions with distinct IDs
        let sessions = vec![
            make_session("20260306143000", "task A", SessionPhase::Planned),
            make_session("20260306144500", "task B", SessionPhase::Completed),
        ];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: JSON array contains 2 entries with the expected IDs
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        let arr = value
            .as_array()
            .unwrap_or_else(|| panic!("expected JSON array"));
        assert_eq!(arr.len(), 2, "should have 2 sessions");
        assert_eq!(arr[0]["id"], "20260306143000");
        assert_eq!(arr[1]["id"], "20260306144500");
    }

    #[test]
    fn test_write_sessions_json_failed_phase_is_normalized() {
        // Given: a session in Failed phase
        let sessions = vec![make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("some error".to_string()),
        )];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: JSON entry has phase="Failed" and phase_error="some error"
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        let entry = &value
            .as_array()
            .unwrap_or_else(|| panic!("expected JSON array"))[0];
        assert_eq!(entry["phase"], "Failed");
        assert_eq!(entry["phase_error"], "some error");
    }

    #[test]
    fn test_write_sessions_json_output_ends_with_newline() {
        let sessions: Vec<SessionState> = vec![];
        let mut buf = Vec::new();
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));
        assert!(
            buf.ends_with(b"\n"),
            "JSON output should end with a newline"
        );
    }

    // -----------------------------------------------------------------------
    // SessionPhase::Draft -- actions, label, and JSON
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_draft_exact() {
        // Given: Draft phase session
        let session = make_session("20260523100000", "my draft", SessionPhase::Draft);

        // When
        let actions = session_actions(&session);

        // Then: only Generate Plan, Delete, and Back are offered
        assert_eq!(actions, vec!["Generate Plan", "Delete", "Back"]);
    }

    #[test]
    fn test_format_session_label_draft_contains_draft_text() {
        // Given: Draft phase session
        let s = make_session("20260523110000", "my draft task", SessionPhase::Draft);

        // When
        let label = strip(&format_session_label(&s));

        // Then: the label contains "Draft" and the session input
        assert!(
            label.contains("Draft"),
            "Draft label should contain 'Draft': {label}"
        );
        assert!(
            label.contains("my draft task"),
            "Draft label should contain input: {label}"
        );
    }

    #[test]
    fn test_session_to_json_draft_phase_string() {
        // Given: a session in Draft phase
        let session = make_session("20260523120000", "draft task", SessionPhase::Draft);

        // When
        let dto = session_to_json(session);

        // Then: phase is "Draft" and phase_error is None
        assert_eq!(dto.phase, "Draft");
        assert_eq!(dto.phase_error, None);
    }

    // -----------------------------------------------------------------------
    // "Edit Settings" action availability
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_awaiting_approval_includes_edit_settings() {
        // Given: AwaitingApproval phase with a plan available
        let session = make_session("20260619100000", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions_with_plan_availability(&session, true);

        // Then: "Edit Settings" is present so the user can change config/skip-steps after planning
        assert!(
            actions.contains(&"Edit Settings"),
            "AwaitingApproval should have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_edit_settings_available_even_without_plan() {
        // Given: AwaitingApproval phase but plan not yet available (still planning)
        let session = make_session("20260619100001", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions_with_plan_availability(&session, false);

        // Then: "Edit Settings" is still present (skip-steps can be edited without a plan)
        assert!(
            actions.contains(&"Edit Settings"),
            "AwaitingApproval without plan should still have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_includes_edit_settings() {
        // Given: Planned phase
        let session = make_session("20260619100002", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then
        assert!(
            actions.contains(&"Edit Settings"),
            "Planned should have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_edit_settings_does_not_replace_run_or_replan() {
        // Given: Planned phase
        let session = make_session("20260619100003", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: "Edit Settings" is additive — Run and Replan still exist
        assert!(
            actions.contains(&"Run"),
            "Planned should still have 'Run': {actions:?}"
        );
        assert!(
            actions.contains(&"Replan"),
            "Planned should still have 'Replan': {actions:?}"
        );
        assert!(
            actions.contains(&"Edit Settings"),
            "Planned should have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_completed_has_no_edit_settings() {
        // Given: Completed phase
        let session = make_session("20260619100007", "task", SessionPhase::Completed);

        // When
        let actions = session_actions(&session);

        // Then
        assert!(
            !actions.contains(&"Edit Settings"),
            "Completed should NOT have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_draft_has_no_edit_settings() {
        // Given: Draft phase — config editing is not meaningful before planning starts
        let session = make_session("20260619100008", "task", SessionPhase::Draft);

        // When
        let actions = session_actions(&session);

        // Then
        assert!(
            !actions.contains(&"Edit Settings"),
            "Draft should NOT have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_failed_has_edit_settings() {
        // Given: Failed phase — user should be able to edit skip/current_step and retry
        let session = make_session(
            "20260620100001",
            "task",
            SessionPhase::Failed("step s failed".to_string()),
        );

        // When
        let actions = session_actions(&session);

        // Then: "Edit Settings" is present for Failed phase
        assert!(
            actions.contains(&"Edit Settings"),
            "Failed should have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_suspended_has_edit_settings() {
        // Given: Suspended phase — user should be able to adjust skip/current_step before resuming
        let session = make_session("20260620100002", "task", SessionPhase::Suspended);

        // When
        let actions = session_actions(&session);

        // Then: "Edit Settings" is present for Suspended phase
        assert!(
            actions.contains(&"Edit Settings"),
            "Suspended should have 'Edit Settings': {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_running_has_no_edit_settings() {
        // Given: Running phase — editing is prohibited while the runner is active
        let session = make_session("20260620100003", "task", SessionPhase::Running);

        // When
        let actions = session_actions(&session);

        // Then: "Edit Settings" must NOT appear (runner would race with the edit)
        assert!(
            !actions.contains(&"Edit Settings"),
            "Running should NOT have 'Edit Settings': {actions:?}"
        );
    }
}