blyte 0.86.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::io::{BufRead, ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::serve::TOKEN_HEADER;
use crate::session::{Entry, EntryBody};
use crate::surface_dir::{is_running, list_records_for_root};
use crate::surface_registry::{
    find_by_name, first_line, live_entries, report_unreadable, RegistryEntry, SurfaceState,
};

const OPEN_CODE_TIMEOUT: Duration = Duration::from_secs(5);
const RELOAD_WAIT_TIMEOUT: Duration = Duration::from_secs(20);
const RELOAD_POLL_INTERVAL: Duration = Duration::from_millis(100);
const STOP_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
const STOP_POLL_INTERVAL: Duration = Duration::from_millis(50);
const MAX_OPEN_CODE_RESPONSE_BYTES: usize = 64 * 1024;
const RUNS_WINDOW_DAYS: u64 = 14;
const PICKER_MAX_STOPPED: usize = 5;

/// A stopped surface belonging to a folder.
///
/// `last_used` is in Unix seconds: the `ts` of the last complete entry in
/// `entries.jsonl`, or the record's `started_at` when that file is absent or
/// has no entries (a surface that was started and never used was last used
/// when it started).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct StoppedSurface {
    pub id: String,
    pub name: String,
    pub last_used: u64,
    pub last_message: Option<String>,
}

fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
    let bytes = match std::fs::read(path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
    };

    let mut last_ts: Option<u64> = None;
    let mut last_user_text: Option<String> = None;
    let mut pos = 0usize;
    let mut line_no = 0usize;
    while pos < bytes.len() {
        line_no += 1;
        let start = pos;
        let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
            Some(rel) => pos + rel + 1,
            None => bytes.len(),
        };
        let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
        let line_slice = &bytes[start..end];
        let parsed = std::str::from_utf8(line_slice)
            .map_err(|e| e.to_string())
            .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
        match parsed {
            Ok(entry) => {
                last_ts = Some(entry.ts);
                if let EntryBody::UserMessage { text, .. } = entry.body {
                    last_user_text = Some(text);
                }
            }
            Err(reason) => {
                if !is_last_without_newline {
                    return Err(format!(
                        "invalid entry in {} at line {}: {}",
                        path.display(),
                        line_no,
                        reason
                    ));
                }
            }
        }
        pos = end;
    }

    let last_message = last_user_text.and_then(|text| {
        let line = first_line(&text);
        if line.is_empty() {
            None
        } else {
            Some(line)
        }
    });

    Ok((last_ts, last_message))
}

fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
    let records = list_records_for_root(root, Some(state_dir))?;
    let mut stopped = Vec::new();
    for located in records {
        if is_running(&located.record) {
            continue;
        }
        let entries_path = located.dir.join("entries.jsonl");
        let (last_ts, last_message) = scan_entries_summary(&entries_path)?;
        let last_used = last_ts.unwrap_or(located.record.started_at);
        stopped.push(StoppedSurface {
            id: located.record.id,
            name: located.record.name,
            last_used,
            last_message,
        });
    }
    stopped.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
    Ok(stopped)
}

/// Collect stopped surfaces belonging to `folder`, newest first by `last_used`, then by `id`.
pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
    let root = crate::serve::resolve_folder(folder)?;
    stopped_surfaces_for_root(&root, state_dir)
}

fn format_utc_minute(ts: u64) -> String {
    let days = (ts / 86_400) as i64;
    let secs_of_day = ts % 86_400;
    let hour = secs_of_day / 3_600;
    let min = (secs_of_day % 3_600) / 60;

    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };

    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
}

pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
    if entries.is_empty() {
        return format!("no stopped surfaces in {}\n", folder.display());
    }

    let rows: Vec<(&str, &str, String, String)> = entries
        .iter()
        .map(|entry| {
            let last_used = format_utc_minute(entry.last_used);
            let message = match &entry.last_message {
                Some(msg) => msg.chars().take(60).collect(),
                None => "-".to_string(),
            };
            (entry.name.as_str(), entry.id.as_str(), last_used, message)
        })
        .collect();

    let name_w = rows
        .iter()
        .map(|row| row.0.chars().count())
        .max()
        .unwrap_or(0)
        .max("NAME".len());
    let id_w = rows
        .iter()
        .map(|row| row.1.chars().count())
        .max()
        .unwrap_or(0)
        .max("ID".len());
    let used_w = rows
        .iter()
        .map(|row| row.2.chars().count())
        .max()
        .unwrap_or(0)
        .max("LAST USED".len());

    let mut out = String::new();
    let _ = writeln!(
        out,
        "{:<name_w$}  {:<id_w$}  {:<used_w$}  LAST MESSAGE",
        "NAME", "ID", "LAST USED"
    );
    for (name, id, last_used, message) in rows {
        let _ = writeln!(
            out,
            "{name:<name_w$}  {id:<id_w$}  {last_used:<used_w$}  {message}"
        );
    }
    let _ = writeln!(out);
    let _ = writeln!(out, "resume with: blyte --resume <name or id>");
    out
}

pub fn run_stopped_surfaces(
    folder: &Path,
    state_dir: &Path,
    json: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let root = match crate::serve::resolve_folder(folder) {
        Ok(root) => root,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    let entries = match stopped_surfaces_for_root(&root, state_dir) {
        Ok(entries) => entries,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if json {
        match serde_json::to_string_pretty(&entries) {
            Ok(text) => {
                let _ = writeln!(out, "{text}");
                return 0;
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
                return 1;
            }
        }
    }

    let _ = write!(out, "{}", format_stopped_surfaces_table(&entries, &root));
    0
}

fn repository_name(root: &Path) -> String {
    root.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| root.display().to_string())
}

fn count_running_runs_at(root: &Path, now: SystemTime) -> Result<usize, String> {
    let now = now
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))?
        .as_secs();
    crate::live_runs::collect(root, now, RUNS_WINDOW_DAYS).map(|live| live.running.len())
}

pub fn count_running_runs(root: &Path) -> Result<usize, String> {
    count_running_runs_at(root, SystemTime::now())
}

fn format_surface_state(entry: &RegistryEntry) -> String {
    if entry.state != SurfaceState::Idle {
        return entry.state.display_label().to_string();
    }
    match count_running_runs(&entry.root) {
        Ok(0) => entry.state.display_label().to_string(),
        Ok(1) => "idle (1 run working)".to_string(),
        Ok(n) => format!("idle ({n} runs working)"),
        Err(err) => format!("idle (runs unknown: {err})"),
    }
}

fn format_surface_version(entry: &RegistryEntry) -> String {
    match entry.runtime.is_stale() {
        Ok(false) => entry.runtime.version.clone(),
        Ok(true) => format!("{} (stale)", entry.runtime.version),
        Err(err) => format!("{} (stale unknown: {err})", entry.runtime.version),
    }
}

#[derive(serde::Serialize)]
struct SurfaceJsonEntry<'a> {
    #[serde(flatten)]
    entry: &'a RegistryEntry,
    stale: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stale_error: Option<String>,
    runs_working: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    runs_error: Option<String>,
}

pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
    if entries.is_empty() {
        return "no surfaces are running\n".to_string();
    }

    let rows: Vec<(String, String, &str, String, String, &str)> = entries
        .iter()
        .map(|entry| {
            let name = if current_id == Some(entry.id.as_str()) {
                format!("{} (this surface)", entry.name)
            } else {
                entry.name.clone()
            };
            (
                name,
                repository_name(&entry.root),
                entry.branch.as_deref().unwrap_or("-"),
                format_surface_version(entry),
                format_surface_state(entry),
                entry.doing.as_str(),
            )
        })
        .collect();

    let name_w = rows
        .iter()
        .map(|row| row.0.chars().count())
        .max()
        .unwrap_or(0)
        .max("NAME".len());
    let repo_w = rows
        .iter()
        .map(|row| row.1.chars().count())
        .max()
        .unwrap_or(0)
        .max("REPOSITORY".len());
    let branch_w = rows
        .iter()
        .map(|row| row.2.chars().count())
        .max()
        .unwrap_or(0)
        .max("BRANCH".len());
    let version_w = rows
        .iter()
        .map(|row| row.3.chars().count())
        .max()
        .unwrap_or(0)
        .max("VERSION".len());
    let state_w = rows
        .iter()
        .map(|row| row.4.chars().count())
        .max()
        .unwrap_or(0)
        .max("STATE".len());

    let mut out = String::new();
    let _ = writeln!(
        out,
        "{:<name_w$}  {:<repo_w$}  {:<branch_w$}  {:<version_w$}  {:<state_w$}  DOING",
        "NAME", "REPOSITORY", "BRANCH", "VERSION", "STATE"
    );
    for (name, repo, branch, version, state, doing) in rows {
        let _ = writeln!(
            out,
            "{name:<name_w$}  {repo:<repo_w$}  {branch:<branch_w$}  {version:<version_w$}  {state:<state_w$}  {doing}"
        );
    }
    out
}

pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
    let listing = match live_entries(dir) {
        Ok(listing) => listing,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    report_unreadable(&listing.unreadable, err);

    if json {
        let payload: Vec<SurfaceJsonEntry<'_>> = listing
            .entries
            .iter()
            .map(|entry| {
                let (stale, stale_error) = match entry.runtime.is_stale() {
                    Ok(stale) => (Some(stale), None),
                    Err(stale_err) => (None, Some(stale_err)),
                };
                let (runs_working, runs_error) = match count_running_runs(&entry.root) {
                    Ok(count) => (Some(count), None),
                    Err(runs_err) => (None, Some(runs_err)),
                };
                SurfaceJsonEntry {
                    entry,
                    stale,
                    stale_error,
                    runs_working,
                    runs_error,
                }
            })
            .collect();
        match serde_json::to_string_pretty(&payload) {
            Ok(text) => {
                let _ = writeln!(out, "{text}");
                return 0;
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
                return 1;
            }
        }
    }

    let _ = write!(out, "{}", format_surfaces_table(&listing.entries, None));
    0
}

fn read_surface_token(entry: &RegistryEntry) -> Result<String, String> {
    let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
    let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
        format!(
            "surface {} has no usable token at {}",
            entry.name,
            token_path.display()
        )
    })?;
    let token = raw_token.trim();
    if token.is_empty() || token.contains(['\n', '\r']) {
        return Err(format!(
            "surface {} has no usable token at {}",
            entry.name,
            token_path.display()
        ));
    }
    Ok(token.to_string())
}

pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
    let token = read_surface_token(entry)?;
    Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
}

fn parse_http_status(head: &str) -> Result<u16, String> {
    let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
    let mut parts = status_line.split_whitespace();
    let version = parts
        .next()
        .ok_or_else(|| "empty HTTP response".to_string())?;
    if !version.starts_with("HTTP/") {
        return Err("invalid HTTP response".to_string());
    }
    let code_str = parts
        .next()
        .ok_or_else(|| "missing HTTP status code".to_string())?;
    code_str
        .parse::<u16>()
        .map_err(|_| "invalid HTTP status code".to_string())
}

pub fn request_open_code(entry: &RegistryEntry, token: &str) -> Result<String, String> {
    request_open_code_at(&entry.name, entry.port, token)
}

pub fn request_open_code_at(name: &str, port: u16, token: &str) -> Result<String, String> {
    let deadline = Instant::now() + OPEN_CODE_TIMEOUT;
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream = TcpStream::connect_timeout(&addr, OPEN_CODE_TIMEOUT).map_err(|e| {
        if e.kind() == ErrorKind::ConnectionRefused {
            format!("surface {name} refused the connection on port {port}")
        } else {
            format!("cannot connect to surface {name} on port {port}: {e}")
        }
    })?;

    let remaining = deadline.saturating_duration_since(Instant::now());
    if remaining.is_zero() {
        return Err(format!("surface {name} timed out on port {port}"));
    }
    let _ = stream.set_write_timeout(Some(remaining));

    let req = format!(
        "POST /api/session/open-codes HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
    );
    stream
        .write_all(req.as_bytes())
        .map_err(|e| format!("failed to request an open code from surface {name}: {e}"))?;

    let mut raw = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
            return Err(format!(
                "surface {name} gave an answer blyte does not understand"
            ));
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(format!("surface {name} timed out on port {port}"));
        }
        let _ = stream.set_read_timeout(Some(remaining));
        let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
        match stream.read(&mut chunk[..max_read]) {
            Ok(0) => break,
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
                return Err(format!("surface {name} timed out on port {port}"));
            }
            Err(e) => {
                return Err(format!("failed to read answer from surface {name}: {e}"));
            }
        }
    }

    let text = std::str::from_utf8(&raw)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let (head, resp_body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    let status = parse_http_status(head)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    if status != 200 {
        return Err(format!(
            "surface {name} could not create an open code (HTTP {status})"
        ));
    }
    let parsed: serde_json::Value = serde_json::from_str(resp_body)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let code = parsed
        .get("code")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    Ok(code.to_string())
}

fn known_folders(state_dir: &Path, entries: &[RegistryEntry]) -> Result<Vec<String>, String> {
    let mut folders = BTreeSet::new();
    let repos_path = state_dir.join("repos");
    match std::fs::read_to_string(&repos_path) {
        Ok(content) => {
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let path = PathBuf::from(trimmed);
                if path.is_dir() {
                    folders.insert(trimmed.to_string());
                }
            }
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {}
        Err(e) => {
            return Err(format!("failed to read {}: {e}", repos_path.display()));
        }
    }
    for entry in entries {
        folders.insert(entry.root.to_string_lossy().into_owned());
    }
    Ok(folders.into_iter().collect())
}

pub fn surfaces_payload(
    registry_dir: &Path,
    state_dir: &Path,
    current_id: &str,
    stopped: &[StoppedSurface],
) -> Result<serde_json::Value, String> {
    let listing = live_entries(registry_dir)?;
    let mut entries = listing.entries;
    entries.sort_by(|a, b| {
        a.name
            .cmp(&b.name)
            .then_with(|| a.started_at.cmp(&b.started_at))
    });
    if !entries.iter().any(|entry| entry.id == current_id) {
        return Err(format!(
            "current surface {current_id} is not in the surface registry"
        ));
    }
    let folders = known_folders(state_dir, &entries)?;
    let surfaces: Vec<serde_json::Value> = entries
        .iter()
        .map(|entry| {
            let (url, error) = match surface_url(entry) {
                Ok(url) => (Some(url), None),
                Err(err) => (None, Some(err)),
            };
            let (stale, stale_error) = match entry.runtime.is_stale() {
                Ok(stale) => (Some(stale), None),
                Err(err) => (None, Some(err)),
            };
            serde_json::json!({
                "id": entry.id,
                "name": entry.name,
                "root": entry.root.to_string_lossy(),
                "branch": entry.branch,
                "doing": entry.doing,
                "state": entry.state,
                "version": entry.runtime.version,
                "boot_id": entry.runtime.boot_id,
                "stale": stale,
                "stale_error": stale_error,
                "current": entry.id == current_id,
                "url": url,
                "error": error,
            })
        })
        .collect();
    let unreadable: Vec<serde_json::Value> = listing
        .unreadable
        .iter()
        .map(|record| {
            serde_json::json!({
                "path": record.path.to_string_lossy(),
                "reason": record.reason,
            })
        })
        .collect();
    Ok(serde_json::json!({
        "surfaces": surfaces,
        "stopped": stopped,
        "folders": folders,
        "unreadable": unreadable,
    }))
}

pub fn run_open(
    dir: &Path,
    name: &str,
    opener: &dyn Fn(&str),
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let entry = match find_by_name(dir, name) {
        Ok(entry) => entry,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let token = match read_surface_token(&entry) {
        Ok(token) => token,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let code = match request_open_code(&entry, &token) {
        Ok(code) => code,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
    opener(&url);
    let _ = writeln!(out, "blyte: opened surface {}", entry.name);
    0
}

fn http_json_request(
    name: &str,
    port: u16,
    method: &str,
    path: &str,
    token: &str,
    body: Option<&str>,
    timeout: Duration,
) -> Result<(u16, String), String> {
    let deadline = Instant::now() + timeout;
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| {
        if e.kind() == ErrorKind::ConnectionRefused {
            format!("surface {name} refused the connection on port {port}")
        } else {
            format!("cannot connect to surface {name} on port {port}: {e}")
        }
    })?;

    let remaining = deadline.saturating_duration_since(Instant::now());
    if remaining.is_zero() {
        return Err(format!("surface {name} timed out on port {port}"));
    }
    let _ = stream.set_write_timeout(Some(remaining));

    let req = match body {
        Some(payload) => format!(
            "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
            payload.len()
        ),
        None => format!(
            "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
        ),
    };
    stream
        .write_all(req.as_bytes())
        .map_err(|e| format!("failed to contact surface {name}: {e}"))?;

    let mut raw = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
            return Err(format!(
                "surface {name} gave an answer blyte does not understand"
            ));
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(format!("surface {name} timed out on port {port}"));
        }
        let _ = stream.set_read_timeout(Some(remaining));
        let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
        match stream.read(&mut chunk[..max_read]) {
            Ok(0) => break,
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
                return Err(format!("surface {name} timed out on port {port}"));
            }
            Err(e) => {
                return Err(format!("failed to read answer from surface {name}: {e}"));
            }
        }
    }

    let text = std::str::from_utf8(&raw)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let (head, resp_body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    let status = parse_http_status(head)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    Ok((status, resp_body.to_string()))
}

pub fn request_reload(entry: &RegistryEntry, token: &str) -> Result<(), String> {
    let (status, resp_body) = http_json_request(
        &entry.name,
        entry.port,
        "POST",
        "/api/reload",
        token,
        Some("{}"),
        OPEN_CODE_TIMEOUT,
    )?;
    if status != 200 {
        let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
            .ok()
            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
        return match detail {
            Some(msg) if !msg.trim().is_empty() => Err(format!(
                "surface {} failed to reload (HTTP {status}): {msg}",
                entry.name
            )),
            _ => Err(format!(
                "surface {} failed to reload (HTTP {status})",
                entry.name
            )),
        };
    }
    let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
        format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        )
    })?;
    if parsed.get("reloading").and_then(|v| v.as_bool()) != Some(true) {
        return Err(format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        ));
    }
    Ok(())
}

fn wait_for_reloaded_surface(
    entry: &RegistryEntry,
    token: &str,
    timeout: Duration,
) -> Result<(String, String), String> {
    let deadline = Instant::now() + timeout;
    let mut last_error: Option<String> = None;
    while Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(Instant::now());
        let step_timeout = remaining.min(Duration::from_secs(2));
        match http_json_request(
            &entry.name,
            entry.port,
            "GET",
            "/api/session",
            token,
            None,
            step_timeout,
        ) {
            Ok((200, body)) => {
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body) {
                    if let (Some(boot_id), Some(version)) = (
                        parsed
                            .get("boot_id")
                            .and_then(|v| v.as_str())
                            .map(str::trim),
                        parsed
                            .get("version")
                            .and_then(|v| v.as_str())
                            .map(str::trim),
                    ) {
                        if !boot_id.is_empty() && boot_id != entry.runtime.boot_id {
                            return Ok((version.to_string(), boot_id.to_string()));
                        }
                    }
                }
            }
            Ok((status, _)) => {
                last_error = Some(format!("HTTP {status} while waiting for reload"));
            }
            Err(e) => {
                last_error = Some(e);
            }
        }
        std::thread::sleep(RELOAD_POLL_INTERVAL);
    }
    match last_error {
        Some(e) => Err(format!(
            "surface {} did not come back after reload within {}s ({e})",
            entry.name,
            timeout.as_secs()
        )),
        None => Err(format!(
            "surface {} did not report a new boot_id after reload within {}s",
            entry.name,
            timeout.as_secs()
        )),
    }
}

fn select_surface_targets(
    dir: &Path,
    cwd: &Path,
    target: Option<&str>,
    all: bool,
    err: &mut dyn Write,
) -> Result<Vec<RegistryEntry>, String> {
    let listing = live_entries(dir)?;
    report_unreadable(&listing.unreadable, err);
    let mut entries = listing.entries;
    entries.sort_by(|a, b| {
        a.name
            .cmp(&b.name)
            .then_with(|| a.started_at.cmp(&b.started_at))
    });

    if all {
        return Ok(entries);
    }

    if let Some(name_or_id) = target {
        let matches: Vec<RegistryEntry> = entries
            .iter()
            .filter(|e| e.id == name_or_id || e.name == name_or_id)
            .cloned()
            .collect();
        return match matches.len() {
            0 => {
                if entries.is_empty() {
                    Err(format!(
                        "no running surface named {name_or_id} (no surfaces are running)"
                    ))
                } else {
                    let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
                    Err(format!(
                        "no running surface named {name_or_id}; running surfaces: {}",
                        names.join(", ")
                    ))
                }
            }
            1 => Ok(matches),
            _ => {
                let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
                Err(format!(
                    "more than one running surface is named {name_or_id}; specify by id: {}",
                    ids.join(", ")
                ))
            }
        };
    }

    let root = crate::serve::resolve_folder(cwd)?;
    let matches: Vec<RegistryEntry> = entries.into_iter().filter(|e| e.root == root).collect();
    match matches.len() {
        0 => Err(format!("no running surface for {}", root.display())),
        1 => Ok(matches),
        _ => {
            let names: Vec<String> = matches
                .iter()
                .map(|e| format!("{} ({})", e.name, e.id))
                .collect();
            Err(format!(
                "multiple surfaces are running for {}; specify one by name or id: {}",
                root.display(),
                names.join(", ")
            ))
        }
    }
}

pub fn run_reload(
    dir: &Path,
    cwd: &Path,
    target: Option<&str>,
    all: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let targets = match select_surface_targets(dir, cwd, target, all, err) {
        Ok(targets) => targets,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if targets.is_empty() {
        let _ = writeln!(out, "blyte: no surfaces are running");
        return 0;
    }

    let mut had_error = false;
    let mut pending: Vec<(RegistryEntry, String)> = Vec::new();
    for entry in targets {
        let token = match read_surface_token(&entry) {
            Ok(token) => token,
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
                continue;
            }
        };
        if let Err(e) = request_reload(&entry, &token) {
            let _ = writeln!(err, "blyte: {e}");
            had_error = true;
            continue;
        }
        pending.push((entry, token));
    }

    for (entry, token) in pending {
        match wait_for_reloaded_surface(&entry, &token, RELOAD_WAIT_TIMEOUT) {
            Ok((new_version, _new_boot_id)) => {
                if !new_version.is_empty() && new_version != entry.runtime.version {
                    let _ = writeln!(
                        out,
                        "blyte: reloaded surface {} ({} -> {})",
                        entry.name, entry.runtime.version, new_version
                    );
                } else {
                    let version_label = if new_version.is_empty() {
                        entry.runtime.version.as_str()
                    } else {
                        new_version.as_str()
                    };
                    let _ = writeln!(
                        out,
                        "blyte: reloaded surface {} ({version_label})",
                        entry.name
                    );
                }
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
            }
        }
    }

    if had_error {
        1
    } else {
        0
    }
}

pub fn request_stop(entry: &RegistryEntry, token: &str, force: bool) -> Result<(), String> {
    let payload = if force { "{\"force\":true}" } else { "{}" };
    let (status, resp_body) = http_json_request(
        &entry.name,
        entry.port,
        "POST",
        "/api/stop",
        token,
        Some(payload),
        OPEN_CODE_TIMEOUT,
    )?;
    if status != 200 && status != 202 {
        let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
            .ok()
            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
        return match detail {
            Some(msg) if !msg.trim().is_empty() => Err(format!(
                "surface {} failed to stop (HTTP {status}): {msg}",
                entry.name
            )),
            _ => Err(format!(
                "surface {} failed to stop (HTTP {status})",
                entry.name
            )),
        };
    }
    let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
        format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        )
    })?;
    if parsed.get("stopping").and_then(|v| v.as_bool()) != Some(true) {
        return Err(format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        ));
    }
    Ok(())
}

fn wait_for_surface_stopped(
    dir: &Path,
    entry: &RegistryEntry,
    timeout: Duration,
) -> Result<(), String> {
    let deadline = Instant::now() + timeout;
    let addr = SocketAddr::from(([127, 0, 0, 1], entry.port));
    let reg_path = crate::surface_registry::entry_path(dir, &entry.id);
    while Instant::now() < deadline {
        let port_closed = TcpStream::connect_timeout(&addr, Duration::from_millis(150)).is_err();
        if port_closed {
            if !reg_path.exists() {
                return Ok(());
            }
            if !crate::surface_dir::pid_exists(entry.pid) {
                crate::surface_registry::remove_entry(dir, &entry.id)?;
                return Ok(());
            }
        }
        std::thread::sleep(STOP_POLL_INTERVAL);
    }
    Err(format!(
        "surface {} did not stop within {}s",
        entry.name,
        timeout.as_secs()
    ))
}

pub fn stop_surface_entry(
    dir: &Path,
    entry: &RegistryEntry,
    force: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let token = match read_surface_token(entry) {
        Ok(token) => token,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    if let Err(e) = request_stop(entry, &token, force) {
        let _ = writeln!(err, "blyte: {e}");
        return 1;
    }
    if let Err(e) = wait_for_surface_stopped(dir, entry, STOP_WAIT_TIMEOUT) {
        let _ = writeln!(err, "blyte: {e}");
        return 1;
    }
    let _ = writeln!(
        out,
        "blyte: stopped surface {} ({}); resume with: blyte --resume {}",
        entry.name, entry.id, entry.name
    );
    0
}

pub fn run_stop(
    dir: &Path,
    cwd: &Path,
    target: Option<&str>,
    all: bool,
    force: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let targets = match select_surface_targets(dir, cwd, target, all, err) {
        Ok(targets) => targets,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if targets.is_empty() {
        if all {
            let _ = writeln!(out, "blyte: no surfaces are running");
            return 0;
        }
        let _ = writeln!(err, "blyte: no running surface matched");
        return 1;
    }

    let mut had_error = false;
    let mut pending: Vec<RegistryEntry> = Vec::new();
    for entry in targets {
        let token = match read_surface_token(&entry) {
            Ok(token) => token,
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
                continue;
            }
        };
        if let Err(e) = request_stop(&entry, &token, force) {
            let _ = writeln!(err, "blyte: {e}");
            had_error = true;
            continue;
        }
        pending.push(entry);
    }

    for entry in pending {
        match wait_for_surface_stopped(dir, &entry, STOP_WAIT_TIMEOUT) {
            Ok(()) => {
                let _ = writeln!(
                    out,
                    "blyte: stopped surface {} ({}); resume with: blyte --resume {}",
                    entry.name, entry.id, entry.name
                );
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
            }
        }
    }

    if had_error {
        1
    } else {
        0
    }
}

pub fn open_running_entry(
    entry: &RegistryEntry,
    no_open: bool,
    opener: &dyn Fn(&str),
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let token = match read_surface_token(entry) {
        Ok(token) => token,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if no_open {
        let _ = writeln!(
            out,
            "blyte: surface {} at http://127.0.0.1:{}/#token={token}",
            entry.name, entry.port
        );
        return 0;
    }

    let code = match request_open_code(entry, &token) {
        Ok(code) => code,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
    opener(&url);
    let _ = writeln!(out, "blyte: opened surface {}", entry.name);
    0
}

pub fn running_surfaces_for_folder(
    dir: &Path,
    folder: &Path,
) -> Result<Vec<RegistryEntry>, String> {
    let root = crate::serve::resolve_folder(folder)?;
    let listing = live_entries(dir)?;
    let mut matches: Vec<RegistryEntry> = listing
        .entries
        .into_iter()
        .filter(|e| e.root == root)
        .collect();
    matches.sort_by(|a, b| {
        b.started_at
            .cmp(&a.started_at)
            .then_with(|| a.name.cmp(&b.name))
    });
    Ok(matches)
}

pub fn load_picker_candidates(
    reg_dir: &Path,
    state_dir: &Path,
    folder: &Path,
) -> Result<(Vec<RegistryEntry>, Vec<StoppedSurface>), String> {
    let running = running_surfaces_for_folder(reg_dir, folder).map_err(|e| {
        format!(
            "failed to load running surfaces from {}: {e}",
            reg_dir.display()
        )
    })?;
    let stopped = if running.is_empty() {
        stopped_surfaces(folder, state_dir).map_err(|e| {
            format!(
                "failed to load stopped surfaces for {} (state dir {}): {e}",
                folder.display(),
                state_dir.display()
            )
        })?
    } else {
        Vec::new()
    };
    Ok((running, stopped))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LaunchAction {
    OpenRunning(RegistryEntry),
    Resume(String),
    StartNew,
    StopRunning(RegistryEntry),
    Cancel,
}

pub fn should_run_picker(is_tty: bool, resume: Option<&str>, foreground: bool, new: bool) -> bool {
    is_tty && resume.is_none() && !new && !foreground
}

pub fn pick_launch_action(
    running: &[RegistryEntry],
    stopped: &[StoppedSurface],
    input: &mut dyn BufRead,
    out: &mut dyn Write,
) -> Result<LaunchAction, String> {
    if !running.is_empty() {
        if running.len() == 1 {
            let entry = &running[0];
            writeln!(
                out,
                "Surface `{}` is already running for this folder (port {}).",
                entry.name, entry.port
            )
            .map_err(|e| e.to_string())?;
            writeln!(out, "  [1] Open running surface `{}` (default)", entry.name)
                .map_err(|e| e.to_string())?;
            writeln!(out, "  [n] Start a new surface").map_err(|e| e.to_string())?;
            writeln!(out, "  [s] Stop running surface `{}`", entry.name)
                .map_err(|e| e.to_string())?;
            writeln!(out, "  [q] Cancel").map_err(|e| e.to_string())?;
        } else {
            writeln!(
                out,
                "Multiple surfaces are already running for this folder:"
            )
            .map_err(|e| e.to_string())?;
            for (idx, entry) in running.iter().enumerate() {
                let suffix = if idx == 0 { " (default)" } else { "" };
                writeln!(
                    out,
                    "  [{}] Open `{}` ({}, port {}){}",
                    idx + 1,
                    entry.name,
                    entry.id,
                    entry.port,
                    suffix
                )
                .map_err(|e| e.to_string())?;
            }
            writeln!(out, "  [n] Start a new surface").map_err(|e| e.to_string())?;
            writeln!(
                out,
                "  [s] Stop `{}` (or `s <num>` to stop another)",
                running[0].name
            )
            .map_err(|e| e.to_string())?;
            writeln!(out, "  [q] Cancel").map_err(|e| e.to_string())?;
        }

        loop {
            write!(out, "Choice [1]: ").map_err(|e| e.to_string())?;
            out.flush().map_err(|e| e.to_string())?;
            let mut line = String::new();
            let n = input.read_line(&mut line).map_err(|e| e.to_string())?;
            if n == 0 {
                return Ok(LaunchAction::Cancel);
            }
            let choice = line.trim().to_ascii_lowercase();
            if choice.is_empty() || choice == "o" || choice == "open" {
                return Ok(LaunchAction::OpenRunning(running[0].clone()));
            }
            if choice == "n" || choice == "new" {
                return Ok(LaunchAction::StartNew);
            }
            if choice == "q" || choice == "quit" {
                return Ok(LaunchAction::Cancel);
            }
            if choice == "s" || choice == "stop" {
                return Ok(LaunchAction::StopRunning(running[0].clone()));
            }
            if let Some(rest) = choice
                .strip_prefix("s ")
                .or_else(|| choice.strip_prefix("stop "))
            {
                if let Ok(idx) = rest.trim().parse::<usize>() {
                    if idx >= 1 && idx <= running.len() {
                        return Ok(LaunchAction::StopRunning(running[idx - 1].clone()));
                    }
                }
            }
            if let Ok(idx) = choice.parse::<usize>() {
                if idx >= 1 && idx <= running.len() {
                    return Ok(LaunchAction::OpenRunning(running[idx - 1].clone()));
                }
            }
            writeln!(
                out,
                "Invalid choice. Enter 1..{}, n, s, or q.",
                running.len()
            )
            .map_err(|e| e.to_string())?;
        }
    }

    if !stopped.is_empty() {
        let shown = &stopped[..stopped.len().min(PICKER_MAX_STOPPED)];
        writeln!(out, "Recent stopped surfaces for this folder:").map_err(|e| e.to_string())?;
        for (idx, entry) in shown.iter().enumerate() {
            let suffix = if idx == 0 { " (default)" } else { "" };
            let preview = match &entry.last_message {
                Some(msg) => {
                    let snippet: String = msg.chars().take(40).collect();
                    format!(" - {snippet}")
                }
                None => String::new(),
            };
            writeln!(
                out,
                "  [{}] Resume `{}` ({}){}{}",
                idx + 1,
                entry.name,
                entry.id,
                preview,
                suffix
            )
            .map_err(|e| e.to_string())?;
        }
        writeln!(out, "  [n] Start a fresh surface").map_err(|e| e.to_string())?;
        writeln!(out, "  [q] Cancel").map_err(|e| e.to_string())?;

        loop {
            write!(out, "Choice [1]: ").map_err(|e| e.to_string())?;
            out.flush().map_err(|e| e.to_string())?;
            let mut line = String::new();
            let n = input.read_line(&mut line).map_err(|e| e.to_string())?;
            if n == 0 {
                return Ok(LaunchAction::Cancel);
            }
            let choice = line.trim().to_ascii_lowercase();
            if choice.is_empty() || choice == "r" || choice == "resume" {
                return Ok(LaunchAction::Resume(shown[0].id.clone()));
            }
            if choice == "n" || choice == "new" {
                return Ok(LaunchAction::StartNew);
            }
            if choice == "q" || choice == "quit" {
                return Ok(LaunchAction::Cancel);
            }
            if let Ok(idx) = choice.parse::<usize>() {
                if idx >= 1 && idx <= shown.len() {
                    return Ok(LaunchAction::Resume(shown[idx - 1].id.clone()));
                }
            }
            writeln!(out, "Invalid choice. Enter 1..{}, n, or q.", shown.len())
                .map_err(|e| e.to_string())?;
        }
    }

    Ok(LaunchAction::StartNew)
}

#[cfg(test)]
mod tests {
    use super::{count_running_runs_at, wait_for_surface_stopped};
    use crate::surface_registry::{entry_path, write_entry, RegistryEntry, SurfaceState};
    use crate::surface_version::SurfaceRuntimeInfo;
    use std::net::TcpListener;
    use std::path::Path;
    use std::time::{Duration, Instant, UNIX_EPOCH};

    fn unused_port() -> u16 {
        TcpListener::bind("127.0.0.1:0")
            .expect("bind ephemeral port")
            .local_addr()
            .expect("local addr")
            .port()
    }

    fn test_entry(dir: &Path, id: &str, name: &str, pid: u32, port: u16) -> RegistryEntry {
        let fake_bin = dir.join("blyte-bin");
        if !fake_bin.exists() {
            std::fs::write(&fake_bin, b"#!/bin/sh\n").expect("write fake bin");
        }
        let runtime =
            SurfaceRuntimeInfo::from_binary("0.83.1", &fake_bin, "boot-wait").expect("runtime");
        RegistryEntry {
            id: id.to_string(),
            name: name.to_string(),
            root: dir.to_path_buf(),
            branch: Some("main".to_string()),
            pid,
            port,
            started_at: 1_700_000_000,
            doing: "idle".to_string(),
            state: SurfaceState::Idle,
            runtime,
        }
    }

    #[test]
    fn count_running_runs_at_rejects_pre_epoch_time() {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(tmp.path().join(".git")).expect("create .git");
        let pre_epoch = UNIX_EPOCH
            .checked_sub(Duration::from_secs(1))
            .expect("pre-epoch SystemTime");

        let err = count_running_runs_at(tmp.path(), pre_epoch)
            .expect_err("expected error for system clock before UNIX_EPOCH");
        assert!(
            err.contains("UNIX_EPOCH"),
            "error should name UNIX_EPOCH: {err}"
        );
    }

    #[test]
    fn wait_for_surface_stopped_polls_until_registry_removed_while_pid_alive() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let reg_dir = tmp.path().join("surfaces");
        let entry = test_entry(
            tmp.path(),
            "s00000000000000a1",
            "slow-cleanup",
            std::process::id(),
            unused_port(),
        );
        write_entry(&reg_dir, &entry).expect("write entry");
        let reg_path = entry_path(&reg_dir, &entry.id);
        assert!(reg_path.exists());

        let remover_path = reg_path.clone();
        let handle = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(160));
            std::fs::remove_file(&remover_path).expect("remove registry entry");
        });

        let started = Instant::now();
        wait_for_surface_stopped(&reg_dir, &entry, Duration::from_secs(2))
            .expect("wait should succeed once registry entry is removed");
        let elapsed = started.elapsed();
        handle.join().expect("join remover thread");
        assert!(
            elapsed >= Duration::from_millis(120),
            "returned too early before cleanup finished: {elapsed:?}"
        );
        assert!(!reg_path.exists());
    }

    #[test]
    fn wait_for_surface_stopped_times_out_and_keeps_registry_when_pid_still_alive() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let reg_dir = tmp.path().join("surfaces");
        let entry = test_entry(
            tmp.path(),
            "s00000000000000a2",
            "stuck-cleanup",
            std::process::id(),
            unused_port(),
        );
        write_entry(&reg_dir, &entry).expect("write entry");
        let reg_path = entry_path(&reg_dir, &entry.id);

        let err = wait_for_surface_stopped(&reg_dir, &entry, Duration::from_millis(180))
            .expect_err("expected timeout while pid is alive and registry exists");
        assert!(err.contains("stuck-cleanup"), "got: {err}");
        assert!(err.contains("did not stop"), "got: {err}");
        assert!(
            reg_path.exists(),
            "wait_for_surface_stopped must not delete registry while pid is still alive"
        );
    }

    #[cfg(unix)]
    #[test]
    fn wait_for_surface_stopped_cleans_up_stale_registry_after_pid_exits() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let reg_dir = tmp.path().join("surfaces");
        let mut child = std::process::Command::new("/bin/sh")
            .args(["-c", "exit 0"])
            .spawn()
            .expect("spawn short-lived process");
        let dead_pid = child.id();
        let status = child.wait().expect("reap short-lived process");
        assert!(status.success());

        let entry = test_entry(
            tmp.path(),
            "s00000000000000a3",
            "crashed-surface",
            dead_pid,
            unused_port(),
        );
        write_entry(&reg_dir, &entry).expect("write entry");
        let reg_path = entry_path(&reg_dir, &entry.id);
        assert!(reg_path.exists());

        wait_for_surface_stopped(&reg_dir, &entry, Duration::from_secs(2))
            .expect("dead pid with closed port should clean up stale registry entry");
        assert!(!reg_path.exists());
    }
}