From f3d7a4f45fe1153d2cefd43181c3cfc13531779c Mon Sep 17 00:00:00 2001 From: zackees Date: Thu, 11 Jun 2026 19:20:23 -0700 Subject: [PATCH] feat(viewer): closing the viewer window terminates the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a non-blocking ViewerProcess::is_alive() probe (WaitForSingleObject on Windows, SpawnedChild::try_wait on POSIX) and treat viewer exit as a clean shutdown signal: the normal sketch watch loop checks liveness each 1s tick, and --serve-dir selects over Ctrl+C and a 1s liveness poll. Headless serve (--internal-serve-dir-headless) is unchanged — it never constructs a ViewerProcess, asserted via the new serve_dir_request() dispatch tests. Viewer crash and user close are treated identically and exit 0; in-flight compiles always finish before shutdown. Closes #167 Co-Authored-By: Claude Opus 4.7 --- crates/fastled-cli/src/commands.rs | 42 ++++++++++++-- crates/fastled-cli/src/lib.rs | 40 ++++++++++--- crates/fastled-cli/src/viewer.rs | 92 ++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+), 12 deletions(-) diff --git a/crates/fastled-cli/src/commands.rs b/crates/fastled-cli/src/commands.rs index c94d8daa..94260ad5 100644 --- a/crates/fastled-cli/src/commands.rs +++ b/crates/fastled-cli/src/commands.rs @@ -80,7 +80,7 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode { let url = format!("http://{addr}"); println!("Serving at {url}"); - let _viewer = match viewer::launch_tauri_viewer(&url) { + let mut viewer = match viewer::launch_tauri_viewer(&url) { Ok(process) => process, Err(e) => { eprintln!("fastled: Tauri viewer failed: {e:#}"); @@ -115,6 +115,15 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode { let rx = file_watcher.start(); loop { + // The viewer window is the app from the user's perspective: once + // it is gone (closed or crashed), shut the CLI down cleanly. An + // in-flight compile always finishes first because this check only + // runs between loop ticks. + if !viewer.is_alive() { + println!("\nViewer window closed; shutting down."); + break; + } + let should_rebuild = match rx.recv_timeout(std::time::Duration::from_secs(1)) { Ok(changed) => { println!("\nChanges detected in {changed:?}"); @@ -355,7 +364,7 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode { println!("Serving {dir} at {url}"); println!("Press Ctrl+C to stop..."); - let _viewer = if launch_viewer { + let viewer = if launch_viewer { match viewer::launch_tauri_viewer(&url) { Ok(process) => Some(process), Err(e) => { @@ -367,9 +376,32 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode { None }; - // Wait for Ctrl+C. - tokio::signal::ctrl_c().await.ok(); - println!("\nShutting down..."); + match viewer { + Some(mut viewer) => { + // Exit on Ctrl+C or when the viewer window is closed. + let ctrl_c = tokio::signal::ctrl_c(); + tokio::pin!(ctrl_c); + loop { + tokio::select! { + _ = &mut ctrl_c => { + println!("\nShutting down..."); + break; + } + _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => { + if !viewer.is_alive() { + println!("\nViewer window closed; shutting down."); + break; + } + } + } + } + } + None => { + // Headless serve has no viewer to watch; run until Ctrl+C. + tokio::signal::ctrl_c().await.ok(); + println!("\nShutting down..."); + } + } ExitCode::SUCCESS }) } diff --git a/crates/fastled-cli/src/lib.rs b/crates/fastled-cli/src/lib.rs index df542002..f70f1df6 100644 --- a/crates/fastled-cli/src/lib.rs +++ b/crates/fastled-cli/src/lib.rs @@ -64,13 +64,9 @@ pub fn run() -> ExitCode { return commands::run_internal_dwarf_smoke(&cli); } - if let Some(ref serve_dir) = cli.internal_serve_dir_headless { - return commands::serve_directory(serve_dir, false); - } - - // Handle --serve-dir natively with the Rust HTTP server (no Python needed). - if let Some(ref serve_dir) = cli.serve_dir { - return commands::serve_directory(serve_dir, true); + // Handle serve-dir modes natively with the Rust HTTP server. + if let Some((serve_dir, launch_viewer)) = serve_dir_request(&cli) { + return commands::serve_directory(serve_dir, launch_viewer); } if cli.install { @@ -138,6 +134,17 @@ pub fn run() -> ExitCode { ExitCode::FAILURE } +/// Map serve-dir CLI flags to `(directory, launch_viewer)`. +/// +/// `--internal-serve-dir-headless` is the no-UI serve path: it never launches +/// a viewer, so viewer-exit shutdown can never apply to it. +fn serve_dir_request(cli: &cli::Cli) -> Option<(&str, bool)> { + if let Some(ref dir) = cli.internal_serve_dir_headless { + return Some((dir, false)); + } + cli.serve_dir.as_deref().map(|dir| (dir, true)) +} + #[cfg(test)] mod tests { use super::*; @@ -198,6 +205,25 @@ mod tests { } } + #[test] + fn serve_dir_request_headless_never_launches_viewer() { + let mut cli = base_cli(); + cli.internal_serve_dir_headless = Some("some/dir".to_string()); + assert_eq!(serve_dir_request(&cli), Some(("some/dir", false))); + } + + #[test] + fn serve_dir_request_serve_dir_launches_viewer() { + let mut cli = base_cli(); + cli.serve_dir = Some("some/dir".to_string()); + assert_eq!(serve_dir_request(&cli), Some(("some/dir", true))); + } + + #[test] + fn serve_dir_request_none_without_serve_flags() { + assert_eq!(serve_dir_request(&base_cli()), None); + } + #[test] fn collect_debug_source_paths_finds_wasm_and_source_map_entries() { let temp = tempfile::tempdir().expect("tempdir"); diff --git a/crates/fastled-cli/src/viewer.rs b/crates/fastled-cli/src/viewer.rs index 7e439def..1431c592 100644 --- a/crates/fastled-cli/src/viewer.rs +++ b/crates/fastled-cli/src/viewer.rs @@ -148,6 +148,33 @@ impl ViewerProcess { pub fn pid(&self) -> u32 { self.child.id() } + + /// Non-blocking liveness probe: `true` while the viewer process is still + /// running, `false` once it has exited (window closed or crashed). + #[cfg(windows)] + pub fn is_alive(&mut self) -> bool { + process_handle_is_alive(self.process) + } + + /// Non-blocking liveness probe: `true` while the viewer process is still + /// running, `false` once it has exited (window closed or crashed). + /// + /// Reaping the child here is safe: the surviving + /// [`ContainedProcessGroup`] kill-on-drop is a best-effort `killpg`, so a + /// reaped leader does not break group cleanup. + #[cfg(not(windows))] + pub fn is_alive(&mut self) -> bool { + // An error from try_wait means we can no longer observe the child; + // treat it as dead so the CLI shuts down instead of running forever. + !matches!(self.child.try_wait(), Ok(Some(_)) | Err(_)) + } +} + +#[cfg(windows)] +fn process_handle_is_alive(process: windows_sys::Win32::Foundation::HANDLE) -> bool { + use windows_sys::Win32::Foundation::WAIT_TIMEOUT; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + unsafe { WaitForSingleObject(process, 0) == WAIT_TIMEOUT } } #[cfg(windows)] @@ -526,4 +553,69 @@ mod tests { assert_eq!(VIEWER_CREATION_FLAGS & 0x0800_0000, 0x0800_0000); assert_eq!(VIEWER_CREATION_FLAGS & 0x0000_0200, 0x0000_0200); } + + #[test] + #[cfg(windows)] + fn test_process_handle_liveness_alive_to_dead() { + use std::os::windows::io::AsRawHandle; + + // ping -n 5 keeps the child alive for several seconds. + let mut child = Command::new("ping") + .args(["-n", "5", "127.0.0.1"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn ping"); + let handle = child.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE; + + assert!( + process_handle_is_alive(handle), + "expected freshly spawned process to be alive" + ); + + child.kill().expect("kill ping"); + child.wait().expect("wait ping"); + + assert!( + !process_handle_is_alive(handle), + "expected exited process to be dead" + ); + } + + #[test] + #[cfg(not(windows))] + fn test_viewer_process_is_alive_alive_to_dead() { + let group = ContainedProcessGroup::new().expect("process group"); + let mut command = Command::new("sleep"); + command.arg("30"); + let stdio = SpawnStdio { + stdin: StdioSource::Null, + stdout: StdioSource::Null, + stderr: StdioSource::Null, + ..SpawnStdio::default() + }; + let child = group.spawn(&mut command, stdio).expect("spawn sleep"); + let mut viewer = ViewerProcess { + _group: group, + child, + }; + + assert!( + viewer.is_alive(), + "expected freshly spawned process to be alive" + ); + + viewer.child.kill().expect("kill sleep"); + + // The kill is asynchronous from the probe's perspective; poll briefly. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while viewer.is_alive() { + assert!( + std::time::Instant::now() < deadline, + "expected killed process to be observed dead within 5s" + ); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } }