croft-software 0.2.182

VSCode-style TUI written in Rust
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
//! Repair the `PATH` a GUI launch inherits.
//!
//! A terminal launch hands croft the PATH the user's shell built: homebrew,
//! nix, cargo, uv, everything. A GUI launch does not. macOS launchd starts
//! Croft.app (Dock click, Spotlight, an opened document) with the bare
//! `/usr/bin:/bin:/usr/sbin:/sbin`, and Ghostty's `--initial-command` runs
//! croft under `bash --noprofile --norc`, so no rc file ever puts the missing
//! directories back. Every tool croft shells out to then becomes invisible:
//! `pdftoppm` disappears and PDF previews freeze on page 1, `pdfinfo`
//! disappears and the page count with it, and the same goes for git, ripgrep,
//! language servers and the pair-programming CLIs.
//!
//! The fix is to ask the user's login shell what the PATH actually is. This is
//! what VS Code and Zed both do for the same reason. But an interactive login
//! shell takes as long as the user's rc files do, often a second or more, and
//! croft starts in milliseconds with no exceptions (#1973), so startup never
//! waits for it. The answer is remembered in croft's cache directory instead:
//! a launch puts the remembered PATH back at once, before croft spawns
//! anything, and once the editor is up asks the shell again in the background
//! so the next launch sees whatever the rc files have added since. `croft install-launcher` and
//! `croft setup-ghostty`, which a user runs before their first GUI launch,
//! remember it up front. Only a launch that arrives with launchd's exact PATH
//! does any of this, so a terminal launch costs nothing.

use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

/// Exactly what launchd hands a GUI process. Any other PATH came from a
/// shell that already ran the user's configuration, so we leave it alone.
const LAUNCHD_DIRS: [&str; 4] = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];

/// How long the login shell gets to answer. A shell that hangs on its own rc
/// file must not leave a probe (and the process it runs in) hanging.
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);

/// Markers around the value so an interactive rc file's own chatter (banners,
/// version notices, `fastfetch`) can never be mistaken for the PATH.
const BEGIN: &str = "__CROFT_PATH_BEGIN__";
const END: &str = "__CROFT_PATH_END__";

/// Whether this PATH is a GUI launch's stripped inheritance rather than a
/// shell's. Empty or unset counts: it is no more usable than launchd's.
///
/// Directories inside an application bundle do not count either way. The app
/// that launched us puts its own there (Ghostty appends
/// `/Applications/Ghostty.app/Contents/MacOS`, iTerm2 its `utilities`), which
/// no user's shell would ever do, so their presence is not evidence that a
/// shell ran.
fn is_stripped(path: Option<&str>) -> bool {
    let Some(path) = path.map(str::trim).filter(|p| !p.is_empty()) else {
        return true;
    };
    path.split(':')
        .filter(|e| !e.is_empty())
        .filter(|e| !e.contains(".app/"))
        .all(|e| LAUNCHD_DIRS.contains(&e.trim_end_matches('/')))
}

/// The login shell's PATH ahead of what we already have, with duplicates
/// dropped. Keeping the inherited entries means the system directories
/// survive even if the user's shell drops them.
fn merge(current: Option<&str>, probed: &str) -> String {
    let mut out: Vec<&str> = Vec::new();
    for entry in probed
        .split(':')
        .chain(current.unwrap_or_default().split(':'))
        .filter(|e| !e.is_empty())
    {
        if !out.contains(&entry) {
            out.push(entry);
        }
    }
    out.join(":")
}

/// Ask `shell`, started under the `inherited` PATH, for its PATH. `-l -i` so both the login files (`.zprofile`,
/// `.bash_profile`) and the interactive ones (`.zshrc`) get a say, since
/// either may be where the user builds their PATH (csh/tcsh accept `-l` only
/// as the sole argument, so that family runs `-i` alone). The value is
/// printed by an inner `/bin/sh` reading the *environment*: fish expands its
/// own quoted `$PATH` list space-joined, while the exported variable is
/// colon-joined in every shell. stdin is closed so a shell that prompts gets
/// EOF instead of blocking, and the whole thing is bounded by `timeout`,
/// [`PROBE_TIMEOUT`] in croft itself. `inherited` is what a GUI launch hands
/// the shell, never a PATH already repaired from memory (see
/// [`probe_and_remember`]).
fn probe(shell: &str, inherited: Option<&str>, timeout: Duration) -> Option<String> {
    let mut cmd = probe_cmd(shell);
    match inherited {
        Some(path) => cmd.env("PATH", path),
        None => cmd.env_remove("PATH"),
    };
    run_probe(cmd, timeout)
}

/// The probe invocation for `shell`, before it is spawned. Split from
/// [`probe`] so a test can inject an environment (`HOME`) around it.
fn probe_cmd(shell: &str) -> Command {
    let mut cmd = Command::new(shell);
    let name = std::path::Path::new(shell)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();
    if name.ends_with("csh") {
        // csh/tcsh accept `-l` only as the sole argument, so the login-shell
        // marking goes the other way: a leading dash in argv[0], the same
        // convention login(1) uses. Without it tcsh reads `.cshrc` but never
        // `~/.login` - the conventional place a csh user builds `path` - and
        // the probe recovers nothing for the csh family.
        std::os::unix::process::CommandExt::arg0(&mut cmd, format!("-{name}"));
        cmd.arg("-i");
    } else {
        cmd.args(["-l", "-i"]);
    }
    cmd.arg("-c")
        .arg(format!(r#"/bin/sh -c 'printf "{BEGIN}%s{END}" "$PATH"'"#));
    cmd
}

/// Run a prepared probe command and return the PATH it printed, giving up
/// after `timeout`.
fn run_probe(mut cmd: Command, timeout: Duration) -> Option<String> {
    // Its own session, so the probe has no controlling terminal. `-l -i`
    // makes the shell interactive, and an interactive zsh takes the
    // terminal's foreground process group for job control; left in croft's
    // session it steals the TTY, and once it exits croft is a background
    // process on its own terminal — enabling raw mode then fails with EIO
    // and a Dock launch dies on arrival.
    unsafe {
        std::os::unix::process::CommandExt::pre_exec(&mut cmd, || {
            libc::setsid();
            Ok(())
        });
    }
    let mut child = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    let mut stdout = child.stdout.take()?;
    let (tx, rx) = std::sync::mpsc::channel();
    // Read until the END marker, not EOF: a backgrounded grandchild from an
    // rc file (`(brew update &)`, an agent start) inherits the pipe's write
    // end and holds EOF back long after the shell answered and exited.
    std::thread::spawn(move || {
        let mut buf = Vec::new();
        let mut chunk = [0u8; 4096];
        loop {
            match std::io::Read::read(&mut stdout, &mut chunk) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    buf.extend_from_slice(&chunk[..n]);
                    if String::from_utf8_lossy(&buf).contains(END) {
                        break;
                    }
                }
            }
        }
        let _ = tx.send(buf);
    });
    let out = rx.recv_timeout(timeout).ok();
    // Either it answered, or it is wedged and must not outlive the probe
    // holding a pipe open. The reap runs off-thread: a shell stuck in
    // uninterruptible sleep (rc file stat'ing a dead network mount) cannot
    // be killed, and a synchronous wait() on it would wedge startup after
    // all.
    let _ = child.kill();
    std::thread::spawn(move || {
        let _ = child.wait();
    });
    extract(&String::from_utf8_lossy(&out?))
}

/// Pull the PATH out from between the markers.
fn extract(out: &str) -> Option<String> {
    let (_, rest) = out.split_once(BEGIN)?;
    let (path, _) = rest.split_once(END)?;
    let path = path.trim();
    (!path.is_empty()).then(|| path.to_string())
}

/// The PATH to run under, or `None` to keep what we inherited. `known` is the
/// login shell's PATH as last remembered; it is only asked for when the
/// inherited PATH needs repairing.
fn repaired(current: Option<&str>, known: impl FnOnce() -> Option<String>) -> Option<String> {
    if !is_stripped(current) {
        return None;
    }
    let known = known()?;
    let merged = merge(current, &known);
    (merged != current.unwrap_or_default()).then_some(merged)
}

/// Where the login shell's PATH is remembered between launches. A cache: it
/// is rebuilt by the next probe if it goes.
fn memory_path() -> PathBuf {
    crate::paths::croft_cache_dir().join("login-path")
}

/// The PATH remembered in `file` for `shell`. A PATH another shell reported
/// does not count: switching shells must not run croft under the old one's.
fn recall(file: &Path, shell: &str) -> Option<String> {
    let text = std::fs::read_to_string(file).ok()?;
    let (who, path) = text.split_once('\n')?;
    let path = path.trim();
    (who == shell && !path.is_empty()).then(|| path.to_string())
}

/// Remember `path` as `shell`'s PATH in `file`. Written beside and renamed
/// over, so a launch reading it never sees half of one.
fn remember(file: &Path, shell: &str, path: &str) -> std::io::Result<()> {
    if recall(file, shell).as_deref() == Some(path) {
        return Ok(());
    }
    if let Some(dir) = file.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let tmp = file.with_extension(format!("tmp{}", std::process::id()));
    std::fs::write(&tmp, format!("{shell}\n{path}\n"))?;
    std::fs::rename(&tmp, file).inspect_err(|_| {
        let _ = std::fs::remove_file(&tmp);
    })
}

/// Ask `shell` for its PATH, starting it under `inherited` as a GUI launch
/// would, and remember the answer in `file` for the next launch. Nothing is
/// remembered when the shell does not answer. The shell must not inherit a
/// PATH already repaired from memory: whatever it remembered would come back
/// in its answer, and a directory taken out of an rc file would never leave.
/// The shell gets `timeout` to answer, as for [`probe`].
fn probe_and_remember(shell: &str, inherited: Option<&str>, file: &Path, timeout: Duration) {
    if let Some(path) = probe(shell, inherited, timeout) {
        let _ = remember(file, shell, &path);
    }
}

/// Ask the user's login shell for its PATH now and remember it, so the first
/// GUI launch already has it. For the setup commands a user runs from a
/// terminal before that launch; they may wait for the shell, startup never
/// does. The shell starts under launchd's PATH, not this terminal's, so it
/// answers exactly what it would for a GUI launch.
pub fn remember_login_path() {
    let launchd = LAUNCHD_DIRS.join(":");
    probe_and_remember(
        &login_shell(),
        Some(&launchd),
        &memory_path(),
        PROBE_TIMEOUT,
    );
}

/// The user's login shell. launchd sets `SHELL` from the user record for GUI
/// sessions; zsh is the macOS default when it does not.
fn login_shell() -> String {
    std::env::var("SHELL")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| String::from("/bin/zsh"))
}

/// The PATH a GUI launch inherited, kept by [`repair`] for
/// [`refresh_in_background`]. Never set on a terminal launch.
static INHERITED: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

/// Put the user's real PATH back when croft was started by the GUI, without
/// waiting for their shell. Call once at startup, before anything spawns a
/// child or a thread.
pub fn repair() {
    let current = std::env::var("PATH").ok();
    if !is_stripped(current.as_deref()) {
        return;
    }
    let shell = login_shell();
    let file = memory_path();
    if let Some(fixed) = repaired(current.as_deref(), || recall(&file, &shell)) {
        // SAFETY: `set_var` is only unsafe because another thread may be
        // reading the environment concurrently. This runs at the top of
        // `Cli::run`, before croft starts the tokio runtime, any watcher, or
        // any child process.
        unsafe { std::env::set_var("PATH", OsStr::new(&fixed)) };
    }
    let _ = INHERITED.set(current);
}

/// Ask the login shell again, off the startup path, and remember its answer
/// for the next GUI launch. A no-op unless [`repair`] saw a GUI launch, and
/// it asks once per process however often it is called. The editor calls it
/// once it is up, and nothing else does: a short-lived command (`croft
/// open-link` from the URL handler) would exit with the probe's login shell
/// still running, and one wedged in its rc files would be left behind, while
/// an editor session normally runs past the probe's timeout, which kills such
/// a shell.
pub fn refresh_in_background() {
    static ASKED: std::sync::Once = std::sync::Once::new();
    let Some(inherited) = INHERITED.get() else {
        return;
    };
    ASKED.call_once(|| {
        spawn_refresh(
            login_shell(),
            inherited.clone(),
            memory_path(),
            PROBE_TIMEOUT,
        );
    });
}

/// Ask `shell` again on a thread of its own, under the `inherited` PATH, and
/// remember its answer in `file`, for the next launch; `timeout` as for
/// [`probe`].
fn spawn_refresh(
    shell: String,
    inherited: Option<String>,
    file: PathBuf,
    timeout: Duration,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || probe_and_remember(&shell, inherited.as_deref(), &file, timeout))
}

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

    /// The probe's deadline stretched for the load the suite puts on this
    /// machine (#307, #2221): a healthy shell can take longer than
    /// [`PROBE_TIMEOUT`] to start while thousands of tests run beside it.
    fn loaded_timeout() -> Duration {
        crate::test_budget::spawn_budget(PROBE_TIMEOUT)
    }

    /// Write `script` to `path` as a stand-in login shell and make it ready
    /// to run (#2221). A test forking while the script was open for writing
    /// holds it "Text file busy" until that child execs, and a probe takes a
    /// failed spawn for a shell with no answer. So the stand-in runs once
    /// here, waiting that out, with `CROFT_STUB_WARMUP` set for a script that
    /// would otherwise do its slow part. Returns the path as the shell name.
    fn stand_in_shell(path: &Path, script: &str) -> String {
        std::fs::write(path, script).unwrap();
        let mut perm = std::fs::metadata(path).unwrap().permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
        std::fs::set_permissions(path, perm).unwrap();
        crate::review_ops::output_retrying_busy(Command::new(path).env("CROFT_STUB_WARMUP", "1"))
            .expect("the stand-in shell runs");
        path.display().to_string()
    }

    #[test]
    fn launchd_path_reads_as_stripped() {
        assert!(is_stripped(Some("/usr/bin:/bin:/usr/sbin:/sbin")));
        // Order and trailing slashes are launchd's business, not a signal.
        assert!(is_stripped(Some("/bin:/usr/bin:/sbin/:/usr/sbin")));
        assert!(is_stripped(Some("")));
        assert!(is_stripped(None));
    }

    /// The PATH a Dock click actually produces, read off a live Croft.app
    /// launch: launchd's four directories plus the bundle dir Ghostty appends
    /// for itself. An app putting its own bundle on PATH is not a shell having
    /// run, so this still needs repairing.
    #[test]
    fn a_dock_launch_through_ghostty_reads_as_stripped() {
        assert!(is_stripped(Some(
            "/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Ghostty.app/Contents/MacOS"
        )));
        assert!(is_stripped(Some(
            "/Applications/iTerm.app/Contents/Resources/utilities:/usr/bin:/bin"
        )));
    }

    #[test]
    fn a_shell_built_path_is_left_alone() {
        assert!(!is_stripped(Some(
            "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
        )));
        assert!(!is_stripped(Some("/usr/bin:/bin:/Users/v/.cargo/bin")));
    }

    #[test]
    fn merge_puts_the_login_shell_first_and_keeps_the_system_dirs() {
        let merged = merge(
            Some("/usr/bin:/bin:/usr/sbin:/sbin"),
            "/opt/homebrew/bin:/usr/bin:/bin",
        );
        assert_eq!(merged, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
    }

    #[test]
    fn merge_drops_duplicates() {
        let merged = merge(Some("/usr/bin:/usr/bin"), "/usr/bin:/opt/homebrew/bin");
        assert_eq!(merged, "/usr/bin:/opt/homebrew/bin");
    }

    #[test]
    fn extract_ignores_rc_file_chatter() {
        let out = format!("Welcome to zsh!\nnode v22\n{BEGIN}/opt/homebrew/bin:/usr/bin{END}");
        assert_eq!(extract(&out).as_deref(), Some("/opt/homebrew/bin:/usr/bin"));
    }

    #[test]
    fn extract_returns_none_without_both_markers() {
        assert!(extract("/opt/homebrew/bin").is_none());
        assert!(extract(&format!("{BEGIN}/opt/homebrew/bin")).is_none());
        assert!(extract(&format!("{BEGIN}{END}")).is_none());
    }

    /// The whole point: a GUI launch gets the shell's directories back, so
    /// `pdftoppm` and friends are findable again.
    #[test]
    fn a_gui_launch_gets_the_shell_path_back() {
        let fixed = repaired(Some("/usr/bin:/bin:/usr/sbin:/sbin"), || {
            Some(String::from("/opt/homebrew/bin:/usr/bin:/bin"))
        });
        assert_eq!(
            fixed.as_deref(),
            Some("/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin")
        );
    }

    #[test]
    fn a_terminal_launch_never_probes_or_changes_anything() {
        let fixed = repaired(Some("/opt/homebrew/bin:/usr/bin"), || {
            panic!("a shell-built PATH must not be looked up")
        });
        assert!(fixed.is_none());
    }

    #[test]
    fn a_remembered_path_comes_back_for_the_same_shell() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("cache").join("login-path");
        remember(&file, "/bin/zsh", "/opt/homebrew/bin:/usr/bin").unwrap();
        assert_eq!(
            recall(&file, "/bin/zsh").as_deref(),
            Some("/opt/homebrew/bin:/usr/bin")
        );
        remember(&file, "/bin/zsh", "/opt/x:/usr/bin").unwrap();
        assert_eq!(
            recall(&file, "/bin/zsh").as_deref(),
            Some("/opt/x:/usr/bin")
        );
    }

    /// A user who switched their login shell must not run croft under the
    /// PATH the old one built.
    #[test]
    fn a_path_another_shell_reported_is_not_used() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("login-path");
        remember(&file, "/bin/zsh", "/opt/homebrew/bin:/usr/bin").unwrap();
        assert!(recall(&file, "/opt/homebrew/bin/fish").is_none());
    }

    #[test]
    fn a_missing_or_garbled_memory_is_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("login-path");
        assert!(recall(&file, "/bin/zsh").is_none());
        std::fs::write(&file, "/bin/zsh").unwrap();
        assert!(recall(&file, "/bin/zsh").is_none());
        std::fs::write(&file, "/bin/zsh\n\n").unwrap();
        assert!(recall(&file, "/bin/zsh").is_none());
    }

    /// #1973: a GUI launch puts the PATH back from memory, at once, however
    /// long the login shell takes; the slow shell's answer is for the next
    /// launch, and lands there.
    #[test]
    fn a_gui_launch_never_waits_for_the_login_shell() {
        let dir = tempfile::tempdir().unwrap();
        let shell = stand_in_shell(
            &dir.path().join("slow-shell"),
            &format!(
                "#!/bin/sh\n[ -n \"$CROFT_STUB_WARMUP\" ] && exit 0\nsleep 1\n\
                 printf '{BEGIN}/new/tools/bin:/usr/bin{END}'\n"
            ),
        );
        let file = dir.path().join("login-path");
        remember(&file, &shell, "/old/tools/bin:/usr/bin").unwrap();
        let dock = "/usr/bin:/bin:/usr/sbin:/sbin";
        let start = std::time::Instant::now();
        let fixed = repaired(Some(dock), || recall(&file, &shell));
        let refresh = spawn_refresh(
            shell.clone(),
            Some(dock.into()),
            file.clone(),
            loaded_timeout(),
        );
        assert!(
            start.elapsed() < Duration::from_millis(500),
            "startup waited {:?} for the login shell",
            start.elapsed()
        );
        assert_eq!(
            fixed.as_deref(),
            Some("/old/tools/bin:/usr/bin:/bin:/usr/sbin:/sbin")
        );
        refresh.join().unwrap();
        assert_eq!(
            recall(&file, &shell).as_deref(),
            Some("/new/tools/bin:/usr/bin")
        );
    }

    /// The refresh asks the shell under the PATH the launch inherited, not
    /// the one repaired from memory: otherwise a directory once remembered
    /// comes back in every answer, and taking it out of an rc file never
    /// takes it off croft's PATH.
    #[test]
    fn a_directory_taken_out_of_the_rc_files_leaves_the_memory() {
        let dir = tempfile::tempdir().unwrap();
        let shell = stand_in_shell(
            &dir.path().join("stub-shell"),
            &format!("#!/bin/sh\nprintf '{BEGIN}/now/bin:%s{END}' \"$PATH\"\n"),
        );
        let file = dir.path().join("login-path");
        remember(&file, &shell, "/gone/bin:/usr/bin:/bin").unwrap();
        probe_and_remember(&shell, Some("/usr/bin:/bin"), &file, loaded_timeout());
        assert_eq!(
            recall(&file, &shell).as_deref(),
            Some("/now/bin:/usr/bin:/bin")
        );
    }

    /// The very first GUI launch, before anything was remembered, starts
    /// under the inherited PATH rather than waiting for the shell.
    #[test]
    fn a_first_gui_launch_starts_under_the_inherited_path() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("login-path");
        assert!(repaired(Some("/usr/bin:/bin"), || recall(&file, "/bin/zsh")).is_none());
    }

    #[test]
    fn a_failed_probe_keeps_the_inherited_path() {
        assert!(repaired(Some("/usr/bin:/bin"), || None).is_none());
    }

    #[test]
    fn a_probe_that_adds_nothing_changes_nothing() {
        assert!(
            repaired(Some("/usr/bin:/bin:/usr/sbin:/sbin"), || Some(
                String::from("/usr/bin:/bin:/usr/sbin:/sbin")
            ))
            .is_none()
        );
    }

    /// End to end against a real shell: the probe must actually come back with
    /// a PATH, otherwise the markers or the flags are wrong.
    #[test]
    fn probing_a_real_shell_returns_a_usable_path() {
        let shell = if std::path::Path::new("/bin/zsh").exists() {
            "/bin/zsh"
        } else {
            "/bin/sh"
        };
        // The production probe caps a hanging shell at PROBE_TIMEOUT so croft's
        // startup cannot hang; under suite load a healthy shell legitimately
        // exceeds it, so the TEST scales that same deadline (#307) instead of
        // asserting production's startup budget is generous enough for CI.
        let path = run_probe(probe_cmd(shell), loaded_timeout())
            .expect("the login shell must report a PATH");
        assert!(path.contains("/bin"), "got {path:?}");
    }

    /// The whole chain, end to end through a real process spawn: the PATH a
    /// Dock click produces must come back with the login shell's own
    /// directories merged in front, or croft can see nothing the user
    /// installed (`pdftoppm`, `git`, `rg`, the language servers) when
    /// started from Croft.app. A stub login shell stands in for the user's
    /// (the suite must not depend on, or execute, a developer's rc files),
    /// but a strict one: it refuses any argv other than the probe's real
    /// `-l -i -c <script>` shape, contributes a directory the way a login
    /// shell does (into the exported environment), and runs the probe
    /// script through a real `/bin/sh` so the nested quoting is exercised.
    #[test]
    fn a_dock_launch_ends_up_seeing_the_users_own_directories() {
        let dir = tempfile::tempdir().unwrap();
        let shell = stand_in_shell(
            &dir.path().join("stub-shell"),
            "#!/bin/sh\n\
             [ \"$1\" = -l ] || exit 64\n\
             [ \"$2\" = -i ] || exit 64\n\
             [ \"$3\" = -c ] || exit 64\n\
             [ $# -eq 4 ] || exit 64\n\
             PATH=\"/stub/tools/bin:$PATH\"; export PATH\n\
             exec /bin/sh -c \"$4\"\n",
        );
        let dock = "/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Ghostty.app/Contents/MacOS";
        // One launch asks the shell and remembers; the next one runs under it.
        let file = dir.path().join("login-path");
        probe_and_remember(&shell, Some(dock), &file, loaded_timeout());
        let fixed = repaired(Some(dock), || recall(&file, &shell))
            .expect("a Dock launch must have its PATH repaired");
        assert!(
            fixed.starts_with("/stub/tools/bin:"),
            "the shell's directories must lead, got {fixed:?}"
        );
        // And nothing we started with is lost on the way.
        for entry in dock.split(':') {
            assert!(fixed.split(':').any(|e| e == entry), "{entry} dropped");
        }
    }

    /// An rc file that backgrounds a helper (`(brew update &)`, an agent
    /// start) leaves the pipe's write end open in the grandchild after the
    /// shell itself exits. The probe must return the moment the END marker
    /// arrives instead of waiting for an EOF that only comes when the
    /// grandchild eventually dies.
    #[test]
    fn a_backgrounded_grandchild_does_not_stall_the_probe() {
        let mut cmd = Command::new("/bin/sh");
        cmd.args([
            "-c",
            &format!("printf '{BEGIN}/opt/x:/usr/bin{END}'; sleep 5 &"),
        ]);
        let start = std::time::Instant::now();
        let out = run_probe(cmd, Duration::from_millis(1500));
        assert_eq!(out.as_deref(), Some("/opt/x:/usr/bin"));
        assert!(
            start.elapsed() < Duration::from_millis(1200),
            "the probe waited {:?} on a grandchild's pipe",
            start.elapsed()
        );
    }

    /// tcsh rejects `-l` combined with any other flag (`-l` must be the sole
    /// argument), and fish expands a quoted `$PATH` space-joined. The probe
    /// must still get a colon-joined PATH out of both families.
    #[test]
    fn a_csh_family_login_shell_still_answers() {
        if !std::path::Path::new("/bin/tcsh").exists() {
            eprintln!("skipping: tcsh not installed");
            return;
        }
        let path = probe("/bin/tcsh", Some("/usr/bin:/bin"), loaded_timeout())
            .expect("tcsh must report a PATH");
        assert!(path.contains("/bin"), "got {path:?}");
    }

    /// `~/.login` is the conventional place a csh user builds `path` (it is
    /// the login-only file), and tcsh refuses `-l` next to any other flag -
    /// so the probe must mark itself a login shell the way login(1) does,
    /// with a leading dash in argv[0]. Runs the real tcsh against a stub
    /// HOME: if `.login` is never sourced, the probe recovered nothing and
    /// the whole module is dead for the csh family.
    #[test]
    fn a_csh_family_probe_reads_the_login_file() {
        if !std::path::Path::new("/bin/tcsh").exists() {
            eprintln!("skipping: tcsh not installed");
            return;
        }
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".login"),
            "setenv PATH /from/login:$PATH\n",
        )
        .unwrap();
        let mut cmd = probe_cmd("/bin/tcsh");
        cmd.env("HOME", home.path());
        let path = run_probe(cmd, loaded_timeout()).expect("tcsh must answer");
        assert!(
            path.split(':').any(|e| e == "/from/login"),
            "~/.login was not sourced; the csh user's PATH is lost: {path:?}"
        );
    }

    /// The probe must run in its own session, with no controlling terminal.
    /// `-l -i` makes the user's shell interactive, and an interactive zsh
    /// takes the terminal's foreground process group for job control. Left
    /// in croft's session it steals the TTY; when it exits, croft is a
    /// background process on its own terminal and enabling raw mode fails
    /// with EIO — a Dock launch "crashes" on arrival. A session of its own
    /// makes the theft impossible.
    #[test]
    fn the_probe_cannot_touch_crofts_terminal_session() {
        // macOS ps has no session-id keyword (`sess` prints 0), so the
        // stub reports its sid via python (resolved through PATH — the
        // absolute /usr/bin/python3 only exists with the Xcode CLT).
        if Command::new("python3").arg("--version").output().is_err() {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let shell = stand_in_shell(
            &dir.path().join("stub-shell"),
            &format!(
                "#!/bin/sh\n\
                 exec python3 -c 'import os; \
                 print(\"{BEGIN}%d{END}\" % os.getsid(0))'\n"
            ),
        );
        let sid = run_probe(probe_cmd(&shell), loaded_timeout())
            .expect("the stub must report its session id");
        let own = unsafe { libc::getsid(0) };
        assert_ne!(
            sid.trim().parse::<i64>().expect("a numeric session id"),
            i64::from(own),
            "the probe shell shares croft's terminal session"
        );
    }

    /// A shell wedged on its own rc file must not wedge croft.
    #[test]
    fn a_hanging_shell_gives_up_instead_of_blocking_startup() {
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "sleep 600"]);
        let start = std::time::Instant::now();
        let out = run_probe(cmd, Duration::from_millis(300));
        assert!(out.is_none(), "a wedged shell must not report a PATH");
        assert!(
            start.elapsed() < Duration::from_secs(5),
            "startup waited {:?} on a hung shell",
            start.elapsed()
        );
    }

    /// And the timeout must not be so eager that a slow rc file loses.
    #[test]
    fn a_shell_that_answers_within_the_timeout_is_read() {
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", &format!("printf '{BEGIN}/opt/x:/usr/bin{END}'")]);
        assert_eq!(
            run_probe(cmd, loaded_timeout()).as_deref(),
            Some("/opt/x:/usr/bin")
        );
    }
}