Lutra/apps/lutra-cli/src/launch.rs
danny 1bf69ded55 A1: macOS readiness: setup guide, cargo xtask mac-report, unix/macOS fixes
- docs/macos.md: step-by-step setup for a fresh Apple Silicon Mac (Xcode
  CLT, Homebrew, git, PHP, Composer, Node 22, pnpm, rustup, clone from
  Forgejo), the machine report, Gatekeeper notes, macOS differences and
  what Windows cannot check.
- cargo xtask mac-report: versions, the gate steps, the bundled-UI desktop
  build and a self-check over the control channel (project, file,
  Phpactor, hover, git.status, terminal, screenshot, quit); every step
  times out and runs in a lutra_proc group; one report.md to send back.
- Fixes: macOS native menu (system menus only; Cmd+W stays buffer.close,
  Cmd+Q runs app.quit), xcap screenshot region in points on macOS
  (Retina), login shell (-l, /bin/zsh fallback) and LANG for the
  terminal on macOS, PHP lookup in Homebrew/MacPorts dirs for Finder
  starts, case-insensitive LSP path mapping on macOS, rendezvous file
  mode re-set to 0600, CLI-started desktop in its own process group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:47:45 +01:00

113 lines
3.7 KiB
Rust

//! Finding and starting the desktop app when no Lutra is running.
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use lutra_control::client::{self, Client};
/// Environment variable with the path of the desktop binary to start.
pub const DESKTOP_ENV: &str = "LUTRA_DESKTOP";
/// File name of the desktop binary.
const DESKTOP_NAME: &str = if cfg!(windows) {
"lutra-desktop.exe"
} else {
"lutra-desktop"
};
/// How long to wait for a started app to write its rendezvous file and
/// answer.
pub const START_TIMEOUT: Duration = Duration::from_secs(60);
/// Time between two looks at the rendezvous file while the app starts.
const POLL: Duration = Duration::from_millis(150);
/// Time to wait for one connection attempt while the app starts.
const PROBE: Duration = Duration::from_secs(2);
/// The desktop binary: `LUTRA_DESKTOP` if set, else `lutra-desktop` next to
/// this executable, else the first `lutra-desktop` on `PATH`.
///
/// # Errors
/// A message naming the places that were tried.
pub fn find_desktop() -> Result<PathBuf, String> {
if let Some(path) = std::env::var_os(DESKTOP_ENV).filter(|v| !v.is_empty()) {
return Ok(PathBuf::from(path));
}
let sibling = std::env::current_exe()
.ok()
.and_then(|exe| Some(exe.parent()?.join(DESKTOP_NAME)))
.filter(|path| path.is_file());
if let Some(path) = sibling {
return Ok(path);
}
std::env::var_os("PATH")
.and_then(|paths| {
std::env::split_paths(&paths)
.map(|dir| dir.join(DESKTOP_NAME))
.find(|path| path.is_file())
})
.ok_or_else(|| {
format!(
"cannot find {DESKTOP_NAME}: set {DESKTOP_ENV}, or put it next to lutra or on PATH"
)
})
}
/// Starts `desktop` detached from this terminal (Windows: a detached process
/// in a new process group; Unix: a new process group, so a Ctrl-C or
/// hangup aimed at the terminal's foreground group does not reach it) and
/// waits until it answers
/// on the rendezvous file in `dir`. A desktop that exits successfully may
/// have forwarded to an instance that started at the same time, so only a
/// failed exit ends the wait early.
///
/// # Errors
/// A message if it cannot be started, exits early, or does not answer
/// within [`START_TIMEOUT`].
pub fn start(desktop: &Path, dir: &Path) -> Result<Client, String> {
let mut command = Command::new(desktop);
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command
.spawn()
.map_err(|e| format!("cannot start {}: {e}", desktop.display()))?;
let deadline = Instant::now() + START_TIMEOUT;
loop {
if let Ok((_, client)) = client::connect_live(dir, PROBE) {
return Ok(client);
}
if let Ok(Some(status)) = child.try_wait()
&& !status.success()
{
return Err(format!(
"{} exited before it was ready ({status})",
desktop.display()
));
}
if Instant::now() >= deadline {
return Err(format!(
"{} did not answer within {} s",
desktop.display(),
START_TIMEOUT.as_secs()
));
}
thread::sleep(POLL);
}
}