blyte 0.85.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
use std::ffi::{OsStr, OsString};
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

#[cfg(unix)]
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
#[cfg(unix)]
use std::os::unix::process::CommandExt;

const START_TIMEOUT: Duration = Duration::from_secs(30);
const POLL_INTERVAL: Duration = Duration::from_millis(25);
const TAIL_LINES: usize = 20;

pub const STRIPPED_ENV_VARS: &[&str] = &[
    "BLYTE_SESSION",
    crate::usage_log::SURFACE_ID_ENV,
    crate::usage_log::SURFACE_NAME_ENV,
    "BLYTE_DISPATCH_ID",
    "BLYTE_DISPATCH_PARENT",
    "BLYTE_MODEL_SHELL",
    "__BLYTE_IN_GATE",
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedSurface {
    pub name: String,
    pub url: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DetachedSurface {
    pub id: String,
    pub name: String,
    pub port: u16,
    pub token: String,
    pub pid: u32,
    pub log_path: PathBuf,
}

pub fn surface_log_path_for_id(state_dir: &Path, id: &str) -> PathBuf {
    state_dir.join("surface").join(format!("{id}.log"))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartError {
    BadRequest(String),
    Internal(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedStartLine {
    name: String,
    port: u16,
    token: String,
}

pub fn resolve_start_folder(raw: &str) -> Result<PathBuf, String> {
    let home = std::env::var_os("HOME");
    resolve_start_folder_with_home(raw, home.as_deref())
}

pub fn resolve_start_folder_with_home(raw: &str, home: Option<&OsStr>) -> Result<PathBuf, String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err("folder must not be empty".to_string());
    }

    let path = if trimmed == "~" {
        let home_dir = home.filter(|v| !v.is_empty()).ok_or_else(|| {
            format!("cannot expand folder {trimmed}: HOME is not set or is empty")
        })?;
        PathBuf::from(home_dir)
    } else if let Some(rest) = trimmed.strip_prefix("~/") {
        let home_dir = home.filter(|v| !v.is_empty()).ok_or_else(|| {
            format!("cannot expand folder {trimmed}: HOME is not set or is empty")
        })?;
        PathBuf::from(home_dir).join(rest.trim_start_matches('/'))
    } else {
        PathBuf::from(trimmed)
    };

    if !path.is_absolute() {
        return Err(format!(
            "folder {} must be an absolute path",
            path.display()
        ));
    }

    let meta = match fs::metadata(&path) {
        Ok(m) => m,
        Err(e) if e.kind() == ErrorKind::NotFound => {
            return Err(format!("folder {} does not exist", path.display()));
        }
        Err(e) => {
            return Err(format!("cannot inspect folder {}: {e}", path.display()));
        }
    };

    if !meta.is_dir() {
        return Err(format!("folder {} is not a directory", path.display()));
    }

    Ok(path)
}

fn random_hex_16() -> Result<String, String> {
    let mut bytes = [0u8; 8];
    let mut file =
        fs::File::open("/dev/urandom").map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
    file.read_exact(&mut bytes)
        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(16);
    for byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    Ok(out)
}

fn ensure_private_dir(dir: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(dir)
            .map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
        fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
            .map_err(|e| format!("failed to set permissions on {}: {e}", dir.display()))?;
    }
    #[cfg(not(unix))]
    {
        fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
    }
    Ok(())
}

fn create_private_log_file_in(dir: &Path, prefix: &str) -> Result<(PathBuf, fs::File), String> {
    ensure_private_dir(dir)?;

    for _ in 0..16 {
        let name = format!("{prefix}{}.log", random_hex_16()?);
        let path = dir.join(name);
        let mut opts = OpenOptions::new();
        opts.create_new(true).read(true).write(true);
        #[cfg(unix)]
        opts.mode(0o600);
        match opts.open(&path) {
            Ok(file) => {
                #[cfg(unix)]
                {
                    fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).map_err(|e| {
                        let _ = fs::remove_file(&path);
                        format!("failed to set permissions on {}: {e}", path.display())
                    })?;
                }
                return Ok((path, file));
            }
            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
            Err(e) => {
                return Err(format!("failed to create log file {}: {e}", path.display()));
            }
        }
    }

    Err(format!(
        "failed to create a unique log file in {}",
        dir.display()
    ))
}

fn create_log_file(state_dir: &Path) -> Result<(PathBuf, fs::File), String> {
    create_private_log_file_in(&state_dir.join("surface-starts"), "")
}

pub fn fetch_health_surface_id(port: u16) -> Result<String, String> {
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let timeout = Duration::from_secs(5);
    let mut stream = TcpStream::connect_timeout(&addr, timeout)
        .map_err(|e| format!("failed to connect to surface health endpoint on port {port}: {e}"))?;
    let _ = stream.set_read_timeout(Some(timeout));
    let _ = stream.set_write_timeout(Some(timeout));
    let req =
        format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
    stream
        .write_all(req.as_bytes())
        .map_err(|e| format!("failed to write health request on port {port}: {e}"))?;
    let mut raw = Vec::new();
    stream
        .read_to_end(&mut raw)
        .map_err(|e| format!("failed to read health response on port {port}: {e}"))?;
    let text = String::from_utf8_lossy(&raw);
    let (_, body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| format!("malformed health response from port {port}"))?;
    let parsed: serde_json::Value = serde_json::from_str(body)
        .map_err(|e| format!("invalid health JSON from port {port}: {e}"))?;
    let id = parsed
        .get("surface_id")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| format!("health response from port {port} is missing surface_id"))?;
    Ok(id.to_string())
}

fn parse_start_line(line: &str) -> Option<ParsedStartLine> {
    let trimmed = line.trim_end_matches('\r');
    let rest = trimmed.strip_prefix("blyte: surface ")?;
    let (name, url) = rest.rsplit_once(" at ")?;
    if name.is_empty() {
        return None;
    }
    let after_host = url.strip_prefix("http://127.0.0.1:")?;
    let (port_str, token) = after_host.split_once("/#token=")?;
    let port: u16 = port_str.parse().ok()?;
    if port == 0 {
        return None;
    }
    let token = token.trim();
    if token.is_empty() {
        return None;
    }
    Some(ParsedStartLine {
        name: name.to_string(),
        port,
        token: token.to_string(),
    })
}

fn find_start_line_in_complete_lines(text: &str) -> Option<ParsedStartLine> {
    let mut rest = text;
    while let Some((line, after)) = rest.split_once('\n') {
        if let Some(parsed) = parse_start_line(line) {
            return Some(parsed);
        }
        rest = after;
    }
    None
}

fn redact_tokens(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(idx) = rest.find("#token=") {
        out.push_str(&rest[..idx]);
        out.push_str("#token=<redacted>");
        let after = &rest[idx + "#token=".len()..];
        let end = after
            .find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ')' | ']'))
            .unwrap_or(after.len());
        rest = &after[end..];
    }
    out.push_str(rest);
    out
}

fn last_lines_redacted(text: &str, max_lines: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    let start = lines.len().saturating_sub(max_lines);
    let joined = lines[start..].join("\n");
    redact_tokens(&joined)
}

pub fn start_surface_in(raw_folder: &str, state_dir: &Path) -> Result<StartedSurface, StartError> {
    let folder = resolve_start_folder(raw_folder).map_err(StartError::BadRequest)?;
    let exe = std::env::current_exe()
        .map_err(|e| StartError::Internal(format!("failed to locate blyte executable: {e}")))?;
    start_surface_with_exe(
        &folder,
        state_dir,
        &exe,
        &["--foreground", "--no-open"],
        START_TIMEOUT,
    )
}

fn promote_start_log(
    state_dir: &Path,
    staging_path: &Path,
    surface_id: &str,
) -> Result<PathBuf, String> {
    let dest = surface_log_path_for_id(state_dir, surface_id);
    if let Some(parent) = dest.parent() {
        ensure_private_dir(parent)?;
    }
    fs::rename(staging_path, &dest).map_err(|e| {
        format!(
            "failed to move surface log from {} to {}: {e}",
            staging_path.display(),
            dest.display()
        )
    })?;
    Ok(dest)
}

pub fn launch_detached_surface(
    folder: &Path,
    state_dir: &Path,
    args: &[OsString],
) -> Result<DetachedSurface, String> {
    let exe =
        std::env::current_exe().map_err(|e| format!("failed to locate blyte executable: {e}"))?;
    launch_detached_surface_with_exe(folder, state_dir, &exe, args, START_TIMEOUT)
}

pub fn launch_detached_surface_with_exe(
    folder: &Path,
    state_dir: &Path,
    exe: &Path,
    args: &[OsString],
    timeout: Duration,
) -> Result<DetachedSurface, String> {
    let surface_dir = state_dir.join("surface");
    let (log_path, stdout_file) = create_private_log_file_in(&surface_dir, ".starting-")?;
    let stderr_file = match stdout_file.try_clone() {
        Ok(f) => f,
        Err(e) => {
            let _ = fs::remove_file(&log_path);
            return Err(format!("failed to duplicate log file handle: {e}"));
        }
    };

    let mut cmd = Command::new(exe);
    cmd.args(args)
        .current_dir(folder)
        .stdin(Stdio::null())
        .stdout(Stdio::from(stdout_file))
        .stderr(Stdio::from(stderr_file));

    for var in STRIPPED_ENV_VARS {
        cmd.env_remove(var);
    }

    #[cfg(unix)]
    unsafe {
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }

    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            let _ = fs::remove_file(&log_path);
            return Err(format!(
                "failed to start blyte in {}: {e}",
                folder.display()
            ));
        }
    };
    let pid = child.id();

    let deadline = Instant::now() + timeout;
    loop {
        if let Ok(bytes) = fs::read(&log_path) {
            let text = String::from_utf8_lossy(&bytes);
            if let Some(parsed) = find_start_line_in_complete_lines(&text) {
                let surface_id = match fetch_health_surface_id(parsed.port) {
                    Ok(id) => id,
                    Err(e) => {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _ = fs::remove_file(&log_path);
                        return Err(e);
                    }
                };
                let final_log = match promote_start_log(state_dir, &log_path, &surface_id) {
                    Ok(path) => path,
                    Err(e) => {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _ = fs::remove_file(&log_path);
                        return Err(e);
                    }
                };
                std::thread::spawn(move || {
                    let _ = child.wait();
                });
                return Ok(DetachedSurface {
                    id: surface_id,
                    name: parsed.name,
                    port: parsed.port,
                    token: parsed.token,
                    pid,
                    log_path: final_log,
                });
            }
        }

        match child.try_wait() {
            Ok(Some(status)) => {
                let bytes = match fs::read(&log_path) {
                    Ok(bytes) => bytes,
                    Err(e) => {
                        let _ = fs::remove_file(&log_path);
                        return Err(format!(
                            "surface in {} exited before starting ({status}); failed to read start log {}: {e}",
                            folder.display(),
                            log_path.display()
                        ));
                    }
                };
                let text = String::from_utf8_lossy(&bytes);
                let _ = fs::remove_file(&log_path);
                let tail = last_lines_redacted(&text, TAIL_LINES);
                let msg = if tail.trim().is_empty() {
                    format!(
                        "surface in {} exited before starting ({status})",
                        folder.display()
                    )
                } else {
                    format!(
                        "surface in {} exited before starting ({status}):\n{tail}",
                        folder.display()
                    )
                };
                return Err(msg);
            }
            Ok(None) => {}
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                let _ = fs::remove_file(&log_path);
                return Err(format!("failed to check started surface process: {e}"));
            }
        }

        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            let _ = child.kill();
            let _ = child.wait();
            return Err(format!(
                "timed out after {} s waiting for surface in {} to start; log kept at {}",
                timeout.as_secs(),
                folder.display(),
                log_path.display()
            ));
        }
        std::thread::sleep(POLL_INTERVAL.min(remaining));
    }
}

pub fn start_surface_with_exe(
    folder: &Path,
    state_dir: &Path,
    exe: &Path,
    args: &[&str],
    timeout: Duration,
) -> Result<StartedSurface, StartError> {
    let (log_path, stdout_file) = create_log_file(state_dir).map_err(StartError::Internal)?;
    let stderr_file = match stdout_file.try_clone() {
        Ok(f) => f,
        Err(e) => {
            let _ = fs::remove_file(&log_path);
            return Err(StartError::Internal(format!(
                "failed to duplicate log file handle: {e}"
            )));
        }
    };

    let mut cmd = Command::new(exe);
    cmd.args(args)
        .current_dir(folder)
        .stdin(Stdio::null())
        .stdout(Stdio::from(stdout_file))
        .stderr(Stdio::from(stderr_file));

    for var in STRIPPED_ENV_VARS {
        cmd.env_remove(var);
    }

    #[cfg(unix)]
    unsafe {
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }

    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            let _ = fs::remove_file(&log_path);
            return Err(StartError::Internal(format!(
                "failed to start blyte in {}: {e}",
                folder.display()
            )));
        }
    };

    let deadline = Instant::now() + timeout;
    loop {
        if let Ok(bytes) = fs::read(&log_path) {
            let text = String::from_utf8_lossy(&bytes);
            if let Some(parsed) = find_start_line_in_complete_lines(&text) {
                if let Ok(surface_id) = fetch_health_surface_id(parsed.port) {
                    if promote_start_log(state_dir, &log_path, &surface_id).is_err() {
                        let _ = fs::remove_file(&log_path);
                    }
                } else {
                    let _ = fs::remove_file(&log_path);
                }
                std::thread::spawn(move || {
                    let _ = child.wait();
                });
                let code = crate::surfaces_cmd::request_open_code_at(
                    &parsed.name,
                    parsed.port,
                    &parsed.token,
                )
                .map_err(StartError::Internal)?;
                return Ok(StartedSurface {
                    name: parsed.name,
                    url: format!("http://127.0.0.1:{}/#open={code}", parsed.port),
                });
            }
        }

        match child.try_wait() {
            Ok(Some(status)) => {
                let bytes = match fs::read(&log_path) {
                    Ok(bytes) => bytes,
                    Err(e) => {
                        let _ = fs::remove_file(&log_path);
                        return Err(StartError::Internal(format!(
                            "surface in {} exited before starting ({status}); failed to read start log {}: {e}",
                            folder.display(),
                            log_path.display()
                        )));
                    }
                };
                let text = String::from_utf8_lossy(&bytes);
                let _ = fs::remove_file(&log_path);
                let tail = last_lines_redacted(&text, TAIL_LINES);
                let msg = if tail.trim().is_empty() {
                    format!(
                        "surface in {} exited before starting ({status})",
                        folder.display()
                    )
                } else {
                    format!(
                        "surface in {} exited before starting ({status}):\n{tail}",
                        folder.display()
                    )
                };
                return Err(StartError::Internal(msg));
            }
            Ok(None) => {}
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                let _ = fs::remove_file(&log_path);
                return Err(StartError::Internal(format!(
                    "failed to check started surface process: {e}"
                )));
            }
        }

        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            let _ = child.kill();
            let _ = child.wait();
            return Err(StartError::Internal(format!(
                "timed out after {} s waiting for surface in {} to start; log kept at {}",
                timeout.as_secs(),
                folder.display(),
                log_path.display()
            )));
        }
        std::thread::sleep(POLL_INTERVAL.min(remaining));
    }
}

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

    #[test]
    fn resolve_folder_checks_tilde_absolute_exists_and_is_dir() {
        let temp = tempfile::tempdir().unwrap();
        let home = temp.path().join("home");
        let sub = home.join("proj");
        fs::create_dir_all(&sub).unwrap();
        let file = temp.path().join("file.txt");
        fs::write(&file, "hi").unwrap();
        let missing = temp.path().join("nope");

        let resolved = resolve_start_folder_with_home("~/proj", Some(home.as_os_str())).unwrap();
        assert_eq!(resolved, sub);

        let err_no_home = resolve_start_folder_with_home("~/proj", None).unwrap_err();
        assert!(err_no_home.contains("~/proj"), "{err_no_home}");
        assert!(err_no_home.contains("HOME"), "{err_no_home}");

        let err_empty_home =
            resolve_start_folder_with_home("~/proj", Some(OsStr::new(""))).unwrap_err();
        assert!(err_empty_home.contains("HOME"), "{err_empty_home}");

        let err_rel = resolve_start_folder_with_home("relative/dir", None).unwrap_err();
        assert!(err_rel.contains("relative/dir"), "{err_rel}");
        assert!(err_rel.contains("absolute"), "{err_rel}");

        let err_missing =
            resolve_start_folder_with_home(&missing.to_string_lossy(), None).unwrap_err();
        assert!(
            err_missing.contains(&missing.display().to_string()),
            "{err_missing}"
        );
        assert!(err_missing.contains("does not exist"), "{err_missing}");
        assert!(!missing.exists());

        let err_file = resolve_start_folder_with_home(&file.to_string_lossy(), None).unwrap_err();
        assert!(err_file.contains(&file.display().to_string()), "{err_file}");
        assert!(err_file.contains("not a directory"), "{err_file}");
    }

    #[test]
    fn parse_and_redact_start_line() {
        let line = "blyte: surface demo at http://127.0.0.1:4321/#token=secret123\n";
        let parsed = find_start_line_in_complete_lines(line).unwrap();
        assert_eq!(parsed.name, "demo");
        assert_eq!(parsed.port, 4321);
        assert_eq!(parsed.token, "secret123");

        assert!(find_start_line_in_complete_lines(
            "blyte: surface demo at http://127.0.0.1:4321/#token=partial"
        )
        .is_none());

        let redacted = redact_tokens("http://127.0.0.1:4321/#token=secret123 done");
        assert!(!redacted.contains("secret123"), "{redacted}");
        assert!(redacted.contains("#token=<redacted>"), "{redacted}");
    }

    #[cfg(unix)]
    #[test]
    fn timeout_kills_child_and_keeps_log_file() {
        let temp = tempfile::tempdir().unwrap();
        let state = temp.path().join("state");
        let folder = temp.path().join("work");
        fs::create_dir_all(&folder).unwrap();

        let err = start_surface_with_exe(
            &folder,
            &state,
            Path::new("/bin/sleep"),
            &["30"],
            Duration::from_millis(150),
        )
        .unwrap_err();
        let StartError::Internal(msg) = err else {
            panic!("expected internal error, got {err:?}");
        };
        assert!(msg.contains("timed out"), "{msg}");
        let log_dir = state.join("surface-starts");
        let entries: Vec<_> = fs::read_dir(&log_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(entries.len(), 1);
        let log_path = entries[0].path();
        assert!(msg.contains(&log_path.display().to_string()), "{msg}");
        let dir_mode = fs::metadata(&log_dir).unwrap().permissions().mode() & 0o777;
        let file_mode = fs::metadata(&log_path).unwrap().permissions().mode() & 0o777;
        assert_eq!(dir_mode, 0o700);
        assert_eq!(file_mode, 0o600);
    }

    #[cfg(unix)]
    #[test]
    fn early_exit_reports_unreadable_start_log() {
        let temp = tempfile::tempdir().unwrap();
        let state = temp.path().join("state");
        let folder = temp.path().join("work");
        fs::create_dir_all(&folder).unwrap();
        let log_dir = state.join("surface-starts");
        let log_dir_str = log_dir.to_string_lossy().into_owned();

        let err = start_surface_with_exe(
            &folder,
            &state,
            Path::new("/bin/sh"),
            &["-c", "rm -f \"$1\"/*.log; exit 1", "sh", &log_dir_str],
            Duration::from_secs(5),
        )
        .unwrap_err();
        let StartError::Internal(msg) = err else {
            panic!("expected internal error, got {err:?}");
        };
        assert!(msg.contains("failed to read start log"), "{msg}");
        assert!(msg.contains(&log_dir_str), "{msg}");
    }

    #[cfg(unix)]
    #[test]
    fn early_exit_removes_start_log_file() {
        let temp = tempfile::tempdir().unwrap();
        let state = temp.path().join("state");
        let folder = temp.path().join("work");
        fs::create_dir_all(&folder).unwrap();

        let err = start_surface_with_exe(
            &folder,
            &state,
            Path::new("/bin/sh"),
            &["-c", "echo boom >&2; exit 1"],
            Duration::from_secs(5),
        )
        .unwrap_err();
        let StartError::Internal(msg) = err else {
            panic!("expected internal error, got {err:?}");
        };
        assert!(msg.contains("boom"), "{msg}");
        let log_dir = state.join("surface-starts");
        assert!(log_dir.is_dir());
        let remaining: Vec<_> = fs::read_dir(&log_dir)
            .unwrap()
            .map(|e| e.unwrap().path())
            .collect();
        assert!(remaining.is_empty(), "leftover log files: {remaining:?}");
    }
}