Skip to main content

rinne_workers/transport/
external_terminal.rs

1//! External terminal transport — open a **real** system Terminal window and run
2//! the harness there so the user sees the actual product UI (Grok Build, Claude
3//! Code, Codex, …).
4//!
5//! # Why earlier attempts failed
6//!
7//! 1. **`script(1)`** nested a PTY → mouse-protocol garbage (`35;6M…`).
8//! 2. **`tee`** stole the TTY → plain JSON dumps, no product UI.
9//! 3. **`kill -9` on the process group** aborted the TUI without disabling mouse
10//!    tracking → Terminal kept emitting CSI mouse reports as text after death.
11//! 4. **Banners + non-`exec` mess** before the TUI fought alt-screen rendering.
12//!
13//! # Correct interactive path
14//!
15//! - Launch a minimal launcher that **resets the TTY**, then runs the harness
16//!   as the foreground job on the real Terminal TTY (no script, no tee).
17//! - Deliverable is a **result file** the agent writes (Rinne polls it).
18//! - On completion / cancel: **SIGTERM first** so the launcher EXIT trap can
19//!   reset mouse tracking + alt-screen; SIGKILL only as a last resort.
20//! - Capture (plain single-turn) mode still uses `tee` when the user opts out
21//!   of the product UI.
22
23use std::io::{Read, Seek, SeekFrom};
24use std::path::Path;
25use std::process::Command as StdCommand;
26use std::time::{Duration, Instant};
27
28use tokio::time::sleep;
29use tokio_util::sync::CancellationToken;
30
31use rinne_core::worker::{emit, EventSink, ExecStatus, WorkerEvent};
32use rinne_core::{Result, RinneError};
33
34use super::subprocess::{LineMapper, SubprocessOutput, SubprocessSpec};
35
36const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
37/// Prefix the launcher writes its own status lines with, so they can be told
38/// apart from harness output in the shared log (see `is_terminal_noise`).
39const LAUNCHER_MARKER: &str = "rinne-launcher:";
40const POLL: Duration = Duration::from_millis(100);
41/// How long a result file must stay the same size before we accept it.
42const RESULT_STABLE: Duration = Duration::from_millis(1200);
43/// After SIGTERM, wait this long for a clean EXIT trap before SIGKILL.
44const TERM_GRACE: Duration = Duration::from_secs(4);
45/// How often the launcher's watchdog checks that Rinne is still alive. Bounds
46/// how long a harness can outlive a hard-killed Rinne.
47const WATCHDOG_POLL_SECS: u64 = 2;
48
49/// How the launcher should treat the child process.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum TerminalMode {
52    /// Single-turn / headless flags: tee stdout so Rinne can parse. No product UI.
53    Capture,
54    /// Full interactive product UI on a real TTY. Result via `spec.result_file`.
55    Interactive,
56}
57
58/// Run `spec` inside a newly opened system terminal window (cwd = workspace).
59pub async fn run(
60    spec: SubprocessSpec,
61    events: &EventSink,
62    cancel: &CancellationToken,
63    mapper: LineMapper,
64) -> Result<SubprocessOutput> {
65    let mode = if looks_like_single_turn(&spec) && spec.result_file.is_none() {
66        TerminalMode::Capture
67    } else {
68        TerminalMode::Interactive
69    };
70    run_with_mode(spec, events, cancel, mapper, mode).await
71}
72
73/// Like [`run`], but forces capture vs interactive.
74pub async fn run_with_mode(
75    spec: SubprocessSpec,
76    events: &EventSink,
77    cancel: &CancellationToken,
78    mapper: LineMapper,
79    mode: TerminalMode,
80) -> Result<SubprocessOutput> {
81    let started = Instant::now();
82    let suffix = unique_suffix();
83    // Unique title tag so we can always find/close THIS window even if tty
84    // matching or Automation permissions fail on the first try.
85    let stage_tag = format!("rinne-stage-{}-{}", std::process::id(), suffix);
86    let scratch = std::env::temp_dir().join(&stage_tag);
87    std::fs::create_dir_all(&scratch)
88        .map_err(|e| RinneError::Worker(format!("external terminal scratch dir: {e}")))?;
89
90    let log_path = scratch.join("harness.log");
91    let exit_path = scratch.join("exit.code");
92    let pid_path = scratch.join("wrapper.pid");
93    let tty_path = scratch.join("tty.name");
94    let tag_path = scratch.join("stage.tag");
95    let win_path = scratch.join("window.id");
96    // macOS: `.command` is a recognized executable shell script type.
97    let script_path = scratch.join("run-harness.command");
98
99    std::fs::write(&log_path, b"").ok();
100    let _ = std::fs::write(&tag_path, &stage_tag);
101    let _ = std::fs::remove_file(&exit_path);
102
103    write_launcher(
104        &script_path,
105        &spec,
106        &log_path,
107        &exit_path,
108        &pid_path,
109        &tty_path,
110        &stage_tag,
111        mode,
112    )?;
113
114    emit(
115        events,
116        WorkerEvent::Message(match mode {
117            TerminalMode::Capture => "opening single-turn harness in system Terminal…".into(),
118            TerminalMode::Interactive => "opening harness product UI in system Terminal…".into(),
119        }),
120    );
121
122    open_system_terminal(&script_path, &spec.workspace, &stage_tag, &win_path)?;
123
124    let deadline = spec
125        .timeout
126        .map(|d| Instant::now() + d)
127        .unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
128
129    wait_for_file(&pid_path, cancel, deadline).await?;
130
131    let mut log_file = std::fs::File::open(&log_path).ok();
132    let mut log_pos: u64 = 0;
133    let mut captured = String::new();
134    let mut truncated = false;
135    let mut line_buf = String::new();
136    let mut terminal_status: Option<ExecStatus> = None;
137    let mut got_result_file = false;
138    let mut last_result_size: u64 = 0;
139    let mut result_stable_since: Option<Instant> = None;
140    // How many result-file lines already streamed into Stage.
141    let mut stage_lines_emitted: usize = 0;
142
143    loop {
144        if cancel.is_cancelled() {
145            soft_stop(&pid_path, &exit_path).await;
146            ensure_stage_window_closed(&tty_path, &tag_path, &win_path).await;
147            terminal_status = Some(ExecStatus::Cancelled);
148            break;
149        }
150        if Instant::now() >= deadline {
151            soft_stop(&pid_path, &exit_path).await;
152            ensure_stage_window_closed(&tty_path, &tag_path, &win_path).await;
153            terminal_status = Some(ExecStatus::TimedOut);
154            break;
155        }
156
157        // ── Result-file: stream partial output into Stage as it grows ─────
158        if let Some(ref rf) = spec.result_file {
159            if let Ok(partial) = std::fs::read_to_string(rf) {
160                if !partial.is_empty() {
161                    stream_result_to_stage(events, &partial, &mut stage_lines_emitted);
162                }
163            }
164            if let Some(text) = stable_result(rf, &mut last_result_size, &mut result_stable_since) {
165                captured = text;
166                got_result_file = true;
167                // Finish streaming any remaining lines into Stage.
168                stream_result_to_stage(events, &captured, &mut stage_lines_emitted);
169                emit(
170                    events,
171                    WorkerEvent::Message("✓ deliverable ready — closing Terminal".into()),
172                );
173                // SIGTERM → launcher EXIT trap resets TTY + closes the window.
174                soft_stop(&pid_path, &exit_path).await;
175                ensure_stage_window_closed(&tty_path, &tag_path, &win_path).await;
176                terminal_status = Some(ExecStatus::Success);
177                break;
178            }
179        }
180
181        // ── Optional log tail (capture mode) ──────────────────────────────
182        if let Some(ref mut lf) = log_file {
183            if lf.seek(SeekFrom::Start(log_pos)).is_ok() {
184                let mut buf = Vec::new();
185                if lf.read_to_end(&mut buf).is_ok() && !buf.is_empty() {
186                    log_pos += buf.len() as u64;
187                    let chunk = String::from_utf8_lossy(&buf);
188                    for ch in chunk.chars() {
189                        if ch == '\n' {
190                            flush_line(
191                                &mut line_buf,
192                                &mut captured,
193                                &mut truncated,
194                                mapper,
195                                events,
196                            );
197                        } else if ch != '\r' {
198                            line_buf.push(ch);
199                        }
200                    }
201                }
202            }
203        }
204
205        if exit_path.exists() {
206            if !line_buf.is_empty() {
207                flush_line(&mut line_buf, &mut captured, &mut truncated, mapper, events);
208            }
209            if let Some(ref rf) = spec.result_file {
210                if let Ok(text) = std::fs::read_to_string(rf) {
211                    let text = text.trim().to_string();
212                    if !text.is_empty() {
213                        captured = text;
214                        got_result_file = true;
215                        stream_result_to_stage(events, &captured, &mut stage_lines_emitted);
216                    }
217                }
218            }
219            ensure_stage_window_closed(&tty_path, &tag_path, &win_path).await;
220            break;
221        }
222
223        sleep(POLL).await;
224    }
225
226    // Drain remaining log (capture mode only — result-file path already streamed).
227    if !got_result_file {
228        if let Ok(meta) = std::fs::metadata(&log_path) {
229            if meta.len() > log_pos {
230                if let Ok(mut f) = std::fs::File::open(&log_path) {
231                    let _ = f.seek(SeekFrom::Start(log_pos));
232                    let mut rest = String::new();
233                    let _ = f.read_to_string(&mut rest);
234                    for ch in rest.chars() {
235                        if ch == '\n' {
236                            flush_line(
237                                &mut line_buf,
238                                &mut captured,
239                                &mut truncated,
240                                mapper,
241                                events,
242                            );
243                        } else if ch != '\r' {
244                            line_buf.push(ch);
245                        }
246                    }
247                    if !line_buf.is_empty() {
248                        flush_line(&mut line_buf, &mut captured, &mut truncated, mapper, events);
249                    }
250                }
251            }
252        }
253        if let Some(ref rf) = spec.result_file {
254            if let Ok(text) = std::fs::read_to_string(rf) {
255                let text = text.trim().to_string();
256                if !text.is_empty() {
257                    captured = text;
258                    got_result_file = true;
259                    stream_result_to_stage(events, &captured, &mut stage_lines_emitted);
260                }
261            }
262        }
263    }
264
265    // Ensure Stage has the final body even if capture mode only filled `captured`.
266    if got_result_file || !captured.trim().is_empty() {
267        stream_result_to_stage(events, &captured, &mut stage_lines_emitted);
268    }
269
270    let exit_code = std::fs::read_to_string(&exit_path)
271        .ok()
272        .and_then(|s| s.trim().parse::<i32>().ok());
273
274    let status = terminal_status.unwrap_or_else(|| {
275        resolve_status(
276            spec.result_file.is_some(),
277            got_result_file,
278            captured.trim().is_empty(),
279            exit_code,
280            cancel.is_cancelled(),
281        )
282    });
283
284    // Final guarantee: multi-strategy close with retries (never leave orphans).
285    ensure_stage_window_closed(&tty_path, &tag_path, &win_path).await;
286
287    if matches!(status, ExecStatus::Success) {
288        let _ = std::fs::remove_dir_all(&scratch);
289    } else {
290        emit(
291            events,
292            WorkerEvent::Message(format!(
293                "session artifacts kept at {} (exit {:?})",
294                scratch.display(),
295                exit_code
296            )),
297        );
298    }
299
300    emit(events, WorkerEvent::Done);
301    Ok(SubprocessOutput {
302        stdout: captured,
303        stderr: String::new(),
304        exit_code: if got_result_file { Some(0) } else { exit_code },
305        status,
306        wall_ms: started.elapsed().as_millis() as u64,
307    })
308}
309
310/// Push new lines from the result file into Stage (idempotent via `emitted` count).
311fn stream_result_to_stage(events: &EventSink, text: &str, emitted: &mut usize) {
312    const MAX_STAGE_LINES: usize = 250;
313    let lines: Vec<&str> = text.lines().collect();
314    if lines.is_empty() {
315        return;
316    }
317    if *emitted == 0 {
318        emit(events, WorkerEvent::Message("── harness output ──".into()));
319    }
320    while *emitted < lines.len() && *emitted < MAX_STAGE_LINES {
321        let line = lines[*emitted];
322        *emitted += 1;
323        if line.is_empty() || is_terminal_noise(line) {
324            continue;
325        }
326        // Soft-cap very long single lines for the Stage pane.
327        let shown = if line.chars().count() > 400 {
328            let take: String = line.chars().take(400).collect();
329            format!("{take}…")
330        } else {
331            line.to_string()
332        };
333        emit(events, WorkerEvent::Message(shown));
334    }
335    if lines.len() > MAX_STAGE_LINES && *emitted == MAX_STAGE_LINES {
336        emit(
337            events,
338            WorkerEvent::Message(format!(
339                "… ({} more lines truncated in Stage)",
340                lines.len() - MAX_STAGE_LINES
341            )),
342        );
343        *emitted = lines.len(); // don't re-emit the truncation notice
344    }
345}
346
347/// Accept result file only when non-empty and size-stable.
348fn stable_result(
349    path: &Path,
350    last_size: &mut u64,
351    stable_since: &mut Option<Instant>,
352) -> Option<String> {
353    let meta = std::fs::metadata(path).ok()?;
354    let len = meta.len();
355    if len == 0 {
356        return None;
357    }
358    if len != *last_size {
359        *last_size = len;
360        *stable_since = Some(Instant::now());
361        return None;
362    }
363    let since = stable_since.get_or_insert_with(Instant::now);
364    if since.elapsed() < RESULT_STABLE {
365        return None;
366    }
367    let text = std::fs::read_to_string(path).ok()?;
368    let text = text.trim().to_string();
369    if text.is_empty() {
370        return None;
371    }
372    // Reject mouse-noise-only "results".
373    if is_terminal_noise(&text) {
374        return None;
375    }
376    Some(text)
377}
378
379fn looks_like_single_turn(spec: &SubprocessSpec) -> bool {
380    spec.args.iter().any(|a| {
381        matches!(
382            a.as_str(),
383            "-p" | "--print" | "--single" | "--output-format" | "--prompt-file" | "exec" | "run"
384        ) || a.starts_with("--output-format=")
385            || a.starts_with("--prompt-file=")
386    })
387}
388
389/// Write the launcher script.
390///
391/// Interactive mode deliberately has **no banner** before the harness — banners
392/// fight alt-screen TUIs. Capture mode may print a short header.
393fn write_launcher(
394    script_path: &Path,
395    spec: &SubprocessSpec,
396    log_path: &Path,
397    exit_path: &Path,
398    pid_path: &Path,
399    tty_path: &Path,
400    stage_tag: &str,
401    mode: TerminalMode,
402) -> Result<()> {
403    let mut script = String::new();
404    script.push_str("#!/bin/bash\n");
405    // No `set -e` — we need the EXIT trap even if the harness fails.
406    script.push_str("set -u\n");
407    // Do NOT use `set -m` — job-control process groups make SIGTERM/SIGKILL
408    // racey with Terminal.app and leave mouse tracking enabled on hard kill.
409
410    script.push_str(&format!(
411        "cd {} || exit 90\n",
412        sh_quote(&spec.workspace.display().to_string())
413    ));
414
415    // Clean terminal capabilities for modern TUIs.
416    script.push_str("export TERM=\"${TERM:-xterm-256color}\"\n");
417    script.push_str("export COLORTERM=\"${COLORTERM:-truecolor}\"\n");
418    script.push_str("export DISABLE_AUTO_UPDATE=true\n");
419    script.push_str(&format!("export RINNE_STAGE_TAG={}\n", sh_quote(stage_tag)));
420
421    for (k, v) in &spec.env {
422        script.push_str(&format!("export {}={}\n", k, sh_quote(v)));
423    }
424
425    let pid_q = sh_quote(&pid_path.display().to_string());
426    let exit_q = sh_quote(&exit_path.display().to_string());
427    let log_q = sh_quote(&log_path.display().to_string());
428    let tty_q = sh_quote(&tty_path.display().to_string());
429    let tag_q = sh_quote(stage_tag);
430    // Where the watchdog parks its current `sleep` pid so `on_exit` can reap it.
431    let sleep_pid_q = sh_quote(
432        &pid_path
433            .with_file_name("watchdog-sleep.pid")
434            .display()
435            .to_string(),
436    );
437
438    // ── TTY reset (start + end) — critical for mouse-tracking cleanup ─────
439    script.push_str("reset_tty() {\n");
440    script.push_str("  if [ -w /dev/tty ]; then\n");
441    script.push_str("    printf '\\033[?1003l\\033[?1002l\\033[?1000l\\033[?1006l\\033[?1015l\\033[?1005l' >/dev/tty 2>/dev/null || true\n");
442    script.push_str("    printf '\\033[?25h\\033[?1049l\\033[0m' >/dev/tty 2>/dev/null || true\n");
443    script.push_str("  fi\n");
444    script.push_str("}\n");
445
446    // Mark this window with a unique title so Rinne can always find it.
447    script.push_str("set_stage_title() {\n");
448    script.push_str(&format!("  TAG={tag_q}\n"));
449    script.push_str("  # OSC 0/2: icon + window title (Terminal.app / iTerm honor these).\n");
450    script.push_str("  if [ -w /dev/tty ]; then\n");
451    script.push_str("    printf '\\033]0;%s\\007' \"$TAG\" >/dev/tty 2>/dev/null || true\n");
452    script.push_str("    printf '\\033]2;%s\\007' \"$TAG\" >/dev/tty 2>/dev/null || true\n");
453    script.push_str("  fi\n");
454    script.push_str("  printf '\\033]0;%s\\007' \"$TAG\" 2>/dev/null || true\n");
455    script.push_str("  printf '\\033]2;%s\\007' \"$TAG\" 2>/dev/null || true\n");
456    script.push_str("}\n");
457
458    // NOTE: the launcher deliberately does not close its own window. AppleScript
459    // run from inside the session makes Terminal.app prompt "Closing this window
460    // will terminate the running processes: bash, osascript" on every session.
461    // Rinne closes the window from outside via `ensure_stage_window_closed`,
462    // once the launcher has exited and nothing is left running in it.
463
464    script.push_str("on_exit() {\n");
465    script.push_str("  ec=$?\n");
466    // Started later; `set -u` means it must be referenced defensively.
467    //
468    // Kill the watchdog's inner `sleep` too, not just the subshell: SIGTERM to
469    // a non-interactive bash does not forward to or reap its foreground child,
470    // so the `sleep` would outlive the launcher for up to WATCHDOG_POLL_SECS.
471    // Rinne closes the window within one 100ms poll of seeing `exit.code`, so
472    // that orphan is exactly what makes Terminal.app ask "terminate the running
473    // processes?" — the prompt this design removes.
474    script.push_str(&format!(
475        "  if [ -n \"${{RINNE_WATCHDOG:-}}\" ]; then\n\
476         \x20   kill \"$RINNE_WATCHDOG\" 2>/dev/null || true\n\
477         \x20   kill \"$(cat {} 2>/dev/null)\" 2>/dev/null || true\n\
478         \x20   wait \"$RINNE_WATCHDOG\" 2>/dev/null || true\n\
479         \x20 fi\n",
480        sleep_pid_q
481    ));
482    script.push_str("  reset_tty\n");
483    script.push_str("  set_stage_title\n");
484    script.push_str(&format!("  echo \"$ec\" > {exit_q}\n"));
485    script.push_str(&format!(
486        "  echo \"{LAUNCHER_MARKER} harness exit $ec\" >> {log_q} 2>/dev/null || true\n"
487    ));
488    // Exiting is all this shell should do: once it is gone the window holds no
489    // running processes, so Rinne can close it silently from outside.
490    script.push_str("}\n");
491    script.push_str("trap on_exit EXIT\n");
492    script.push_str("trap 'exit 143' TERM\n");
493    script.push_str("trap 'exit 130' INT\n");
494
495    script.push_str(&format!("echo $$ > {pid_q}\n"));
496
497    // Parent-death watchdog. Rinne can exit without running any cleanup (panic,
498    // SIGKILL, closed laptop), which used to leave the harness running against
499    // the user's subscription with the Terminal window still open. Poll the
500    // Rinne pid and, once it is gone, signal only *children* — killing this
501    // shell directly would skip `on_exit` and leave mouse tracking enabled.
502    //
503    // The subshell's stdio is detached from the tty: an orphaned `sleep` still
504    // holding this window's terminal is what makes Terminal.app ask "terminate
505    // the running processes?" when Rinne closes the window. It records the
506    // `sleep`'s pid so `on_exit` can reap that too — SIGTERM to the subshell
507    // alone does not forward to its foreground child. No `set -m`: job control
508    // here caused pgid races (see `interactive_launcher_resets_tty_…`).
509    script.push_str(&format!(
510        "RINNE_PID={}\n\
511         (\n\
512         \x20 while kill -0 \"$RINNE_PID\" 2>/dev/null; do\n\
513         \x20   sleep {} & echo $! > {}; wait $!\n\
514         \x20 done\n\
515         \x20 pkill -TERM -P $$ 2>/dev/null || true\n\
516         ) </dev/null >/dev/null 2>&1 &\n\
517         RINNE_WATCHDOG=$!\n",
518        std::process::id(),
519        WATCHDOG_POLL_SECS,
520        sleep_pid_q
521    ));
522
523    // Record tty early so Rinne can close the window even if the trap is skipped.
524    script.push_str("TTY_NAME=$(tty 2>/dev/null | sed 's|^/dev/||' || true)\n");
525    script.push_str(&format!(
526        "[ -n \"${{TTY_NAME:-}}\" ] && echo \"$TTY_NAME\" > {tty_q} || true\n"
527    ));
528    // Title first so every subsequent close-by-name works.
529    script.push_str("set_stage_title\n");
530    script.push_str("reset_tty\n");
531    script.push_str("set_stage_title\n");
532
533    // Build argv.
534    script.push_str("cmd=(\n");
535    script.push_str(&format!("  {}\n", sh_quote(&spec.program)));
536    for a in &spec.args {
537        script.push_str(&format!("  {}\n", sh_quote(a)));
538    }
539    script.push_str(")\n");
540
541    let prompt_file = script_path
542        .parent()
543        .unwrap_or(Path::new("/tmp"))
544        .join("prompt.txt");
545    if let Some(ref input) = spec.stdin {
546        let _ = std::fs::write(&prompt_file, input);
547    }
548
549    match mode {
550        TerminalMode::Interactive => {
551            // Clean slate, then product UI. No banner — the harness owns the screen.
552            script.push_str("if [ -w /dev/tty ]; then\n");
553            script.push_str("  printf '\\033[2J\\033[H' >/dev/tty 2>/dev/null || true\n");
554            script.push_str("fi\n");
555            if spec.stdin.is_some() {
556                script.push_str(&format!(
557                    "\"${{cmd[@]}}\" < {}\n",
558                    sh_quote(&prompt_file.display().to_string())
559                ));
560            } else {
561                // format! → "${cmd[@]}"
562                script.push_str("\"${cmd[@]}\"\n");
563            }
564            // EXIT trap: reset TTY, write exit code, close this Terminal window.
565            script.push_str("ec=$?\n");
566            script.push_str("exit \"$ec\"\n");
567        }
568        TerminalMode::Capture => {
569            script.push_str("echo \"Rinne single-turn session\" >> ");
570            script.push_str(&log_q);
571            script.push_str("\n");
572            if spec.stdin.is_some() {
573                script.push_str(&format!(
574                    "\"${{cmd[@]}}\" < {} 2>&1 | tee -a {}\n",
575                    sh_quote(&prompt_file.display().to_string()),
576                    log_q
577                ));
578            } else {
579                script.push_str(&format!("\"${{cmd[@]}}\" 2>&1 | tee -a {}\n", log_q));
580            }
581            script.push_str("ec=${PIPESTATUS[0]}\n");
582            script.push_str("exit \"$ec\"\n");
583        }
584    }
585
586    std::fs::write(script_path, script)
587        .map_err(|e| RinneError::Worker(format!("write terminal launcher: {e}")))?;
588    #[cfg(unix)]
589    {
590        use std::os::unix::fs::PermissionsExt;
591        let mut perms = std::fs::metadata(script_path)
592            .map_err(|e| RinneError::Worker(format!("stat launcher: {e}")))?
593            .permissions();
594        perms.set_mode(0o755);
595        std::fs::set_permissions(script_path, perms)
596            .map_err(|e| RinneError::Worker(format!("chmod launcher: {e}")))?;
597    }
598    Ok(())
599}
600
601/// Open a new system terminal window that runs the launcher.
602fn open_system_terminal(
603    script_path: &Path,
604    workspace: &Path,
605    stage_tag: &str,
606    win_path: &Path,
607) -> Result<()> {
608    let script = script_path.display().to_string();
609    let cwd = workspace.display().to_string();
610
611    let prefer = std::env::var("RINNE_EXTERNAL_TERMINAL")
612        .unwrap_or_default()
613        .to_ascii_lowercase();
614
615    #[cfg(target_os = "macos")]
616    {
617        // No installed-check: an explicit `RINNE_EXTERNAL_TERMINAL=iterm` is
618        // honoured either way (see `choose_macos_terminal`), so probing for the
619        // app only cost a `which` fork per window open.
620        if choose_macos_terminal(&prefer) == MacTerminal::ITerm {
621            return open_iterm(&script, &cwd, stage_tag, win_path);
622        }
623        // Prefer osascript so we can capture the window id for forced close.
624        if open_macos_terminal_capture_id(&script, stage_tag, win_path).is_ok() {
625            return Ok(());
626        }
627        // Fallback: open .command file.
628        if script_path
629            .extension()
630            .and_then(|e| e.to_str())
631            .is_some_and(|e| e == "command")
632        {
633            return open_macos_command_file(script_path);
634        }
635        return open_macos_terminal_capture_id(&script, stage_tag, win_path);
636    }
637
638    #[cfg(not(target_os = "macos"))]
639    {
640        let _ = (cwd, stage_tag, win_path);
641        if prefer == "kitty" || which("kitty") {
642            return run_detached("kitty", &["--title", stage_tag, "bash", &script]);
643        }
644        if prefer == "gnome" || which("gnome-terminal") {
645            return run_detached(
646                "gnome-terminal",
647                &["--title", stage_tag, "--", "bash", &script],
648            );
649        }
650        if which("x-terminal-emulator") {
651            return run_detached("x-terminal-emulator", &["-e", "bash", &script]);
652        }
653        if which("xterm") {
654            return run_detached("xterm", &["-T", stage_tag, "-e", "bash", &script]);
655        }
656        Err(RinneError::Worker(
657            "no system terminal found (install gnome-terminal, xterm, or kitty; \
658             or set RINNE_EXTERNAL_TERMINAL)"
659                .into(),
660        ))
661    }
662}
663
664#[cfg(target_os = "macos")]
665fn open_macos_command_file(script_path: &Path) -> Result<()> {
666    let status = StdCommand::new("open")
667        .arg("-a")
668        .arg("Terminal")
669        .arg(script_path)
670        .status()
671        .map_err(|e| RinneError::Worker(format!("open Terminal: {e}")))?;
672    if status.success() {
673        Ok(())
674    } else {
675        Err(RinneError::Worker(format!(
676            "open Terminal failed with {status}"
677        )))
678    }
679}
680
681#[cfg(target_os = "macos")]
682fn open_macos_terminal_capture_id(script: &str, stage_tag: &str, win_path: &Path) -> Result<()> {
683    // Launch, set custom title via AppleScript, and record window id for kill.
684    let apple = format!(
685        r#"tell application "Terminal"
686  activate
687  set newTab to do script "exec bash {script}"
688  delay 0.35
689  try
690    set custom title of newTab to "{tag}"
691  end try
692  try
693    set wid to id of front window
694    return wid as text
695  on error
696    return ""
697  end try
698end tell"#,
699        script = sh_quote(script).replace('\\', "\\\\"),
700        tag = stage_tag.replace('\\', "\\\\").replace('"', "\\\"")
701    );
702    let output = StdCommand::new("osascript")
703        .arg("-e")
704        .arg(&apple)
705        .output()
706        .map_err(|e| RinneError::Worker(format!("osascript Terminal: {e}")))?;
707    if !output.status.success() {
708        return Err(RinneError::Worker(format!(
709            "osascript Terminal failed with {}",
710            output.status
711        )));
712    }
713    let wid = String::from_utf8_lossy(&output.stdout).trim().to_string();
714    if !wid.is_empty() {
715        let _ = std::fs::write(win_path, &wid);
716    }
717    Ok(())
718}
719
720#[cfg(target_os = "macos")]
721fn open_iterm(script: &str, _cwd: &str, stage_tag: &str, win_path: &Path) -> Result<()> {
722    let apple = format!(
723        r#"tell application "iTerm"
724  activate
725  try
726    tell current window
727      create tab with default profile
728      tell current session
729        write text "exec bash {script}"
730        set name to "{tag}"
731      end tell
732      try
733        set wid to id
734        return wid as text
735      end try
736    end tell
737  on error
738    create window with default profile
739    tell current session of current window
740      write text "exec bash {script}"
741      set name to "{tag}"
742    end tell
743    try
744      set wid to id of current window
745      return wid as text
746    end try
747  end try
748  return ""
749end tell"#,
750        script = sh_quote(script),
751        tag = stage_tag.replace('\\', "\\\\").replace('"', "\\\"")
752    );
753    let output = StdCommand::new("osascript")
754        .arg("-e")
755        .arg(&apple)
756        .output()
757        .map_err(|e| RinneError::Worker(format!("osascript iTerm: {e}")))?;
758    if output.status.success() {
759        let wid = String::from_utf8_lossy(&output.stdout).trim().to_string();
760        if !wid.is_empty() {
761            let _ = std::fs::write(win_path, &wid);
762        }
763        Ok(())
764    } else {
765        open_macos_terminal_capture_id(script, stage_tag, win_path)
766    }
767}
768
769/// True if `bin` is found on `PATH` (honours `PATHEXT` on Windows).
770/// Used by non-macOS terminal selection; compiled everywhere so unit tests cover it.
771fn which(bin: &str) -> bool {
772    let Some(path_var) = std::env::var_os("PATH") else {
773        return false;
774    };
775    let exts: Vec<String> = if cfg!(windows) {
776        std::env::var("PATHEXT")
777            .unwrap_or_else(|_| ".EXE;.CMD;.BAT;.COM".to_string())
778            .split(';')
779            .map(|s| s.to_string())
780            .collect()
781    } else {
782        vec![String::new()]
783    };
784    for dir in std::env::split_paths(&path_var) {
785        for ext in &exts {
786            let candidate = dir.join(format!("{bin}{ext}"));
787            if candidate.is_file() {
788                return true;
789            }
790        }
791    }
792    false
793}
794
795#[cfg(not(target_os = "macos"))]
796fn run_detached(program: &str, args: &[&str]) -> Result<()> {
797    StdCommand::new(program)
798        .args(args)
799        .stdin(std::process::Stdio::null())
800        .stdout(std::process::Stdio::null())
801        .stderr(std::process::Stdio::null())
802        .spawn()
803        .map_err(|e| RinneError::Worker(format!("spawn {program}: {e}")))?;
804    Ok(())
805}
806
807async fn wait_for_file(path: &Path, cancel: &CancellationToken, deadline: Instant) -> Result<()> {
808    loop {
809        if cancel.is_cancelled() {
810            return Err(RinneError::Worker(
811                "cancelled before terminal started".into(),
812            ));
813        }
814        if Instant::now() >= deadline {
815            return Err(RinneError::Worker(
816                "timeout waiting for external terminal to start".into(),
817            ));
818        }
819        if path.exists() {
820            return Ok(());
821        }
822        sleep(POLL).await;
823    }
824}
825
826/// Multi-strategy close with retries. Goal: **never** leave a Stage Terminal open.
827///
828/// Order:
829/// 1. by window id (captured at open)
830/// 2. by unique title tag (`rinne-stage-…`)
831/// 3. by tty name
832/// 4. System Events Cmd+W by title
833/// 5. Linux wmctrl/xdotool by title
834async fn ensure_stage_window_closed(tty_path: &Path, tag_path: &Path, win_path: &Path) {
835    let tag = std::fs::read_to_string(tag_path)
836        .unwrap_or_default()
837        .trim()
838        .to_string();
839    let tty = std::fs::read_to_string(tty_path)
840        .unwrap_or_default()
841        .trim()
842        .trim_start_matches("/dev/")
843        .to_string();
844    let win_id = std::fs::read_to_string(win_path)
845        .unwrap_or_default()
846        .trim()
847        .to_string();
848
849    // Several passes: Terminal.app sometimes ignores the first close while the
850    // shell is still dying.
851    for attempt in 0..6 {
852        close_stage_window_once(&tty, &tag, &win_id);
853        // If we still see a matching window, wait and retry.
854        if !stage_window_still_open(&tag, &win_id) {
855            return;
856        }
857        sleep(Duration::from_millis(150 + attempt * 100)).await;
858    }
859    // Last desperate pass.
860    close_stage_window_once(&tty, &tag, &win_id);
861    close_stage_window_once(&tty, &tag, &win_id);
862}
863
864fn close_stage_window_once(tty: &str, tag: &str, win_id: &str) {
865    #[cfg(target_os = "macos")]
866    {
867        // 1) Window id
868        if !win_id.is_empty() && win_id.chars().all(|c| c.is_ascii_digit()) {
869            let script = format!(
870                r#"tell application "Terminal"
871  try
872    close (every window whose id is {win_id}) saving no
873  end try
874end tell"#
875            );
876            run_osascript(&script);
877            let script = format!(
878                r#"tell application "iTerm"
879  try
880    repeat with w in windows
881      try
882        if (id of w as text) is "{win_id}" then close w
883      end try
884    end repeat
885  end try
886end tell"#
887            );
888            run_osascript(&script);
889        }
890
891        // 2) Unique title tag (most reliable across open methods)
892        if !tag.is_empty() {
893            let tag_esc = tag.replace('\\', "\\\\").replace('"', "\\\"");
894            let script = format!(
895                r#"tell application "Terminal"
896  try
897    set wins to windows whose name contains "{tag_esc}"
898    repeat with w in wins
899      try
900        close w saving no
901      end try
902    end repeat
903  end try
904end tell"#
905            );
906            run_osascript(&script);
907
908            let script = format!(
909                r#"tell application "iTerm"
910  try
911    repeat with w in windows
912      repeat with t in tabs of w
913        repeat with s in sessions of t
914          try
915            if name of s contains "{tag_esc}" then close s
916          end try
917        end repeat
918      end repeat
919      try
920        if name of w contains "{tag_esc}" then close w
921      end try
922    end repeat
923  end try
924end tell"#
925            );
926            run_osascript(&script);
927
928            // System Events (works even when Terminal Apple Events are flaky)
929            let script = format!(
930                r#"tell application "System Events"
931  if exists process "Terminal" then
932    tell process "Terminal"
933      set frontmost to true
934      repeat with w in windows
935        try
936          if name of w contains "{tag_esc}" then
937            perform action "AXRaise" of w
938            keystroke "w" using command down
939            delay 0.12
940            keystroke return
941          end if
942        end try
943      end repeat
944    end tell
945  end if
946  if exists process "iTerm2" then
947    tell process "iTerm2"
948      set frontmost to true
949      repeat with w in windows
950        try
951          if name of w contains "{tag_esc}" then
952            perform action "AXRaise" of w
953            keystroke "w" using command down
954            delay 0.12
955            keystroke return
956          end if
957        end try
958      end repeat
959    end tell
960  end if
961end tell"#
962            );
963            run_osascript(&script);
964        }
965
966        // 3) TTY match
967        if !tty.is_empty() {
968            let script = format!(
969                r#"tell application "Terminal"
970  repeat with w in windows
971    try
972      set t to tty of selected tab of w
973      if t is "{tty}" or t is "/dev/{tty}" then
974        close w saving no
975      end if
976    end try
977  end repeat
978end tell"#
979            );
980            run_osascript(&script);
981
982            let script = format!(
983                r#"tell application "iTerm"
984  repeat with w in windows
985    repeat with t in tabs of w
986      repeat with s in sessions of t
987        try
988          if tty of s contains "{tty}" then close s
989        end try
990      end repeat
991    end repeat
992  end repeat
993end tell"#
994            );
995            run_osascript(&script);
996        }
997    }
998
999    #[cfg(not(target_os = "macos"))]
1000    {
1001        if !tag.is_empty() {
1002            let _ = StdCommand::new("wmctrl")
1003                .args(["-c", tag])
1004                .stdout(std::process::Stdio::null())
1005                .stderr(std::process::Stdio::null())
1006                .status();
1007            let _ = StdCommand::new("xdotool")
1008                .args(["search", "--name", tag, "windowclose", "%@"])
1009                .stdout(std::process::Stdio::null())
1010                .stderr(std::process::Stdio::null())
1011                .status();
1012        }
1013        let _ = tty;
1014        let _ = win_id;
1015    }
1016}
1017
1018fn stage_window_still_open(tag: &str, win_id: &str) -> bool {
1019    if tag.is_empty() && win_id.is_empty() {
1020        return false;
1021    }
1022    #[cfg(target_os = "macos")]
1023    {
1024        let tag_esc = tag.replace('\\', "\\\\").replace('"', "\\\"");
1025        let mut checks = String::new();
1026        if !tag.is_empty() {
1027            checks.push_str(&format!(
1028                r#"
1029tell application "Terminal"
1030  try
1031    set n to count of (windows whose name contains "{tag_esc}")
1032    if n > 0 then return "yes"
1033  end try
1034end tell
1035"#
1036            ));
1037        }
1038        if !win_id.is_empty() && win_id.chars().all(|c| c.is_ascii_digit()) {
1039            checks.push_str(&format!(
1040                r#"
1041tell application "Terminal"
1042  try
1043    set n to count of (windows whose id is {win_id})
1044    if n > 0 then return "yes"
1045  end try
1046end tell
1047"#
1048            ));
1049        }
1050        checks.push_str(r#"return "no""#);
1051        let output = StdCommand::new("osascript").arg("-e").arg(&checks).output();
1052        if let Ok(out) = output {
1053            let s = String::from_utf8_lossy(&out.stdout);
1054            return s.contains("yes");
1055        }
1056        // If we can't query, assume it might still be open so we keep retrying.
1057        return true;
1058    }
1059    #[cfg(not(target_os = "macos"))]
1060    {
1061        if tag.is_empty() {
1062            return false;
1063        }
1064        if let Ok(out) = StdCommand::new("wmctrl").args(["-l"]).output() {
1065            let s = String::from_utf8_lossy(&out.stdout);
1066            return s.contains(tag);
1067        }
1068        false
1069    }
1070}
1071
1072fn run_osascript(script: &str) {
1073    let _ = StdCommand::new("osascript")
1074        .arg("-e")
1075        .arg(script)
1076        .stdout(std::process::Stdio::null())
1077        .stderr(std::process::Stdio::null())
1078        .status();
1079}
1080
1081/// SIGTERM the launcher (so EXIT trap resets the TTY + closes the window),
1082/// wait for exit.code, only then SIGKILL if still alive.
1083async fn soft_stop(pid_path: &Path, exit_path: &Path) {
1084    let Some(pid) = read_pid(pid_path) else {
1085        return;
1086    };
1087
1088    #[cfg(unix)]
1089    {
1090        unsafe {
1091            // Leaves first. The launcher is bash blocked on the foreground
1092            // harness, so its TERM trap cannot run until that harness exits —
1093            // signalling bash alone is a no-op until it is too late. Killing
1094            // the harness lets bash resume into `on_exit`, which resets mouse
1095            // tracking and closes the window (prior failure #3 skipped that).
1096            //
1097            // The group is deliberately not signalled: the launcher shares the
1098            // login shell's process group, so `kill(-pid)` targets a group that
1099            // does not exist, and signalling the real group would hit the user's
1100            // own shell.
1101            for child in descendants_deepest_first(pid, &live_child_pids) {
1102                libc::kill(child, libc::SIGTERM);
1103            }
1104            libc::kill(pid, libc::SIGTERM);
1105        }
1106
1107        let deadline = Instant::now() + TERM_GRACE;
1108        while Instant::now() < deadline {
1109            // Wait for the launcher to actually be gone, not merely for its
1110            // exit file: `on_exit` writes that file and then keeps running for
1111            // a moment. Closing the window while the shell is still alive is
1112            // what makes Terminal.app ask to terminate running processes.
1113            #[cfg(unix)]
1114            {
1115                let alive = unsafe { libc::kill(pid, 0) == 0 };
1116                if !alive {
1117                    if !exit_path.exists() {
1118                        // Trap did not run (hard crash) — synthesize an exit.
1119                        let _ = std::fs::write(exit_path, b"143");
1120                    }
1121                    return;
1122                }
1123            }
1124            sleep(Duration::from_millis(100)).await;
1125        }
1126
1127        // Last resort — again leaves first, so nothing is left reparented to
1128        // init still holding the Terminal window open.
1129        unsafe {
1130            for child in descendants_deepest_first(pid, &live_child_pids) {
1131                libc::kill(child, libc::SIGKILL);
1132            }
1133            libc::kill(pid, libc::SIGKILL);
1134        }
1135        if !exit_path.exists() {
1136            let _ = std::fs::write(exit_path, b"137");
1137        }
1138    }
1139
1140    #[cfg(not(unix))]
1141    {
1142        let _ = (pid, exit_path);
1143    }
1144}
1145
1146fn read_pid(pid_path: &Path) -> Option<i32> {
1147    std::fs::read_to_string(pid_path)
1148        .ok()
1149        .and_then(|s| s.trim().parse().ok())
1150}
1151
1152fn flush_line(
1153    line_buf: &mut String,
1154    captured: &mut String,
1155    truncated: &mut bool,
1156    mapper: LineMapper,
1157    events: &EventSink,
1158) {
1159    let line = std::mem::take(line_buf);
1160    if is_terminal_noise(&line) {
1161        return;
1162    }
1163    if captured.len() < MAX_CAPTURE_BYTES {
1164        captured.push_str(&line);
1165        captured.push('\n');
1166    } else if !*truncated {
1167        *truncated = true;
1168        captured.push_str("\n…[output truncated]\n");
1169    }
1170    for ev in mapper(&line) {
1171        emit(events, ev);
1172    }
1173}
1174
1175/// Which macOS terminal app hosts a Stage session.
1176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1177enum MacTerminal {
1178    /// Terminal.app — the system terminal, and the fallback for anything unknown.
1179    Apple,
1180    ITerm,
1181}
1182
1183/// Pick the terminal app for a Stage session.
1184///
1185/// `prefer` comes from `RINNE_EXTERNAL_TERMINAL`. Terminal.app is the default,
1186/// matching the "opening … in system Terminal" narration; iTerm is opt-in even
1187/// when installed. An explicit preference always wins, so having iTerm present
1188/// can never override a user asking for Terminal.app.
1189fn choose_macos_terminal(prefer: &str) -> MacTerminal {
1190    match prefer.trim().to_ascii_lowercase().as_str() {
1191        "iterm" | "iterm2" => MacTerminal::ITerm,
1192        _ => MacTerminal::Apple,
1193    }
1194}
1195
1196/// Direct children of `pid`, as reported by `pgrep -P`. Empty on any failure —
1197/// callers still signal the launcher itself, so a missing `pgrep` degrades to
1198/// the previous behaviour rather than breaking teardown.
1199fn live_child_pids(pid: i32) -> Vec<i32> {
1200    let Ok(out) = StdCommand::new("pgrep")
1201        .arg("-P")
1202        .arg(pid.to_string())
1203        .output()
1204    else {
1205        return Vec::new();
1206    };
1207    parse_pgrep(&String::from_utf8_lossy(&out.stdout))
1208}
1209
1210/// Split `pgrep` output into PIDs, ignoring blank or malformed lines.
1211fn parse_pgrep(stdout: &str) -> Vec<i32> {
1212    stdout
1213        .lines()
1214        .filter_map(|l| l.trim().parse::<i32>().ok())
1215        .filter(|p| *p > 0)
1216        .collect()
1217}
1218
1219/// Every descendant of `root`, deepest first, excluding `root` itself.
1220///
1221/// Signalling the launcher directly cannot work: bash defers its TERM trap
1222/// until the foreground harness exits, so the trap that resets the TTY never
1223/// runs. Killing the leaves instead lets the harness exit, bash resume, and
1224/// `on_exit` reset mouse tracking before the window closes — which is what
1225/// prior failure #3 (`kill -9` on the process group) skipped.
1226fn descendants_deepest_first(root: i32, children_of: &dyn Fn(i32) -> Vec<i32>) -> Vec<i32> {
1227    let mut seen = std::collections::HashSet::from([root]);
1228    let mut queue = std::collections::VecDeque::from([root]);
1229    // Breadth-first yields shallow→deep; reversing gives leaves first.
1230    let mut order: Vec<i32> = Vec::new();
1231    while let Some(pid) = queue.pop_front() {
1232        for child in children_of(pid) {
1233            // PID reuse can make the walk cyclic; `seen` bounds it.
1234            if child > 0 && seen.insert(child) {
1235                order.push(child);
1236                queue.push_back(child);
1237            }
1238        }
1239    }
1240    order.reverse();
1241    order
1242}
1243
1244/// Decide a session's terminal status from what the launcher left behind.
1245///
1246/// `wanted_result` means the kickoff told the harness to write its deliverable
1247/// to a result file, so that file — not the exit code — is the real signal.
1248fn resolve_status(
1249    wanted_result: bool,
1250    got_result_file: bool,
1251    captured_empty: bool,
1252    exit_code: Option<i32>,
1253    cancelled: bool,
1254) -> ExecStatus {
1255    if got_result_file && !captured_empty {
1256        return ExecStatus::Success;
1257    }
1258    match exit_code {
1259        Some(c) if c != 0 => return ExecStatus::Failed(format!("exited {c}")),
1260        None if cancelled => return ExecStatus::Cancelled,
1261        _ => {}
1262    }
1263    // Exit 0 but no deliverable: the user closed the window, or the harness
1264    // never did the work. Trusting the exit code here silently drops the node's
1265    // output and marks it succeeded.
1266    if wanted_result {
1267        return ExecStatus::Failed(
1268            "harness produced no deliverable — result file was never written".into(),
1269        );
1270    }
1271    match exit_code {
1272        Some(_) => ExecStatus::Success,
1273        None => ExecStatus::Failed("harness terminal closed without exit code".into()),
1274    }
1275}
1276
1277fn is_terminal_noise(line: &str) -> bool {
1278    let t = line.trim();
1279    if t.is_empty() {
1280        return false;
1281    }
1282    // Rinne's own launcher bookkeeping shares the log the Stage tails. It is
1283    // not harness output and must never stand in for the deliverable.
1284    if t.starts_with(LAUNCHER_MARKER) {
1285        return true;
1286    }
1287    // SGR mouse reports: digits/semicolons ending in M/m, often concatenated.
1288    if t.len() >= 4
1289        && t.chars()
1290            .all(|c| c.is_ascii_digit() || matches!(c, ';' | 'M' | 'm'))
1291        && t.contains(';')
1292        && (t.contains('M') || t.ends_with('m'))
1293    {
1294        return true;
1295    }
1296    false
1297}
1298
1299fn sh_quote(s: &str) -> String {
1300    if s.is_empty() {
1301        return "''".into();
1302    }
1303    let mut out = String::from("'");
1304    for ch in s.chars() {
1305        if ch == '\'' {
1306            out.push_str("'\\''");
1307        } else {
1308            out.push(ch);
1309        }
1310    }
1311    out.push('\'');
1312    out
1313}
1314
1315fn unique_suffix() -> u128 {
1316    std::time::SystemTime::now()
1317        .duration_since(std::time::UNIX_EPOCH)
1318        .map(|d| d.as_nanos())
1319        .unwrap_or(0)
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324    use super::*;
1325
1326    fn tree<'a>(edges: &'a [(i32, &'a [i32])]) -> impl Fn(i32) -> Vec<i32> + 'a {
1327        move |pid| {
1328            edges
1329                .iter()
1330                .find(|(p, _)| *p == pid)
1331                .map(|(_, kids)| kids.to_vec())
1332                .unwrap_or_default()
1333        }
1334    }
1335
1336    #[test]
1337    fn descendants_are_returned_leaves_before_parents() {
1338        // launcher(10) → harness(20) → tool(30), plus a sibling(21).
1339        let f = tree(&[(10, &[20, 21]), (20, &[30])]);
1340        let got = descendants_deepest_first(10, &f);
1341
1342        assert!(!got.contains(&10), "root must not be signalled: {got:?}");
1343        let pos = |p: i32| got.iter().position(|x| *x == p).unwrap();
1344        assert!(
1345            pos(30) < pos(20),
1346            "a child must be signalled before its parent"
1347        );
1348        assert_eq!(got.len(), 3, "{got:?}");
1349    }
1350
1351    #[test]
1352    fn an_explicit_terminal_preference_beats_an_installed_iterm() {
1353        // Having iTerm installed must not override an explicit choice, or the
1354        // RINNE_EXTERNAL_TERMINAL escape hatch cannot select Terminal.app.
1355        assert_eq!(choose_macos_terminal("terminal"), MacTerminal::Apple);
1356        assert_eq!(choose_macos_terminal("terminal.app"), MacTerminal::Apple);
1357        assert_eq!(choose_macos_terminal("iterm"), MacTerminal::ITerm);
1358        assert_eq!(choose_macos_terminal("iterm2"), MacTerminal::ITerm);
1359    }
1360
1361    #[test]
1362    fn with_no_preference_the_system_terminal_is_used() {
1363        // Rinne's own narration promises the "system Terminal"; defaulting to
1364        // whatever else happens to be installed contradicts it.
1365        assert_eq!(choose_macos_terminal(""), MacTerminal::Apple);
1366        assert_eq!(choose_macos_terminal("   "), MacTerminal::Apple);
1367    }
1368
1369    #[test]
1370    fn an_unrecognised_preference_falls_back_to_terminal_app() {
1371        assert_eq!(choose_macos_terminal("wezterm"), MacTerminal::Apple);
1372    }
1373
1374    #[test]
1375    fn launcher_never_closes_its_own_window_from_inside() {
1376        let dir = std::env::temp_dir().join(format!("rinne-ext-noclose-{}", std::process::id()));
1377        let _ = std::fs::remove_dir_all(&dir);
1378        std::fs::create_dir_all(&dir).unwrap();
1379        let script = dir.join("run.command");
1380        let spec = SubprocessSpec {
1381            program: "claude".into(),
1382            args: vec!["hello".into()],
1383            workspace: dir.clone(),
1384            stdin: None,
1385            timeout: None,
1386            env: vec![],
1387            result_file: Some(dir.join("result.txt")),
1388        };
1389        write_launcher(
1390            &script,
1391            &spec,
1392            &dir.join("h.log"),
1393            &dir.join("e.code"),
1394            &dir.join("w.pid"),
1395            &dir.join("tty.name"),
1396            "rinne-stage-noclose-tag",
1397            TerminalMode::Interactive,
1398        )
1399        .unwrap();
1400        let body = std::fs::read_to_string(&script).unwrap();
1401
1402        // Closing the window from a process *inside* it makes Terminal.app ask
1403        // "Closing this window will terminate the running processes: bash,
1404        // osascript" on every session. Rinne closes the window from outside,
1405        // after the launcher has exited, where nothing is left running.
1406        assert!(
1407            !body.contains("osascript"),
1408            "launcher must not run AppleScript inside its own window: {body}"
1409        );
1410        assert!(
1411            !body.contains("close_window"),
1412            "window closing belongs to Rinne, not the launcher: {body}"
1413        );
1414        let _ = std::fs::remove_dir_all(&dir);
1415    }
1416
1417    #[test]
1418    fn launcher_reaps_the_harness_when_rinne_dies() {
1419        let dir = std::env::temp_dir().join(format!("rinne-ext-wd-{}", std::process::id()));
1420        let _ = std::fs::remove_dir_all(&dir);
1421        std::fs::create_dir_all(&dir).unwrap();
1422        let script = dir.join("run.command");
1423        let spec = SubprocessSpec {
1424            program: "claude".into(),
1425            args: vec!["hello".into()],
1426            workspace: dir.clone(),
1427            stdin: None,
1428            timeout: None,
1429            env: vec![],
1430            result_file: Some(dir.join("result.txt")),
1431        };
1432        write_launcher(
1433            &script,
1434            &spec,
1435            &dir.join("h.log"),
1436            &dir.join("e.code"),
1437            &dir.join("w.pid"),
1438            &dir.join("tty.name"),
1439            "rinne-stage-wd-tag",
1440            TerminalMode::Interactive,
1441        )
1442        .unwrap();
1443        let body = std::fs::read_to_string(&script).unwrap();
1444
1445        // Rinne can be SIGKILLed, so nothing in-process can clean up. The
1446        // launcher must watch Rinne's pid itself and reap the harness.
1447        assert!(
1448            body.contains(&format!("RINNE_PID={}", std::process::id())),
1449            "launcher must know the Rinne pid that spawned it"
1450        );
1451        assert!(
1452            body.contains("kill -0 \"$RINNE_PID\""),
1453            "launcher must poll that pid for liveness"
1454        );
1455        // Bash keeps only one EXIT trap, so the watchdog must be torn down from
1456        // inside on_exit rather than by installing a second one — a second
1457        // `trap ... EXIT` would silently replace the TTY reset.
1458        assert_eq!(
1459            body.lines()
1460                .filter(|l| l.starts_with("trap ") && l.ends_with(" EXIT"))
1461                .count(),
1462            1,
1463            "exactly one EXIT trap, or on_exit is silently replaced: {body}"
1464        );
1465        // It must kill only its children: killing itself would skip on_exit and
1466        // leave mouse tracking enabled (prior failure #3).
1467        assert!(
1468            body.contains("pkill -TERM -P $$"),
1469            "watchdog must signal children so on_exit still resets the TTY"
1470        );
1471        // The watchdog's own `sleep` must not be left on this window's tty:
1472        // killing the subshell does not reap its foreground child, and an
1473        // orphan holding the terminal is what makes Terminal.app ask
1474        // "terminate the running processes?" when Rinne closes the window.
1475        assert!(
1476            body.contains("watchdog-sleep.pid"),
1477            "watchdog must record its sleep pid so on_exit can reap it: {body}"
1478        );
1479        assert!(
1480            body.contains("</dev/null >/dev/null 2>&1 &"),
1481            "watchdog stdio must be detached from the window's tty: {body}"
1482        );
1483        let _ = std::fs::remove_dir_all(&dir);
1484    }
1485
1486    #[test]
1487    fn pgrep_output_parses_and_ignores_junk() {
1488        assert_eq!(parse_pgrep("120\n131\n"), vec![120, 131]);
1489        assert_eq!(parse_pgrep(""), Vec::<i32>::new());
1490        assert_eq!(parse_pgrep("\n  \nnot-a-pid\n7\n"), vec![7]);
1491        // A zero or negative pid would signal a process group; never emit one.
1492        assert_eq!(parse_pgrep("0\n-1\n9"), vec![9]);
1493    }
1494
1495    #[test]
1496    fn which_finds_a_real_binary_and_rejects_garbage() {
1497        // `sh` is on PATH on every Unix CI image; Windows release jobs use PATHEXT.
1498        #[cfg(unix)]
1499        assert!(which("sh"), "sh should be on PATH");
1500        #[cfg(windows)]
1501        assert!(which("cmd"), "cmd should be on PATH");
1502        assert!(!which("rinne-definitely-not-a-binary-xyzzy"));
1503    }
1504
1505    #[test]
1506    fn descendants_of_a_leaf_is_empty() {
1507        let f = tree(&[]);
1508        assert!(descendants_deepest_first(99, &f).is_empty());
1509    }
1510
1511    #[test]
1512    fn descendants_terminates_on_a_cycle() {
1513        // PID reuse can produce a cycle; the walk must not hang or repeat.
1514        let f = tree(&[(1, &[2]), (2, &[1])]);
1515        let got = descendants_deepest_first(1, &f);
1516        assert_eq!(got, vec![2], "{got:?}");
1517    }
1518
1519    #[test]
1520    fn a_missing_deliverable_fails_even_when_the_harness_exits_clean() {
1521        // An interactive kickoff tells the harness to write its deliverable to
1522        // a result file. Exiting 0 without one means the user closed the window
1523        // or the harness never did the work — the node contributed nothing and
1524        // must not be reported as succeeded.
1525        let status = resolve_status(true, false, true, Some(0), false);
1526        assert!(
1527            matches!(status, ExecStatus::Failed(_)),
1528            "expected Failed, got {status:?}"
1529        );
1530    }
1531
1532    #[test]
1533    fn a_produced_deliverable_succeeds() {
1534        assert!(matches!(
1535            resolve_status(true, true, false, Some(0), false),
1536            ExecStatus::Success
1537        ));
1538    }
1539
1540    #[test]
1541    fn capture_sessions_still_succeed_on_a_clean_exit() {
1542        // No result file was ever demanded, so the exit code is the only signal.
1543        assert!(matches!(
1544            resolve_status(false, false, false, Some(0), false),
1545            ExecStatus::Success
1546        ));
1547    }
1548
1549    #[test]
1550    fn launcher_bookkeeping_is_not_harness_output() {
1551        // The launcher writes its own exit marker into the same log the Stage
1552        // tails, so without filtering it is shown as harness output and can end
1553        // up standing in for the deliverable.
1554        assert!(is_terminal_noise("rinne-launcher: harness exit 0"));
1555        assert!(is_terminal_noise("  rinne-launcher: harness exit 143  "));
1556        assert!(!is_terminal_noise("editing src/main.rs"));
1557        assert!(!is_terminal_noise(
1558            "the launcher script is described in rinne-launcher docs"
1559        ));
1560    }
1561
1562    #[test]
1563    fn sh_quote_handles_spaces_and_quotes() {
1564        assert_eq!(sh_quote("hello"), "'hello'");
1565        assert_eq!(sh_quote("a b"), "'a b'");
1566        assert!(sh_quote("it's").contains("\\'"));
1567    }
1568
1569    #[test]
1570    fn interactive_launcher_resets_tty_and_avoids_script_tee() {
1571        let dir = std::env::temp_dir().join(format!("rinne-ext-int-{}", std::process::id()));
1572        let _ = std::fs::remove_dir_all(&dir);
1573        std::fs::create_dir_all(&dir).unwrap();
1574        let script = dir.join("run.command");
1575        let log = dir.join("h.log");
1576        let exit = dir.join("e.code");
1577        let pid = dir.join("w.pid");
1578        let result = dir.join("result.txt");
1579        let spec = SubprocessSpec {
1580            program: "grok".into(),
1581            args: vec![
1582                "--fullscreen".into(),
1583                "--always-approve".into(),
1584                "hello".into(),
1585            ],
1586            workspace: dir.clone(),
1587            stdin: None,
1588            timeout: None,
1589            env: vec![],
1590            result_file: Some(result),
1591        };
1592        let tty = dir.join("tty.name");
1593        write_launcher(
1594            &script,
1595            &spec,
1596            &log,
1597            &exit,
1598            &pid,
1599            &tty,
1600            "rinne-stage-test-tag",
1601            TerminalMode::Interactive,
1602        )
1603        .unwrap();
1604        let body = std::fs::read_to_string(&script).unwrap();
1605        assert!(body.contains("reset_tty"), "must reset mouse tracking");
1606        assert!(body.contains("1000l"), "must disable mouse mode 1000");
1607        assert!(
1608            body.contains("set_stage_title"),
1609            "must title window for close-by-name"
1610        );
1611        assert!(body.contains("rinne-stage-test-tag"));
1612        assert!(body.contains("trap on_exit EXIT"));
1613        assert!(!body.contains("script -q"), "must not use script(1)");
1614        assert!(
1615            !body.contains("tee -a") || body.contains("Capture"),
1616            "interactive must not tee"
1617        );
1618        assert!(!body.contains("set -m"), "no job-control pgid races");
1619        assert!(!body.contains("Rinne → harness session"));
1620        let _ = std::fs::remove_dir_all(&dir);
1621    }
1622
1623    #[test]
1624    fn capture_launcher_uses_tee_not_script() {
1625        let dir = std::env::temp_dir().join(format!("rinne-ext-cap-{}", std::process::id()));
1626        let _ = std::fs::remove_dir_all(&dir);
1627        std::fs::create_dir_all(&dir).unwrap();
1628        let script = dir.join("run.command");
1629        let log = dir.join("h.log");
1630        let exit = dir.join("e.code");
1631        let pid = dir.join("w.pid");
1632        let tty = dir.join("tty.name");
1633        let spec = SubprocessSpec {
1634            program: "echo".into(),
1635            args: vec!["-p".into(), "hi".into()],
1636            workspace: dir.clone(),
1637            stdin: None,
1638            timeout: Some(Duration::from_secs(5)),
1639            env: vec![],
1640            result_file: None,
1641        };
1642        write_launcher(
1643            &script,
1644            &spec,
1645            &log,
1646            &exit,
1647            &pid,
1648            &tty,
1649            "rinne-stage-cap-tag",
1650            TerminalMode::Capture,
1651        )
1652        .unwrap();
1653        let body = std::fs::read_to_string(&script).unwrap();
1654        assert!(body.contains("tee"));
1655        assert!(!body.contains("script -q"));
1656        assert!(body.contains("rinne-stage-cap-tag"));
1657        let _ = std::fs::remove_dir_all(&dir);
1658    }
1659
1660    #[test]
1661    fn mouse_noise_filtered() {
1662        assert!(is_terminal_noise("35;6M35;35;7M65;35;7M"));
1663        assert!(is_terminal_noise("36;18M35;37;18M"));
1664        assert!(!is_terminal_noise("planning complete"));
1665        assert!(!is_terminal_noise(r#"{"goal":"x"}"#));
1666    }
1667}