Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

Daemon: start every program without a console window on Windows (#157)

reason-machines[bot]892b74009ad0
diff --git a/Cargo.toml b/Cargo.toml
index 0628716..60f1c33 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,7 +39,7 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
console = "0.16"
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Pipes", "Win32_System_Threading"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Pipes", "Win32_System_Threading"] }
[target.'cfg(target_os = "macos")'.dependencies]
tray-icon = { version = "0.26", default-features = false }
diff --git a/src/daemon/ask.rs b/src/daemon/ask.rs
index 789553f..fc03e44 100644
--- a/src/daemon/ask.rs
+++ b/src/daemon/ask.rs
@@ -314,7 +314,7 @@ const NOT_SHOWN: [&str; 2] = ["Actions are not supported", "Failed to show notif
async fn show(cmd: Command) -> Result<String, String> {
use std::process::Stdio;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
- let mut child = tokio::process::Command::from(cmd)
+ let mut child = crate::util::no_window(tokio::process::Command::from(cmd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -424,7 +424,7 @@ function run([title, request, question, secs, icon]) {
#[cfg(target_os = "macos")]
fn dialog(title: &str, request: &str, question: &str) -> Option<Command> {
- let mut cmd = Command::new(asker_bin("osascript", &["/usr/bin/osascript"])?);
+ let mut cmd = crate::util::no_window(Command::new(asker_bin("osascript", &["/usr/bin/osascript"])?));
let icon = icon().map(|p| p.display().to_string()).unwrap_or_default();
cmd.args(["-l", "JavaScript", "-e", PANEL, title, request, question, &OPEN_SECS.to_string(), &icon]);
Some(cmd)
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index dd0b1f7..abec420 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -510,7 +510,7 @@ impl Daemon {
tokio::spawn(async move {
let run = async {
let program = agent::command_for(bin).ok_or_else(|| format!("{bin} not found"))?;
- let out = tokio::process::Command::from(program)
+ let out = crate::util::no_window(tokio::process::Command::from(program))
.args(&args)
.arg(&text)
.stdin(std::process::Stdio::null())
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index 42c01b8..d9d6720 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -92,7 +92,12 @@ pub async fn run(service: bool) -> Result<()> {
async fn tray() {
let Ok(exe) = util::current_exe() else { return };
for _ in 0..5 {
- match tokio::process::Command::new(&exe).arg("tray").stdin(std::process::Stdio::null()).status().await {
+ match util::no_window(tokio::process::Command::new(&exe))
+ .arg("tray")
+ .stdin(std::process::Stdio::null())
+ .status()
+ .await
+ {
Ok(st) if st.success() => return,
Ok(st) => log(&format!("menu bar icon exited ({st}); restarting it")),
Err(e) => return log(&format!("menu bar icon not started: {e}")),
diff --git a/src/daemon/notify.rs b/src/daemon/notify.rs
index 92e34ed..005d190 100644
--- a/src/daemon/notify.rs
+++ b/src/daemon/notify.rs
@@ -48,7 +48,7 @@ impl Daemon {
#[cfg(target_os = "macos")]
fn command(title: &str, body: &str) -> Option<Command> {
- let mut cmd = Command::new(agent::find_bin("osascript")?);
+ let mut cmd = crate::util::no_window(Command::new(agent::find_bin("osascript")?));
let show = r#"display notification (item 2 of argv) with title (item 1 of argv) sound name "Glass""#;
cmd.args(["-e", "on run argv", "-e", show, "-e", "end run", title, body]);
Some(cmd)
@@ -70,7 +70,7 @@ pub(super) fn notify_send() -> Option<Command> {
#[cfg(all(unix, not(target_os = "macos")))]
pub(super) fn notify_send_at(bin: std::path::PathBuf) -> Option<Command> {
- let mut cmd = Command::new(bin);
+ let mut cmd = crate::util::no_window(Command::new(bin));
let bus = match std::env::var_os("DBUS_SESSION_BUS_ADDRESS") {
Some(bus) => bus,
None => {
@@ -101,7 +101,7 @@ fn notifications_on(bus: &std::ffi::OsStr) -> bool {
return true;
};
let call = |args: &[&str]| {
- Command::new(&busctl)
+ crate::util::no_window(Command::new(&busctl))
.env("DBUS_SESSION_BUS_ADDRESS", bus)
.args(["--user", "--timeout=1", "call", "org.freedesktop.DBus", "/org/freedesktop/DBus"])
.arg("org.freedesktop.DBus")
@@ -157,11 +157,9 @@ pub(super) fn powershell(script: &str) -> Option<Command> {
#[cfg(windows)]
pub(super) fn powershell_at(bin: std::path::PathBuf, script: &str) -> Command {
- use std::os::windows::process::CommandExt;
- let mut cmd = Command::new(bin);
+ // No console flashing up next to the notification.
+ let mut cmd = crate::util::no_window(Command::new(bin));
cmd.args(["-NoProfile", "-NonInteractive", "-Command", script]);
- // CREATE_NO_WINDOW: no console flashing up next to the notification.
- cmd.creation_flags(0x0800_0000);
cmd
}
diff --git a/src/daemon/reason.rs b/src/daemon/reason.rs
index 057f192..5b380d2 100644
--- a/src/daemon/reason.rs
+++ b/src/daemon/reason.rs
@@ -59,7 +59,7 @@ impl Daemon {
None => {}
Some(bin) => {
missing = false;
- let child = tokio::process::Command::new(&bin)
+ let child = crate::util::no_window(tokio::process::Command::new(&bin))
.args(["network", "__relay"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
@@ -184,8 +184,11 @@ async fn list_sessions(bin: &std::path::Path, narrow: bool) -> Result<std::proce
if narrow {
args.extend(["--fields", FIELDS]);
}
- let out =
- tokio::process::Command::new(bin).args(args).stdin(std::process::Stdio::null()).kill_on_drop(true).output();
+ let out = crate::util::no_window(tokio::process::Command::new(bin))
+ .args(args)
+ .stdin(std::process::Stdio::null())
+ .kill_on_drop(true)
+ .output();
Ok(tokio::time::timeout(Duration::from_secs(30), out).await??)
}
diff --git a/src/daemon/update.rs b/src/daemon/update.rs
index 1708a27..9955e2c 100644
--- a/src/daemon/update.rs
+++ b/src/daemon/update.rs
@@ -41,7 +41,7 @@ async fn update() -> Result<Option<String>> {
let dir = crate::util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();
let exe = dir.join(format!("{}{}", crate::AGENT_NAME, std::env::consts::EXE_SUFFIX));
let waiting = crate::migrate::waiting(&exe);
- let mut cmd = tokio::process::Command::from(crate::installer(&dir));
+ let mut cmd = crate::util::no_window(tokio::process::Command::from(crate::installer(&dir)));
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
@@ -71,7 +71,8 @@ async fn update() -> Result<Option<String>> {
crate::migrate::keep_waiting_copy(&exe);
}
// Restart only on a binary that really is newer (a release tagged without bumping its version must not loop).
- let installed = tokio::process::Command::new(&exe).arg("--version").kill_on_drop(true).output();
+ let installed =
+ crate::util::no_window(tokio::process::Command::new(&exe)).arg("--version").kill_on_drop(true).output();
let installed = tokio::time::timeout(Duration::from_secs(30), installed).await??;
let installed =
String::from_utf8_lossy(&installed.stdout).trim().rsplit(' ').next().unwrap_or_default().to_string();
@@ -85,7 +86,7 @@ async fn update() -> Result<Option<String>> {
async fn latest_version() -> Result<String> {
let repo = crate::REPO;
let null = if cfg!(windows) { "NUL" } else { "/dev/null" };
- let out = tokio::process::Command::new("curl")
+ let out = crate::util::no_window(tokio::process::Command::new("curl"))
.args([
"-fsSLI",
"--max-time",
diff --git a/src/relays.rs b/src/relays.rs
index 7658359..429dceb 100644
--- a/src/relays.rs
+++ b/src/relays.rs
@@ -192,7 +192,7 @@ fn curl_args(url: &str) -> Vec<String> {
/// The body at `url`, if a 200 of at most `MAX_BYTES`: curl is stopped as soon as more comes, however it is sent.
async fn fetch(url: &str) -> Result<Vec<u8>> {
use tokio::io::AsyncReadExt;
- let mut curl = tokio::process::Command::new("curl")
+ let mut curl = crate::util::no_window(tokio::process::Command::new("curl"))
.args(curl_args(url))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
diff --git a/src/setup.rs b/src/setup.rs
index 6376895..56d4e30 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1111,7 +1111,7 @@ pub fn start_service() -> bool {
/// Our Run entry, as `reg query` shows it.
#[cfg(windows)]
fn run_entry() -> Option<String> {
- let out = Command::new("reg")
+ let out = crate::util::no_window(Command::new("reg"))
.args(["query", RUN_KEY, "/v", &service_name()])
.stdin(std::process::Stdio::null())
.output()
@@ -1122,7 +1122,7 @@ fn run_entry() -> Option<String> {
/// The Run entry a standalone tincan install made, if it still starts this binary or the tincan it replaced.
#[cfg(windows)]
pub fn legacy_run_entry(exe: &Path) -> bool {
- Command::new("reg")
+ crate::util::no_window(Command::new("reg"))
.args(["query", RUN_KEY, "/v", "dev.tincan.daemon"])
.stdin(std::process::Stdio::null())
.output()
@@ -1132,7 +1132,9 @@ pub fn legacy_run_entry(exe: &Path) -> bool {
/// Moves that Run entry over to this binary (ours first, then the old one goes).
#[cfg(windows)]
pub fn move_legacy_run_entry(exe: &Path) {
- let reg = |args: &[&str]| Command::new("reg").args(args).stdin(std::process::Stdio::null()).output();
+ let reg = |args: &[&str]| {
+ crate::util::no_window(Command::new("reg")).args(args).stdin(std::process::Stdio::null()).output()
+ };
if legacy_run_entry(exe) {
let command = format!("\"{}\" daemon --service", exe.display());
if reg(&["add", RUN_KEY, "/v", &service_name(), "/d", &command, "/f"]).is_ok_and(|o| o.status.success()) {
@@ -1143,7 +1145,9 @@ pub fn move_legacy_run_entry(exe: &Path) {
#[cfg(windows)]
async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {
- let reg = |args: &[&str]| Command::new("reg").args(args).stdin(std::process::Stdio::null()).output();
+ let reg = |args: &[&str]| {
+ crate::util::no_window(Command::new("reg")).args(args).stdin(std::process::Stdio::null()).output()
+ };
if remove {
if !dry {
let _ = reg(&["delete", RUN_KEY, "/v", &service_name(), "/f"]);
diff --git a/src/util.rs b/src/util.rs
index c964468..bf3e80d 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -275,10 +275,128 @@ pub fn current_exe() -> std::io::Result<std::path::PathBuf> {
Ok(exe.to_str().and_then(|s| s.strip_suffix(" (deleted)")).map(std::path::PathBuf::from).unwrap_or(exe))
}
+/// `cmd`, set to start without a console window of its own on Windows (CREATE_NO_WINDOW). The daemon runs without a
+/// console, so a console program it starts would otherwise get a new window, flashing up on the user's screen. Every
+/// program the daemon starts goes through here (a test checks).
+pub fn no_window<C: NoWindow>(mut cmd: C) -> C {
+ cmd.hide_window();
+ cmd
+}
+
+pub trait NoWindow {
+ fn hide_window(&mut self);
+}
+
+/// CREATE_NO_WINDOW.
+#[cfg(windows)]
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+
+impl NoWindow for std::process::Command {
+ fn hide_window(&mut self) {
+ #[cfg(windows)]
+ std::os::windows::process::CommandExt::creation_flags(self, CREATE_NO_WINDOW);
+ }
+}
+
+impl NoWindow for tokio::process::Command {
+ fn hide_window(&mut self) {
+ #[cfg(windows)]
+ self.creation_flags(CREATE_NO_WINDOW);
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ /// The files with code the daemon runs, and the setup functions it calls. Tests (a trailing `mod tests`) aside.
+ fn daemon_sources() -> Vec<(std::path::PathBuf, String)> {
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let mut files = vec![root.join("relays.rs")];
+ for entry in std::fs::read_dir(root.join("daemon")).unwrap() {
+ let path = entry.unwrap().path();
+ if path.extension().is_some_and(|e| e == "rs") {
+ files.push(path);
+ }
+ }
+ let mut out: Vec<_> = files
+ .into_iter()
+ .map(|path| {
+ let src = std::fs::read_to_string(&path).unwrap().replace("\r\n", "\n");
+ let code = src.split("\nmod tests {").next().unwrap().to_string();
+ (path, code)
+ })
+ .collect();
+ // The `reg` calls in setup.rs: the daemon asks whether its Run entry is installed.
+ // Windows checks out with CRLF.
+ let setup = std::fs::read_to_string(root.join("setup.rs")).unwrap().replace("\r\n", "\n");
+ let start = setup.find("fn run_entry()").unwrap();
+ let end = setup[start..].find("\n#[cfg(windows)]\nasync fn service(").unwrap() + start;
+ out.push((root.join("setup.rs"), setup[start..end].to_string()));
+ out
+ }
+
+ #[test]
+ fn every_program_the_daemon_starts_goes_through_no_window() {
+ let mut raw = Vec::new();
+ for (path, code) in daemon_sources() {
+ for (at, _) in code.match_indices("Command::").filter(|(at, _)| {
+ let rest = &code[at + "Command::".len()..];
+ rest.starts_with("new(") || rest.starts_with("from(")
+ }) {
+ // `Command::new` may be qualified (`tokio::process::Command::new`): look before the path.
+ let path_start =
+ code[..at].trim_end_matches(|c: char| c.is_alphanumeric() || c == '_' || c == ':').len();
+ if !code[..path_start].trim_end().ends_with("no_window(") {
+ let line = code[..at].lines().count();
+ raw.push(format!(
+ "{}: {}",
+ path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap_or(&path).display(),
+ code.lines().nth(line - 1).unwrap_or_default().trim()
+ ));
+ }
+ }
+ }
+ assert!(
+ raw.is_empty(),
+ "started without util::no_window (a console window flashes up on Windows):\n{}",
+ raw.join("\n")
+ );
+ }
+
+ /// A child started through `no_window` by a process with no console (as the daemon runs) has no console window.
+ #[cfg(windows)]
+ #[test]
+ fn a_child_started_without_a_console_gets_no_window() {
+ use std::os::windows::process::CommandExt;
+ use windows_sys::Win32::System::Console::GetConsoleWindow;
+ const ROLE: &str = "REASON_NETWORK_NO_WINDOW_TEST";
+ const DETACHED_PROCESS: u32 = 0x0000_0008;
+ let me = std::env::current_exe().unwrap();
+ let this_test = "util::tests::a_child_started_without_a_console_gets_no_window";
+ let run = |cmd: &mut std::process::Command, role: &str| {
+ cmd.args([this_test, "--exact", "--nocapture", "--test-threads=1"]).env(ROLE, role).status().unwrap()
+ };
+ match std::env::var(ROLE).as_deref() {
+ // The program the daemon starts: fails if it has a window.
+ Ok("child") => {
+ let window = unsafe { GetConsoleWindow() };
+ assert!(window.is_null(), "the child has a console window");
+ }
+ // The daemon: no console of its own, starts the child as it would.
+ Ok("daemon") => {
+ assert!(unsafe { GetConsoleWindow() }.is_null(), "the daemon was started with a console");
+ let st = run(&mut no_window(std::process::Command::new(&me)), "child");
+ assert!(st.success(), "the child had a console window");
+ }
+ _ => {
+ let mut daemon = std::process::Command::new(&me);
+ daemon.creation_flags(DETACHED_PROCESS);
+ assert!(run(&mut daemon, "daemon").success(), "the daemon's child got a console window");
+ }
+ }
+ }
+
#[test]
fn slugs() {
assert_eq!(slug("Sams-MacBook-Pro"), "sams-macbook-pro");