From c5be696205d21755bc2b86b718070a67a0aeb274 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 25 Oct 2026 16:58:41 +0100 Subject: [PATCH] Windows: stop the children with Ctrl-Break in their own process groups (the engine, gateway and API handle it), so leleka down takes seconds instead of three grace periods; hidden mode hides the console instead of freeing it; no readiness summary after up --mode none Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/main.rs | 11 ++++++++++- crates/deploy/Cargo.toml | 2 +- crates/deploy/src/app.rs | 4 ++-- crates/deploy/src/supervisor.rs | 22 ++++++++++++++-------- crates/deploy/src/winfront.rs | 3 ++- crates/deploy/src/winservice.rs | 2 +- crates/deploy/src/winsys.rs | 17 ++++++++++++----- desktop-core/src/bin/leleka-daemon.rs | 16 +++++++++++++++- desktop-core/src/bin/leleka-inference.rs | 18 +++++++++++++++--- 9 files changed, 72 insertions(+), 23 deletions(-) diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index a76fead7..cd8cb762 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -1075,7 +1075,16 @@ async fn shutdown_signal() { _ = terminate.recv() => {}, } } - #[cfg(not(unix))] + #[cfg(windows)] + { + // Ctrl-Break is how `leleka run` stops its children on Windows (they run in their own process groups). + let mut break_signal = tokio::signal::windows::ctrl_break().expect("install Ctrl-Break handler"); + tokio::select! { + result = tokio::signal::ctrl_c() => { result.expect("install Ctrl-C handler"); }, + _ = break_signal.recv() => {}, + } + } + #[cfg(not(any(unix, windows)))] tokio::signal::ctrl_c() .await .expect("install Ctrl-C handler"); diff --git a/crates/deploy/Cargo.toml b/crates/deploy/Cargo.toml index 580b6e3a..4f1bf1b2 100644 --- a/crates/deploy/Cargo.toml +++ b/crates/deploy/Cargo.toml @@ -35,7 +35,7 @@ tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time rustix = { version = "=1.1.5", features = ["fs", "process", "stdio"] } [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_UI_WindowsAndMessaging"] } leleka-memory = { path = "../leleka-memory" } # The workspace forbids unsafe code; this crate denies it and lets exactly one module (`winsys`, Windows only) opt in. diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 4e580fc2..bf38af1a 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -47,12 +47,12 @@ fn home_dir() -> Option { /// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`). pub async fn main_native(mut args: Vec) -> i32 { - // `--hidden` (the logon task): no console window for this process and none for its children. + // `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it). if let Some(index) = args.iter().position(|a| a == "--hidden") { args.remove(index); crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed); #[cfg(windows)] - crate::winsys::detach_console(); + crate::winsys::hide_console(); } let var = env_var; let environment = Environment { diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index cbfe8d38..03fb1242 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -35,12 +35,11 @@ const LOG_ROTATE_BYTES: u64 = 64 << 20; /// Set by `--hidden` (the Windows logon task): the children get no console window. pub static HIDDEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// `CREATE_NO_WINDOW` for a child of a hidden supervisor (a no-op elsewhere). -pub fn no_window(command: &mut Command) { +/// Windows: the long-lived children (engine, gateway, API) get their own process group, so that Ctrl-C typed in the +/// supervisor's terminal reaches only the supervisor, which then stops them in order with Ctrl-Break (`interrupt`). No-op elsewhere. +pub fn own_group(command: &mut Command) { #[cfg(windows)] - if HIDDEN.load(std::sync::atomic::Ordering::Relaxed) { - command.creation_flags(0x0800_0000); - } + command.creation_flags(0x0000_0200); #[cfg(not(windows))] let _ = command; } @@ -554,7 +553,7 @@ impl Supervisor { Err(message) => return fail(1, message), }; let mut command = Command::new(program); - no_window(&mut command); + own_group(&mut command); command .args(args) .stdout(Stdio::from(out)) @@ -952,7 +951,6 @@ impl Supervisor { async fn cli(&self, args: &[&str]) -> Result<(bool, String), String> { let mut command = Command::new(self.paths.bin("leleka-cli")); - no_window(&mut command); command .arg("--config") .arg(self.paths.daemon_config()) @@ -1322,7 +1320,15 @@ fn interrupt(child: &Child) { } } -#[cfg(not(target_os = "linux"))] +#[cfg(windows)] +fn interrupt(child: &Child) { + // The child leads its own process group (`own_group`), so its pid is the group id Ctrl-Break is aimed at. + if let Some(pid) = child.id() { + let _ = crate::winsys::send_ctrl_break(pid); + } +} + +#[cfg(not(any(target_os = "linux", windows)))] fn interrupt(_child: &Child) {} #[cfg(test)] diff --git a/crates/deploy/src/winfront.rs b/crates/deploy/src/winfront.rs index 99a288b2..7d4439e3 100644 --- a/crates/deploy/src/winfront.rs +++ b/crates/deploy/src/winfront.rs @@ -344,7 +344,8 @@ async fn forward(command: &str, args: &[String]) -> i32 { } match status { Ok(status) => { - if command == "up" && status.success() && !json && !args.iter().any(|a| a == "--dry-run") { + let prepare_only = args.windows(2).any(|w| w[0] == "--mode" && w[1] == "none") || args.iter().any(|a| a == "--mode=none"); + if command == "up" && status.success() && !json && !prepare_only && !args.iter().any(|a| a == "--dry-run") { // A service started under systemd keeps running after `up` returns: say how to reach it. print_windows_summary(&session.bridge.distro, &state_dir, &api); } diff --git a/crates/deploy/src/winservice.rs b/crates/deploy/src/winservice.rs index fb84baf4..8c45ecef 100644 --- a/crates/deploy/src/winservice.rs +++ b/crates/deploy/src/winservice.rs @@ -229,7 +229,7 @@ pub async fn run_wsl(action: ServiceAction, bridge: &Bridge, hidden: bool) -> i3 ServiceAction::Hold => { if hidden { #[cfg(windows)] - crate::winsys::detach_console(); + crate::winsys::hide_console(); } let _ = bridge.capture("systemctl", &["--user", "start", WSL_UNIT]); // A wsl.exe process that never ends keeps the VM (and with it the unit) alive; it ends when the task is stopped. diff --git a/crates/deploy/src/winsys.rs b/crates/deploy/src/winsys.rs index e701c662..84739763 100644 --- a/crates/deploy/src/winsys.rs +++ b/crates/deploy/src/winsys.rs @@ -7,8 +7,9 @@ use windows_sys::Win32::{ Foundation::{CloseHandle, STILL_ACTIVE}, Security::Cryptography::{BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom}, Storage::FileSystem::GetDiskFreeSpaceExW, + UI::WindowsAndMessaging::{SW_HIDE, ShowWindow}, System::{ - Console::{CTRL_BREAK_EVENT, FreeConsole, GenerateConsoleCtrlEvent}, + Console::{CTRL_BREAK_EVENT, GenerateConsoleCtrlEvent, GetConsoleWindow}, Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION}, }, }; @@ -49,10 +50,16 @@ pub fn process_alive(pid: u32) -> bool { ok != 0 && code == STILL_ACTIVE as u32 } -/// Give up the console (the process was started by the logon task and must not show a window). -pub fn detach_console() { - // SAFETY: no arguments; a process without a console is a valid state. - unsafe { FreeConsole() }; +/// Hide the console window (the process was started by the logon task and must not show a window). The console itself stays: +/// the supervisor needs it to send Ctrl-Break to its children. +pub fn hide_console() { + // SAFETY: no arguments; a missing console window is a valid state (null handle). + unsafe { + let window = GetConsoleWindow(); + if !window.is_null() { + ShowWindow(window, SW_HIDE); + } + } } /// Send Ctrl-Break to the process group `group` (a child created with CREATE_NEW_PROCESS_GROUP): what a test or a tool diff --git a/desktop-core/src/bin/leleka-daemon.rs b/desktop-core/src/bin/leleka-daemon.rs index 2ba2920b..9f25bde9 100644 --- a/desktop-core/src/bin/leleka-daemon.rs +++ b/desktop-core/src/bin/leleka-daemon.rs @@ -35,7 +35,7 @@ async fn main() -> Result<(), Box> { tokio::pin!(serving); let result = tokio::select! { result = &mut serving => result, - _ = tokio::signal::ctrl_c() => { + _ = stop_signal() => { let _ = stop.send(()); // Dropping the bounded grace future closes stalled streams; their // RuntimeGeneration drop path requests cancellation without replay. @@ -50,3 +50,17 @@ async fn main() -> Result<(), Box> { result?; Ok(()) } + +/// Ctrl-C everywhere; on Windows also Ctrl-Break, which is how `leleka run` asks a child (they run in their own process +/// groups, where Ctrl-C is not delivered) to drain and stop. +async fn stop_signal() { + #[cfg(windows)] + if let Ok(mut break_signal) = tokio::signal::windows::ctrl_break() { + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = break_signal.recv() => {} + } + return; + } + let _ = tokio::signal::ctrl_c().await; +} diff --git a/desktop-core/src/bin/leleka-inference.rs b/desktop-core/src/bin/leleka-inference.rs index cc9ee861..4d7bbb34 100644 --- a/desktop-core/src/bin/leleka-inference.rs +++ b/desktop-core/src/bin/leleka-inference.rs @@ -249,13 +249,25 @@ async fn main() -> Result<(), Box> { // Transport starts closed for model admission. Loading is an explicit typed // lifecycle command; successful configuration parsing is never model ready. server - .serve(listener, async { - let _ = tokio::signal::ctrl_c().await; - }) + .serve(listener, stop_signal()) .await?; Ok(()) } +/// Ctrl-C everywhere; on Windows also Ctrl-Break, which is how `leleka run` asks a child (they run in their own process +/// groups, where Ctrl-C is not delivered) to drain and stop. +async fn stop_signal() { + #[cfg(windows)] + if let Ok(mut break_signal) = tokio::signal::windows::ctrl_break() { + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = break_signal.recv() => {} + } + return; + } + let _ = tokio::signal::ctrl_c().await; +} + /// Remove `--name VALUE` from `args` and return the value (`None` if absent, an error if it is repeated or has none). fn take_option(args: &mut Vec, name: &str) -> Result, &'static str> { let Some(position) = args.iter().position(|arg| arg == name) else {