From 1be8a4caeaed1bd48a8feb8f249bbe6c90042583 Mon Sep 17 00:00:00 2001 From: RobertTGreat Date: Sat, 24 Oct 2026 18:34:08 +0100 Subject: [PATCH 1/2] fix(launcher): defer hardware probes and hide Windows consoles Collect performance-report hardware after the first frame and preserve logs, input and CLI pipes while suppressing background terminal windows. Co-Authored-By: OpenAI Codex (GPT-6.1 Sol) --- crates/horizon-bench/src/hardware.rs | 10 +- crates/horizon-bench/src/lib.rs | 8 +- crates/horizon-prepare/src/java.rs | 22 ++++- crates/horizon-server/src/engine.rs | 6 +- crates/horizon-server/src/main.rs | 1 + crates/horizon-server/src/process.rs | 18 ++++ crates/horizon-server/src/service.rs | 4 +- crates/horizon-server/src/update.rs | 7 +- crates/horizon-telemetry/src/system.rs | 13 ++- launcher/README.md | 6 ++ launcher/src/agents.rs | 4 +- launcher/src/agents_page.rs | 2 +- launcher/src/backend.rs | 15 +-- launcher/src/cli_tools.rs | 2 +- launcher/src/console.rs | 48 ++++++++++ launcher/src/game_tools.rs | 4 +- launcher/src/lib.rs | 1 + launcher/src/main.rs | 7 ++ launcher/src/perf.rs | 97 +++++++++++++++++++- launcher/src/process.rs | 22 +++++ launcher/src/servers.rs | 8 +- launcher/src/sources.rs | 2 +- launcher/src/tailscale.rs | 7 +- launcher/tests/hidden_processes.rs | 116 ++++++++++++++++++++++++ launcher/tests/startup.rs | 88 ++++++++++++++++++ launcher/tests/support/console_probe.rs | 73 +++++++++++++++ launcher/tests/support/mod.rs | 29 ++++++ 27 files changed, 570 insertions(+), 50 deletions(-) create mode 100644 crates/horizon-server/src/process.rs create mode 100644 launcher/src/console.rs create mode 100644 launcher/src/process.rs create mode 100644 launcher/tests/hidden_processes.rs create mode 100644 launcher/tests/startup.rs create mode 100644 launcher/tests/support/console_probe.rs create mode 100644 launcher/tests/support/mod.rs diff --git a/crates/horizon-bench/src/hardware.rs b/crates/horizon-bench/src/hardware.rs index 17e460bed..6b91202ad 100644 --- a/crates/horizon-bench/src/hardware.rs +++ b/crates/horizon-bench/src/hardware.rs @@ -174,7 +174,15 @@ pub fn cpu_seconds(pid: u32) -> Option { } fn output(program: &str, args: &[&str]) -> Option { - let out = Command::new(program).args(args).output().ok()?; + let mut command = Command::new(program); + command.args(args); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let out = command.output().ok()?; let text = String::from_utf8(out.stdout).ok()?.trim().to_owned(); (out.status.success() && !text.is_empty()).then_some(text) } diff --git a/crates/horizon-bench/src/lib.rs b/crates/horizon-bench/src/lib.rs index bdc885af1..ae70977bd 100644 --- a/crates/horizon-bench/src/lib.rs +++ b/crates/horizon-bench/src/lib.rs @@ -245,13 +245,19 @@ pub struct Report { impl Report { /// An empty report for this machine, created now. pub fn new(kind: Kind, app: App) -> Report { + Self::with_hardware(kind, app, Hardware::detect()) + } + + /// Starts a report using supplied hardware, without running system probes. + /// Interactive apps can collect the remaining machine details after their first frame. + pub fn with_hardware(kind: Kind, app: App, hardware: Hardware) -> Report { Report { format: FORMAT.to_owned(), version: VERSION, kind, created: utc_now(), app, - hardware: Hardware::detect(), + hardware, conditions: Conditions::default(), metrics: BTreeMap::new(), frames: Vec::new(), diff --git a/crates/horizon-prepare/src/java.rs b/crates/horizon-prepare/src/java.rs index a159fb055..78530486c 100644 --- a/crates/horizon-prepare/src/java.rs +++ b/crates/horizon-prepare/src/java.rs @@ -1,6 +1,7 @@ //! The JDK that compiles and runs the vanilla exporters. They call Mojang's own code, so they //! stay Java; everything around them is here. +use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -13,6 +14,19 @@ pub struct Jdk { const TIMEOUT: Duration = Duration::from_secs(3600); +/// Exporters and JDK probes write to pipes or log files, never to a new terminal. +fn command(program: impl AsRef) -> Command { + let mut command = Command::new(program); + command.stdin(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + command +} + fn executable(dir: &Path, name: &str) -> PathBuf { dir.join(if cfg!(windows) { format!("{name}.exe") @@ -29,7 +43,7 @@ fn on_path(name: &str) -> Option { /// The major version `javac -version` reports ("javac 25.0.1" → 25; "javac 1.8.0" → 8). fn javac_major(javac: &Path) -> Result { - let output = Command::new(javac) + let output = command(javac) .arg("-version") .stdin(Stdio::null()) .output() @@ -183,7 +197,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result { candidates.push((javac, java, "PATH")); } if cfg!(target_os = "macos") { - if let Ok(out) = Command::new("/usr/libexec/java_home") + if let Ok(out) = command("/usr/libexec/java_home") .args(["-v", &major.to_string()]) .stderr(Stdio::null()) .output() @@ -260,7 +274,7 @@ impl Jdk { /// `javac --release -proc:none` with Python's `subprocess.run(..., check=True, /// stdout=log, stderr=STDOUT, timeout=3600)`. pub fn javac(&self, major: i64, args: &[String], log: &fs::File) -> Result<(), String> { - let mut command = Command::new(&self.javac); + let mut command = command(&self.javac); command .args(["--release", &major.to_string(), "-proc:none"]) .args(args); @@ -268,7 +282,7 @@ impl Jdk { } pub fn java(&self, args: &[String], cwd: Option<&Path>, log: &fs::File) -> Result<(), String> { - let mut command = Command::new(&self.java); + let mut command = command(&self.java); command.args(args); if let Some(dir) = cwd { command.current_dir(dir); diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs index 051ae77f0..fd7c86321 100644 --- a/crates/horizon-server/src/engine.rs +++ b/crates/horizon-server/src/engine.rs @@ -68,7 +68,8 @@ pub fn program_in( /// system can't load the program, as on a Linux without the ALSA and udev libraries the full game links /// (the server build doesn't). The reason, with what to install. pub fn check_starts(program: &Path) -> Result<(), String> { - let output = Command::new(program) + let mut command = crate::process::command(program); + let output = command .arg("--help") .stdin(Stdio::null()) .stdout(Stdio::null()) @@ -176,7 +177,8 @@ pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result) -> Command { + let mut command = Command::new(program); + configure(&mut command); + command +} + +fn configure(command: &mut Command) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); + } + #[cfg(not(windows))] + let _ = command; +} diff --git a/crates/horizon-server/src/service.rs b/crates/horizon-server/src/service.rs index 6e6d59f23..96b9f218f 100644 --- a/crates/horizon-server/src/service.rs +++ b/crates/horizon-server/src/service.rs @@ -178,7 +178,7 @@ fn systemd_path(service: &str, system: bool) -> Result { } fn run(program: &str, args: &[&str]) -> Result<(), String> { - let status = Command::new(program) + let status = crate::process::command(program) .args(args) .status() .map_err(|e| format!("{program}: {e}"))?; @@ -191,7 +191,7 @@ fn run(program: &str, args: &[&str]) -> Result<(), String> { /// A step that may fail harmlessly (stopping what isn't running): its output would only alarm. fn quiet(program: &str, args: &[&str]) { - let _ = Command::new(program) + let _ = crate::process::command(program) .args(args) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) diff --git a/crates/horizon-server/src/update.rs b/crates/horizon-server/src/update.rs index cbcfe637e..8c87c66bc 100644 --- a/crates/horizon-server/src/update.rs +++ b/crates/horizon-server/src/update.rs @@ -10,7 +10,6 @@ use serde_json::{Value, json}; use std::{ io::Read, path::{Path, PathBuf}, - process::Command, time::{Duration, Instant}, }; @@ -206,7 +205,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> { if link.exists() || link.symlink_metadata().is_ok() { std::fs::remove_dir(link)?; } - let status = Command::new("cmd") + let status = crate::process::command("cmd") .arg("/C") .arg("mklink") .arg("/J") @@ -474,7 +473,7 @@ pub fn unpack(install: &Install, archive: &Path, tag: &str) -> Result Option { - let out = std::process::Command::new(program) - .args(args) - .output() - .ok()?; + let mut command = std::process::Command::new(program); + command.args(args); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let out = command.output().ok()?; let text = String::from_utf8_lossy(&out.stdout).trim().to_owned(); (out.status.success() && !text.is_empty()).then_some(text) } diff --git a/launcher/README.md b/launcher/README.md index cf968f93c..d2b78daea 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -97,6 +97,12 @@ page `servers.json` (the list), `servers//` (the servers created there) an Long pages, dialogs, the server console and data previews have a visible scrollbar when their content overflows. Drag the thumb or click the track to navigate without a mouse wheel. +On Windows, desktop launches and background tools run without terminal windows. Preparation +and server logs still reach the launcher, and CLI commands keep their terminal or redirected +input and output, including MCP. +Hardware details for performance reports are collected in the background after the first +frame, so Windows hardware queries do not delay the window opening. + ## Updates The launcher looks for a newer Horizon release when it starts and every 30 minutes while it diff --git a/launcher/src/agents.rs b/launcher/src/agents.rs index 0cc012b43..2baf198c6 100644 --- a/launcher/src/agents.rs +++ b/launcher/src/agents.rs @@ -122,8 +122,8 @@ pub fn locate(program: &str) -> std::path::PathBuf { /// Settings page's "Test the connection". pub fn self_test(exe: &Path) -> Result { use std::io::Write; - use std::process::{Command, Stdio}; - let mut child = Command::new(exe) + use std::process::Stdio; + let mut child = crate::process::command(exe) .arg("mcp") .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/launcher/src/agents_page.rs b/launcher/src/agents_page.rs index ecb393bf0..e53d6550a 100644 --- a/launcher/src/agents_page.rs +++ b/launcher/src/agents_page.rs @@ -207,7 +207,7 @@ impl Launcher { /// Runs a client's add command; (went well, what it said). fn run_add(program: &str, args: &[String]) -> (bool, String) { - match std::process::Command::new(agents::locate(program)) + match horizon_launcher::process::command(agents::locate(program)) .args(args) .output() { diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 9612bda2b..104a086a5 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -943,7 +943,7 @@ pub fn default_minecraft_dir() -> Option { } fn found(program: &str, arg: &str) -> bool { - Command::new(program) + crate::process::command(program) .arg(arg) .stdout(Stdio::null()) .stderr(Stdio::null()) @@ -1239,14 +1239,14 @@ pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) { let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref() == Some(horizon_prepare::SOURCES_SHA256); let binary = preparer_binary(&dir).filter(|binary| { - !own && Command::new(binary) + !own && crate::process::command(binary) .arg("--help") .output() .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds")) }); log("Copying the sounds from your Minecraft install".into()); let result = match binary { - Some(binary) => Command::new(binary) + Some(binary) => crate::process::command(binary) .current_dir(&dir) .arg("sounds") .arg("--root") @@ -1877,16 +1877,10 @@ fn parse_version_output(out: &str) -> Option<&str> { /// The version of the launcher binary now at `path`, which is not this process's once another /// update (the command line, another window) has replaced the file. fn installed_launcher_version(path: &Path) -> Option { - let mut cmd = Command::new(path); + let mut cmd = crate::process::command(path); cmd.arg("--version") .stdin(Stdio::null()) .stderr(Stdio::null()); - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - cmd.creation_flags(CREATE_NO_WINDOW); - } let out = cmd.output().ok()?; parse_version_output(&String::from_utf8_lossy(&out.stdout)).map(String::from) } @@ -2220,6 +2214,7 @@ impl Running { } pub fn spawn(job: Job, mut cmd: Command, tx: Sender) -> Result { + crate::process::hide_console(&mut cmd); let mut child = cmd .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index ff351f4b3..e420576b5 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -210,7 +210,7 @@ impl Tool { pub fn call(&self, args: &Value) -> Result { let words = self.argv(args)?; let exe = std::env::current_exe().map_err(|e| e.to_string())?; - let out = std::process::Command::new(exe) + let out = horizon_launcher::process::command(exe) .arg("--json") .args(&words) .stdin(std::process::Stdio::null()) diff --git a/launcher/src/console.rs b/launcher/src/console.rs new file mode 100644 index 000000000..b12067139 --- /dev/null +++ b/launcher/src/console.rs @@ -0,0 +1,48 @@ +//! A desktop launch has no console; CLI commands can use the invoking terminal or pipes. +#[cfg(windows)] +pub fn attach_for_cli() -> std::io::Result<()> { + use std::ffi::c_void; + + const ATTACH_PARENT_PROCESS: u32 = u32::MAX; + const STD_INPUT_HANDLE: u32 = -10_i32 as u32; + const STD_OUTPUT_HANDLE: u32 = -11_i32 as u32; + const STD_ERROR_HANDLE: u32 = -12_i32 as u32; + const INVALID_HANDLE_VALUE: isize = -1; + + #[link(name = "kernel32")] + extern "system" { + fn AttachConsole(process_id: u32) -> i32; + fn GetStdHandle(kind: u32) -> *mut c_void; + fn SetStdHandle(kind: u32, handle: *mut c_void) -> i32; + } + + if std::env::args_os().nth(1).is_none() { + return Ok(()); + } + // Attaching can replace the standard handles. Keep inherited pipes/files intact for + // JSON output, MCP and redirected logs, while filling missing handles from the terminal. + // SAFETY: These APIs take numeric constants and opaque handles returned by Windows. + // No handles are closed or dereferenced, and this runs before any worker starts. + unsafe { + let handles = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] + .map(|kind| (kind, GetStdHandle(kind))); + if AttachConsole(ATTACH_PARENT_PROCESS) == 0 { + // No parent console (for example, an MCP client), or already attached. + return Ok(()); + } + for (kind, handle) in handles { + if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE { + continue; + } + if SetStdHandle(kind, handle) == 0 { + return Err(std::io::Error::last_os_error()); + } + } + } + Ok(()) +} + +#[cfg(not(windows))] +pub fn attach_for_cli() -> std::io::Result<()> { + Ok(()) +} diff --git a/launcher/src/game_tools.rs b/launcher/src/game_tools.rs index 3504a531f..efa219396 100644 --- a/launcher/src/game_tools.rs +++ b/launcher/src/game_tools.rs @@ -6,7 +6,7 @@ use horizon_launcher::backend; use serde_json::{json, Value}; use std::io::{BufRead, BufReader, Write}; use std::path::PathBuf; -use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::process::{Child, ChildStdin, ChildStdout, Stdio}; pub const PREFIX: &str = "game_"; @@ -61,7 +61,7 @@ impl GameTools { if !ctl.exists() { return Err(format!("{tag} has no {CTL}")); } - let mut child = Command::new(&ctl) + let mut child = horizon_launcher::process::command(&ctl) .arg("--socket") .arg(socket_path()) .arg("mcp") diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index aa8aec7f2..4b5c164fd 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -9,6 +9,7 @@ pub mod game_app; pub mod heads; pub mod modpacks; pub mod mojang; +pub mod process; pub mod servers; pub mod signed; pub mod sources; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index db2309dd6..9d5d36b60 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1,12 +1,15 @@ //! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft, //! and starts the client or a dedicated server. +#![cfg_attr(target_os = "windows", windows_subsystem = "windows")] + mod agents_page; mod art; mod blocks; mod cli; mod cli_tools; mod collection; +mod console; mod cull; mod game_tools; mod internet; @@ -3497,6 +3500,10 @@ fn menus() -> Vec { } fn main() { + if let Err(error) = console::attach_for_cli() { + eprintln!("Could not restore the launcher's terminal streams: {error}"); + std::process::exit(1); + } perf::process_started(); backend::exe_path(); if let Some(code) = cli::run() { diff --git a/launcher/src/perf.rs b/launcher/src/perf.rs index f46393542..7ecd0136c 100644 --- a/launcher/src/perf.rs +++ b/launcher/src/perf.rs @@ -9,10 +9,11 @@ use std::collections::BTreeMap; use std::path::PathBuf; +use std::sync::mpsc::{self, Receiver, TryRecvError}; use std::sync::OnceLock; use std::time::{Duration, Instant}; -use horizon_bench::{App, Frames, Kind, Report}; +use horizon_bench::{App, Frames, Hardware, Kind, Report}; /// The first thing `main` does; every start time counts from here. pub fn process_started() -> Instant { @@ -35,14 +36,36 @@ pub struct Perf { dirty: bool, /// Off for the windows `horizon-launcher benchmark` starts: they report to it instead. log: bool, + /// Machine probes run after the first frame, never while opening the window. + hardware: Option>, +} + +#[derive(Debug)] +struct Machine { + hardware: Hardware, + power: Option, + load_average: Option, +} + +impl Machine { + fn detect() -> Self { + Self { + hardware: Hardware::detect(), + power: horizon_bench::power_source().map(str::to_owned), + load_average: horizon_bench::load_average(), + } + } } impl Perf { pub fn new(scenario: &str) -> Perf { - let mut report = Report::new(Kind::Launcher, app()); + let hardware = Hardware { + os: std::env::consts::OS.to_owned(), + arch: std::env::consts::ARCH.to_owned(), + ..Hardware::default() + }; + let mut report = Report::with_hardware(Kind::Launcher, app(), hardware); report.conditions.scenario = Some(scenario.to_owned()); - report.conditions.power = horizon_bench::power_source().map(str::to_owned); - report.conditions.load_avg_1m = horizon_bench::load_average(); let path = crate::backend::data_dir().join("benchmarks").join(format!( "launcher-{}-{scenario}.json", report @@ -61,6 +84,7 @@ impl Perf { saved: Instant::now(), dirty: false, log: true, + hardware: None, }; if let Some(bytes) = binary_bytes() { perf.record("launcher.binary_bytes", bytes); @@ -89,6 +113,12 @@ impl Perf { if first { self.first_frame = Some(now); self.record_since("launcher.start_ms", process_started()); + let (sender, receiver) = mpsc::channel(); + self.hardware = Some(receiver); + std::thread::spawn(move || { + // The window may close before the optional report details finish. + let _ = sender.send(Machine::detect()); + }); } else if let Some(gap) = self.last_frame.map(|t| now - t).filter(|g| *g < IDLE_GAP) { self.ui_frames.push(gap.as_secs_f32() * 1000.0); } @@ -102,6 +132,7 @@ impl Perf { /// Samples memory and writes the report when something changed, at most every few seconds. pub fn tick(&mut self) { + self.poll_hardware(); if self.saved.elapsed() < Duration::from_secs(5) { return; } @@ -118,6 +149,7 @@ impl Perf { } pub fn report(&mut self) -> &Report { + self.poll_hardware(); for (name, values) in &self.values { self.report.metric(name, values); } @@ -128,6 +160,28 @@ impl Perf { &self.report } + fn poll_hardware(&mut self) { + let Some(receiver) = &self.hardware else { + return; + }; + match receiver.try_recv() { + Ok(machine) => { + self.report.hardware = machine.hardware; + self.report.conditions.power = machine.power; + self.report.conditions.load_avg_1m = machine.load_average; + self.hardware = None; + self.dirty = true; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => { + self.hardware = None; + eprintln!( + "The launcher could not collect its performance report's machine details." + ); + } + } + } + pub fn save(&mut self) { self.dirty = false; if !self.log { @@ -381,6 +435,41 @@ fn binary_bytes() -> Option { mod tests { use super::*; + #[test] + fn performance_tracking_starts_without_hardware_probes() { + let mut perf = Perf::new("test"); + perf.keep_local_log(false); + assert!(perf.hardware.is_none()); + assert_eq!(perf.report.hardware.os, std::env::consts::OS); + assert!(perf.report.hardware.cpu.is_none()); + assert!(perf.report.conditions.power.is_none()); + } + + #[test] + fn background_hardware_details_preserve_recorded_metrics() { + let mut perf = Perf::new("test"); + perf.keep_local_log(false); + perf.record("launcher.start_ms", 125.); + let (sender, receiver) = mpsc::channel(); + perf.hardware = Some(receiver); + assert_eq!(perf.report().metrics["launcher.start_ms"].mean, 125.); + sender + .send(Machine { + hardware: Hardware { + cpu: Some("Detected CPU".into()), + ..Hardware::default() + }, + power: Some("ac".into()), + load_average: Some(0.5), + }) + .unwrap(); + let report = perf.report(); + assert_eq!(report.hardware.cpu.as_deref(), Some("Detected CPU")); + assert_eq!(report.conditions.power.as_deref(), Some("ac")); + assert_eq!(report.metrics["launcher.start_ms"].mean, 125.); + assert!(perf.hardware.is_none()); + } + #[test] fn the_first_frame_is_the_start_and_close_frames_are_ui_frames() { let mut perf = Perf::new("test"); diff --git a/launcher/src/process.rs b/launcher/src/process.rs new file mode 100644 index 000000000..cd224b686 --- /dev/null +++ b/launcher/src/process.rs @@ -0,0 +1,22 @@ +//! Background commands keep their configured streams without opening Windows consoles. +use std::ffi::OsStr; +use std::process::Command; + +/// Builds a background command. Callers still choose how to capture its input and output. +pub fn command(program: impl AsRef) -> Command { + let mut command = Command::new(program); + hide_console(&mut command); + command +} + +/// Hides a background command's console on Windows, preserving its configured standard streams. +pub fn hide_console(command: &mut Command) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + #[cfg(not(windows))] + let _ = command; +} diff --git a/launcher/src/servers.rs b/launcher/src/servers.rs index 49ef05d66..264ccb149 100644 --- a/launcher/src/servers.rs +++ b/launcher/src/servers.rs @@ -245,7 +245,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> { #[cfg(windows)] { let _ = fs::remove_dir(link); - let status = Command::new("cmd") + let status = crate::process::command("cmd") .args(["/C", "mklink", "/J"]) .arg(link) .arg(target) @@ -266,10 +266,8 @@ pub fn command(dir: &Path, args: &[&str]) -> Result { let program = program().ok_or( "The server programs aren't set up yet: create a server, or press Prepare on its page.", )?; - let mut cmd = Command::new(program); + let mut cmd = crate::process::command(program); cmd.arg("--dir").arg(dir).args(args); - #[cfg(windows)] - std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW Ok(cmd) } @@ -752,7 +750,7 @@ pub fn lan_address() -> Option { pub fn service_installed(dir: &Path) -> bool { if cfg!(windows) { let name = format!("horizon-server-{}", service_suffix(dir)); - return Command::new("schtasks") + return crate::process::command("schtasks") .args(["/Query", "/TN", &name]) .stdout(Stdio::null()) .stderr(Stdio::null()) diff --git a/launcher/src/sources.rs b/launcher/src/sources.rs index 864e6bc73..b27b8417b 100644 --- a/launcher/src/sources.rs +++ b/launcher/src/sources.rs @@ -488,7 +488,7 @@ fn make_link(target: &Path, link: &Path) -> std::io::Result<()> { arg.push("\""); arg }; - let status = std::process::Command::new("cmd") + let status = crate::process::command("cmd") .args(["/C", "mklink", "/J"]) .raw_arg(quoted(link)) .raw_arg(quoted(target)) diff --git a/launcher/src/tailscale.rs b/launcher/src/tailscale.rs index 683ff0aab..b0c20d3bc 100644 --- a/launcher/src/tailscale.rs +++ b/launcher/src/tailscale.rs @@ -126,13 +126,8 @@ pub fn status_of(cli: Option) -> State { let Some(cli) = cli else { return State::Missing; }; - let mut command = Command::new(&cli); + let mut command = crate::process::command(&cli); command.args(["status", "--json"]); - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW - } let out = match command.output() { Ok(out) => out, Err(e) => return State::Off(e.to_string()), diff --git a/launcher/tests/hidden_processes.rs b/launcher/tests/hidden_processes.rs new file mode 100644 index 000000000..c7da90ea9 --- /dev/null +++ b/launcher/tests/hidden_processes.rs @@ -0,0 +1,116 @@ +//! Windows background processes must keep logs, input and exit status without a console. +#![cfg(windows)] + +mod support; +use horizon_launcher::{ + backend::{self, Job, Msg}, + process, +}; +use std::{fs, path::Path, sync::mpsc, time::Duration}; +use support::console_probe as probe; + +fn logged_child(fail: bool) -> (Vec, Result<(), String>) { + let (sender, receiver) = mpsc::channel(); + let mut command = std::process::Command::new(probe()); + if fail { + command.arg("--fail"); + } + let mut child = backend::spawn(Job::Prepare, command, sender).unwrap(); + child.send("input reaches the child"); + let mut lines = Vec::new(); + loop { + match receiver.recv_timeout(Duration::from_secs(10)).unwrap() { + Msg::Line(Job::Prepare, line) => lines.push(line), + Msg::Exit(Job::Prepare, result) => return (lines, result), + _ => panic!("unexpected job message"), + } + } +} + +#[test] +fn hidden_children_keep_stdout_stderr_stdin_and_success() { + let (lines, result) = logged_child(false); + assert!(result.is_ok(), "{result:?}"); + for expected in [ + "console_window_visible=false", + "stdout is captured", + "stderr is captured", + "stdin=input reaches the child", + ] { + assert!( + lines.iter().any(|line| line == expected), + "missing {expected}: {lines:?}" + ); + } +} + +#[test] +fn hidden_children_report_failure_and_keep_their_logs() { + let (lines, result) = logged_child(true); + assert!(result.unwrap_err().contains('7')); + assert!(lines.iter().any(|line| line == "stderr is captured")); +} + +#[test] +fn exporters_write_to_their_log_file_without_a_console() { + let root = probe().parent().unwrap(); + let path = root.join("exporter.log"); + let log = fs::File::create(&path).unwrap(); + let jdk = horizon_prepare::java::Jdk { + java: probe().into(), + javac: probe().into(), + }; + jdk.java(&[], Some(root), &log).unwrap(); + let output = fs::read_to_string(path).unwrap(); + for expected in [ + "console_window_visible=false", + "stdout is captured", + "stderr is captured", + ] { + assert!(output.contains(expected), "missing {expected}: {output}"); + } +} + +#[test] +fn cli_keeps_redirected_stdout_and_stderr() { + let executable = env!("CARGO_BIN_EXE_horizon-launcher"); + let version = process::command(executable) + .arg("--version") + .output() + .unwrap(); + assert!(version.status.success()); + assert!(String::from_utf8_lossy(&version.stdout).starts_with("horizon-launcher ")); + let invalid = process::command(executable) + .arg("--unknown-option") + .output() + .unwrap(); + assert!(!invalid.status.success()); + assert!(String::from_utf8_lossy(&invalid.stderr).contains("--unknown-option")); +} + +#[test] +fn mcp_keeps_its_stdio_transport() { + let executable = Path::new(env!("CARGO_BIN_EXE_horizon-launcher")); + assert!(horizon_launcher::agents::self_test(executable).unwrap() > 0); +} + +#[test] +fn desktop_executable_uses_the_windows_gui_subsystem() { + const PE_HEADER_POINTER: usize = 0x3c; + const PE_OPTIONAL_HEADER_OFFSET: usize = 24; + const SUBSYSTEM_OFFSET: usize = 68; + const WINDOWS_GUI_SUBSYSTEM: u16 = 2; + + let executable = fs::read(env!("CARGO_BIN_EXE_horizon-launcher")).unwrap(); + let header = u32::from_le_bytes( + executable[PE_HEADER_POINTER..PE_HEADER_POINTER + 4] + .try_into() + .unwrap(), + ) as usize; + assert_eq!(&executable[header..header + 4], b"PE\0\0"); + let subsystem = header + PE_OPTIONAL_HEADER_OFFSET + SUBSYSTEM_OFFSET; + assert_eq!( + u16::from_le_bytes(executable[subsystem..subsystem + 2].try_into().unwrap()), + WINDOWS_GUI_SUBSYSTEM + ); +} diff --git a/launcher/tests/startup.rs b/launcher/tests/startup.rs new file mode 100644 index 000000000..776d8ef15 --- /dev/null +++ b/launcher/tests/startup.rs @@ -0,0 +1,88 @@ +//! Full launcher startup against instrumented Windows hardware probes. +#![cfg(windows)] + +mod support; +use std::{ + fs, + path::{Path, PathBuf}, + process::{Child, Output, Stdio}, + time::{Duration, Instant}, +}; + +fn fixture() -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-startup-{}", std::process::id())); + for folder in ["game/telemetry", "launcher", "data", "config", "probes"] { + fs::create_dir_all(root.join(folder)).unwrap(); + } + fs::write(root.join("launcher/settings.json"), r#"{"skip_opening":true,"install_new_versions":false,"desktop_entry":false,"ping_notice_seen":true}"#).unwrap(); + let consent = serde_json::json!({"version":horizon_telemetry::CONSENT_VERSION,"choices":{}}); + fs::write( + root.join("game/telemetry/consent.json"), + consent.to_string(), + ) + .unwrap(); + fs::copy(support::console_probe(), root.join("probes/powershell.exe")).unwrap(); + root +} + +fn launch(root: &Path) -> Child { + let inherited_path = std::env::var_os("PATH").unwrap(); + let paths = std::iter::once(root.join("probes")).chain(std::env::split_paths(&inherited_path)); + horizon_launcher::process::command(env!("CARGO_BIN_EXE_horizon-launcher")) + .current_dir(root) + .env("PATH", std::env::join_paths(paths).unwrap()) + .env("HORIZON_HOME", root.join("game")) + .env("HORIZON_LAUNCHER_HOME", root.join("launcher")) + .env("XDG_DATA_HOME", root.join("data")) + .env("XDG_CONFIG_HOME", root.join("config")) + .env("HORIZON_LAUNCHER_NO_SELF_UPDATE", "1") + .env("HORIZON_NO_AUDIO", "1") + .env("HORIZON_TELEMETRY_URL", "off") + .env("HORIZON_STARTUP_PROBE_LOG", root.join("probes.log")) + .env("HORIZON_LAUNCHER_BENCH", root.join("timing.json")) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() +} + +fn wait_for_exit(mut child: Child, root: &Path) -> Output { + let deadline = Instant::now() + Duration::from_secs(30); + while child.try_wait().unwrap().is_none() { + if Instant::now() >= deadline { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("launcher startup timed out: {}", root.display()); + } + std::thread::sleep(Duration::from_millis(20)); + } + child.wait_with_output().unwrap() +} + +#[test] +#[ignore = "requires an interactive Windows desktop and graphics adapter"] +fn hardware_probes_run_hidden_after_the_first_frame() { + let root = fixture(); + let output = wait_for_exit(launch(&root), &root); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let timing: serde_json::Value = + serde_json::from_slice(&fs::read(root.join("timing.json")).unwrap()).unwrap(); + let first_frame = timing["first_frame_epoch_ms"].as_f64().unwrap().floor(); + let probes = fs::read_to_string(root.join("probes.log")).unwrap(); + // Rust resolves cmd.exe to the system directory, so instrument the seven PowerShell + // probes, which exercise both shared helpers (the cmd probes use those same helpers). + const POWERSHELL_PROBES: usize = 7; + assert_eq!(probes.lines().count(), POWERSHELL_PROBES, "{probes}"); + for probe in probes.lines() { + let fields: Vec<_> = probe.split('|').collect(); + assert!( + fields[0].parse::().unwrap() >= first_frame, + "probe blocked startup: {probe}" + ); + assert_eq!(fields[1], "false", "probe opened a terminal: {probe}"); + } +} diff --git a/launcher/tests/support/console_probe.rs b/launcher/tests/support/console_probe.rs new file mode 100644 index 000000000..1ff16a10b --- /dev/null +++ b/launcher/tests/support/console_probe.rs @@ -0,0 +1,73 @@ +//! A real Windows console program used to check hidden children and their streams. +use std::ffi::c_void; +use std::io; + +fn hardware_probe(visible: bool) -> bool { + let Some(path) = std::env::var_os("HORIZON_STARTUP_PROBE_LOG") else { + return false; + }; + use std::io::Write; + let arguments = std::env::args().skip(1).collect::>().join(" "); + let program = std::env::current_exe().unwrap(); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .unwrap(); + writeln!( + log, + "{timestamp}|{visible}|{}", + program.file_name().unwrap().to_string_lossy() + ) + .unwrap(); + // Slow probes make a synchronous startup regression visible without relying on WMI speed. + std::thread::sleep(std::time::Duration::from_millis(100)); + let responses = [ + ("TotalPhysicalMemory", "17179869184"), + ("NumberOfCores", "8"), + ("MaxClockSpeed", "3600"), + ("BatteryStatus", "2"), + ("Win32_Battery", "0"), + ]; + let response = responses + .iter() + .find_map(|&(query, response)| arguments.contains(query).then_some(response)) + .unwrap_or("Microsoft Windows [Version 10.0.26100]"); + println!("{response}"); + true +} + +#[link(name = "kernel32")] +extern "system" { + fn GetConsoleWindow() -> *mut c_void; +} + +#[link(name = "user32")] +extern "system" { + fn IsWindowVisible(window: *mut c_void) -> i32; +} + +fn main() { + // A console connection can exist without a terminal window, including in ConPTY. + // SAFETY: The opaque window handle comes from Windows and is only queried, never changed. + let visible = unsafe { + let window = GetConsoleWindow(); + !window.is_null() && IsWindowVisible(window) != 0 + }; + if hardware_probe(visible) { + return; + } + println!("console_window_visible={visible}"); + println!("stdout is captured"); + eprintln!("stderr is captured"); + let mut input = String::new(); + io::stdin().read_line(&mut input).unwrap(); + println!("stdin={}", input.trim()); + if std::env::args().any(|argument| argument == "--fail") { + std::process::exit(7); + } +} diff --git a/launcher/tests/support/mod.rs b/launcher/tests/support/mod.rs new file mode 100644 index 000000000..b5a72d115 --- /dev/null +++ b/launcher/tests/support/mod.rs @@ -0,0 +1,29 @@ +use horizon_launcher::process; +use std::{ + fs, + path::{Path, PathBuf}, + sync::OnceLock, +}; + +pub fn console_probe() -> &'static Path { + static PROBE: OnceLock = OnceLock::new(); + PROBE.get_or_init(|| { + let root = + std::env::temp_dir().join(format!("horizon-console-probe-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let executable = root.join("console-probe.exe"); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/console_probe.rs"); + let output = process::command("rustc") + .arg(source) + .arg("-o") + .arg(&executable) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + executable + }) +} From ac43cdea703eefac7a64e1452a6475ea47b47cf0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:25:40 +0200 Subject: [PATCH 2/2] launcher, server: one hidden-command helper per crate, server children keep its terminal - horizon-bench reads the machine with horizon-telemetry's `command_output` (now public) instead of a second copy of it; the console flag lives in one place. - horizon-server's `process::command` hides the console only when the server has none (started by the launcher). Run from a terminal, `schtasks`, `tar` and `mklink` share it as before, so their output still reaches it: a CREATE_NO_WINDOW child can't write to its parent's console. - horizon-prepare's java/javac keep the stdin they had; only the console flag is new. - launcher `process::hide_console` returns the command (no `let _ =` on other systems); the machine-details thread failing just leaves the report without them, as a slow one does. - README: the Windows subsystem's effect on the command line (interactive cmd/PowerShell don't wait or set the exit code) under "Command line", the deferred probe under "Performance log". Co-Authored-By: Claude Opus 5.5 --- crates/horizon-bench/src/hardware.rs | 17 +--------------- crates/horizon-prepare/src/java.rs | 11 +++++----- crates/horizon-server/src/process.rs | 28 ++++++++++++++------------ crates/horizon-telemetry/src/system.rs | 5 ++++- launcher/README.md | 17 ++++++++-------- launcher/src/perf.rs | 8 ++------ launcher/src/process.rs | 11 +++++----- 7 files changed, 41 insertions(+), 56 deletions(-) diff --git a/crates/horizon-bench/src/hardware.rs b/crates/horizon-bench/src/hardware.rs index 6b91202ad..440c834d8 100644 --- a/crates/horizon-bench/src/hardware.rs +++ b/crates/horizon-bench/src/hardware.rs @@ -1,8 +1,7 @@ //! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display //! come from the program that rendered (the game knows its adapter, the launcher its window). -use std::process::Command; - +use horizon_telemetry::system::command_output as output; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -173,20 +172,6 @@ pub fn cpu_seconds(pid: u32) -> Option { Some(ticks / 100.0) } -fn output(program: &str, args: &[&str]) -> Option { - let mut command = Command::new(program); - command.args(args); - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - command.creation_flags(CREATE_NO_WINDOW); - } - let out = command.output().ok()?; - let text = String::from_utf8(out.stdout).ok()?.trim().to_owned(); - (out.status.success() && !text.is_empty()).then_some(text) -} - #[cfg(target_os = "macos")] fn os_version() -> Option { output("sw_vers", &["-productVersion"]) diff --git a/crates/horizon-prepare/src/java.rs b/crates/horizon-prepare/src/java.rs index 78530486c..b4023b7d1 100644 --- a/crates/horizon-prepare/src/java.rs +++ b/crates/horizon-prepare/src/java.rs @@ -14,16 +14,17 @@ pub struct Jdk { const TIMEOUT: Duration = Duration::from_secs(3600); -/// Exporters and JDK probes write to pipes or log files, never to a new terminal. +/// Exporters and JDK probes write to pipes or log files: on Windows they open no terminal. fn command(program: impl AsRef) -> Command { - let mut command = Command::new(program); - command.stdin(Stdio::null()); + let command = Command::new(program); #[cfg(windows)] - { + let command = { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut command = command; command.creation_flags(CREATE_NO_WINDOW); - } + command + }; command } diff --git a/crates/horizon-server/src/process.rs b/crates/horizon-server/src/process.rs index 8a79f1161..8e8d24c70 100644 --- a/crates/horizon-server/src/process.rs +++ b/crates/horizon-server/src/process.rs @@ -1,18 +1,20 @@ -//! Background helpers inherit their log streams without opening a Windows terminal. +//! The programs the server runs. Started by the launcher, the server has no console, and each +//! console program it started would open a terminal window on Windows: those open none. Run from +//! a terminal, they share it, so what they print still reaches it. use std::{ffi::OsStr, process::Command}; pub fn command(program: impl AsRef) -> Command { - let mut command = Command::new(program); - configure(&mut command); + let command = Command::new(program); + #[cfg(windows)] + let command = { + use std::os::windows::process::CommandExt; + use windows_sys::Win32::System::{Console::GetConsoleWindow, Threading::CREATE_NO_WINDOW}; + let mut command = command; + // SAFETY: no arguments; it returns this process's console window or null. + if unsafe { GetConsoleWindow() }.is_null() { + command.creation_flags(CREATE_NO_WINDOW); + } + command + }; command } - -fn configure(command: &mut Command) { - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); - } - #[cfg(not(windows))] - let _ = command; -} diff --git a/crates/horizon-telemetry/src/system.rs b/crates/horizon-telemetry/src/system.rs index 33a5b744d..8ed6f2e3a 100644 --- a/crates/horizon-telemetry/src/system.rs +++ b/crates/horizon-telemetry/src/system.rs @@ -9,7 +9,10 @@ use std::sync::OnceLock; use crate::payload::System; -fn command_output(program: &str, args: &[&str]) -> Option { +/// What `program args` prints, trimmed, when it succeeds and prints something. On Windows the +/// program opens no console window: a GUI launcher or a game started without one would flash a +/// terminal for every probe. +pub fn command_output(program: &str, args: &[&str]) -> Option { let mut command = std::process::Command::new(program); command.args(args); #[cfg(windows)] diff --git a/launcher/README.md b/launcher/README.md index d2b78daea..d9738d0c2 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -97,12 +97,6 @@ page `servers.json` (the list), `servers//` (the servers created there) an Long pages, dialogs, the server console and data previews have a visible scrollbar when their content overflows. Drag the thumb or click the track to navigate without a mouse wheel. -On Windows, desktop launches and background tools run without terminal windows. Preparation -and server logs still reach the launcher, and CLI commands keep their terminal or redirected -input and output, including MCP. -Hardware details for performance reports are collected in the background after the first -frame, so Windows hardware queries do not delay the window opening. - ## Updates The launcher looks for a newer Horizon release when it starts and every 30 minutes while it @@ -133,7 +127,12 @@ and `horizon-launcher-windows-x64.zip`, never marked latest. The version is buil ## Command line -The same binary is a command-line tool; without a subcommand it opens the window. +The same binary is a command-line tool; without a subcommand it opens the window. On Windows it +is a windowed program, so a desktop start opens no terminal; a subcommand writes to the terminal +it was typed in, or to the pipes and files it was given (MCP keeps its stdio). Interactive `cmd` +and PowerShell don't wait for a windowed program: they show the prompt again before its output +and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code use +`start /wait horizon-launcher …` or `Start-Process -Wait`, or read its output through a pipe. horizon-launcher versions [--installed] releases on GitHub, or what is installed (* = selected) horizon-launcher install @@ -256,8 +255,8 @@ Each session writes its own measurements to `benchmarks/launcher-