Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(desktop): shared launch contracts and Windows launch encoding

Marcelitod48b07e44650
diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs
index afebd69..12cf6ae 100644
--- a/apps/desktop/src-tauri/src/daemon.rs
+++ b/apps/desktop/src-tauri/src/daemon.rs
@@ -13,23 +13,29 @@
#[cfg(any(windows, test))]
mod windows_record;
+mod launch;
+pub use launch::*;
+#[cfg(test)]
+mod windows;
+
pub use crate::app_channel::APP_FD;
use crate::app_channel::{AppChannel, Handler};
use crate::health::check_health;
-use std::fs::{self, File, OpenOptions};
+use std::fs::{self, File};
+#[cfg(unix)]
+use std::fs::OpenOptions;
use std::io;
+#[cfg(unix)]
use std::os::fd::{BorrowedFd, FromRawFd, OwnedFd};
+#[cfg(unix)]
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
+#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
-use std::process::{Child, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
-/// Origins of the `tauri dev` server, allowed only on daemons spawned by debug builds.
-pub const DEV_ALLOWED_ORIGINS: &str = r#"["http://127.0.0.1:5173","http://localhost:5173"]"#;
-
const HEALTH_TIMEOUT: Duration = Duration::from_millis(300);
const STOP_GRACE: Duration = Duration::from_secs(5);
/// The daemon stops its engine and memory first; a recorded orphan gets longer than a child.
@@ -91,6 +97,7 @@ pub fn process_started(_pid: u32) -> Option<u64> {
/// Records the daemon just spawned as `pid` (private, 0600). A new file in the same folder renamed
/// over the pid file: never written through a symlink there, and never seen half written.
+#[cfg(unix)]
pub fn record_launch(data_dir: &Path, pid: u32) -> io::Result<()> {
let started = process_started(pid).ok_or_else(|| io::Error::other("the assistant is not running"))?;
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
@@ -114,10 +121,12 @@ pub fn record_launch(data_dir: &Path, pid: u32) -> io::Result<()> {
}
/// A pid file holds `<pid> <start time>`, far below this.
+#[cfg(unix)]
const PID_FILE_MAX: u64 = 64;
/// Whether a pid read from the pid file may name a daemon to signal: never this app, its parent,
/// init, or the kernel.
+#[cfg(unix)]
fn may_be_daemon(pid: u32) -> bool {
// SAFETY: getppid(2) has no preconditions.
let parent = u32::try_from(unsafe { libc::getppid() }).ok();
@@ -126,6 +135,7 @@ fn may_be_daemon(pid: u32) -> bool {
/// The daemon the pid file names, if it holds a launch. Only a small regular file is read: a
/// symlink, a FIFO, or anything else there is ignored (opened without following or blocking).
+#[cfg(unix)]
pub fn recorded_launch(data_dir: &Path) -> Option<Launched> {
let file = OpenOptions::new()
.read(true)
@@ -144,11 +154,13 @@ pub fn recorded_launch(data_dir: &Path) -> Option<Launched> {
}
/// The recorded daemon, while that same process still runs (a reused pid has another start time).
+#[cfg(unix)]
pub fn live_orphan(data_dir: &Path) -> Option<Launched> {
recorded_launch(data_dir).filter(|launch| process_started(launch.pid) == Some(launch.started))
}
/// Removes the pid file when it names `pid`.
+#[cfg(unix)]
fn forget_launch(data_dir: &Path, pid: u32) {
if recorded_launch(data_dir).is_some_and(|launch| launch.pid == pid) {
let _ = fs::remove_file(data_dir.join(PID_FILE));
@@ -157,6 +169,7 @@ fn forget_launch(data_dir: &Path, pid: u32) {
/// SIGTERM to a recorded daemon that is not this app's child, then SIGKILL after `grace`.
/// Only the process the record names: a pid now used by another process is left alone.
+#[cfg(unix)]
fn stop_orphan(launch: Launched, grace: Duration) {
let Ok(pid) = libc::pid_t::try_from(launch.pid) else {
return;
@@ -206,57 +219,9 @@ pub fn start_plan(healthy: bool, owns_child: bool, wants_channel: bool, orphan:
}
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct LaunchSpec {
- pub program: String,
- pub args: Vec<String>,
- pub envs: Vec<(String, String)>,
-}
-
-/// `<node> <daemon script>` (S29.5). With a bundled runtime (`<runtime>/daemon/cli.mjs`
-/// exists) that is the runtime's own Node and daemon, a PATH of the runtime plus the
-/// system folders, and `GENTLE_DOT_RUNTIME`; otherwise the build-time paths and PATH.
-/// `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override the program and script in both.
-pub fn launch_spec(env: impl Fn(&str) -> Option<String>, dev: bool, runtime: Option<&Path>) -> LaunchSpec {
- let pick = |key: &str, fallback: String| env(key).filter(|v| !v.is_empty()).unwrap_or(fallback);
- let bundled = runtime.filter(|dir| dir.join("daemon/cli.mjs").is_file());
- let (node, script, mut envs) = match bundled {
- Some(dir) => {
- let root = dir.display().to_string();
- let path = format!("{root}/bin:{root}/node/bin:/usr/bin:/bin:/usr/sbin:/sbin");
- (
- format!("{root}/node/bin/node"),
- format!("{root}/daemon/cli.mjs"),
- vec![("PATH".to_string(), path), ("GENTLE_DOT_RUNTIME".to_string(), root)],
- )
- }
- None => (
- env!("GENTLE_DOT_BUILD_NODE").to_string(),
- env!("GENTLE_DOT_BUILD_DAEMON_SCRIPT").to_string(),
- vec![("PATH".to_string(), env!("GENTLE_DOT_BUILD_PATH").to_string())],
- ),
- };
- if dev {
- envs.push(("GENTLE_DOT_ALLOWED_ORIGINS".into(), DEV_ALLOWED_ORIGINS.into()));
- }
- LaunchSpec {
- program: pick("GENTLE_DOT_NODE", node),
- args: vec![pick("GENTLE_DOT_DAEMON_SCRIPT", script)],
- envs,
- }
-}
-
-/// Where a bundled runtime would live: `GENTLE_DOT_RUNTIME_DIR`, else the app's `runtime`
-/// resource. `launch_spec` uses it only when it holds `daemon/cli.mjs`.
-pub fn runtime_dir(env: impl Fn(&str) -> Option<String>, resource_dir: Option<PathBuf>) -> Option<PathBuf> {
- env("GENTLE_DOT_RUNTIME_DIR")
- .filter(|v| !v.is_empty())
- .map(PathBuf::from)
- .or_else(|| resource_dir.map(|dir| dir.join("runtime")))
-}
-
/// Opens `<data_dir>/daemon.log` for appending. The folder is 0700 and the log
/// 0600 (looser modes are repaired) because the daemon's output is private.
+#[cfg(unix)]
pub fn open_private_log(data_dir: &Path) -> io::Result<File> {
fs::DirBuilder::new().recursive(true).mode(0o700).create(data_dir)?;
fs::set_permissions(data_dir, fs::Permissions::from_mode(0o700))?;
@@ -265,37 +230,9 @@ pub fn open_private_log(data_dir: &Path) -> io::Result<File> {
Ok(log)
}
-/// A spawned process the app polls, stops, and reaps: a `std::process::Child`, or on macOS a
-/// daemon spawned with its TCC responsibility disclaimed (`disclaimed`).
-pub trait ChildProcess: Send {
- fn id(&self) -> u32;
- /// The exit status once the process ended (reaping it), `None` while it runs.
- fn try_wait(&mut self) -> io::Result<Option<ExitStatus>>;
- /// Sends SIGKILL unless the process was already reaped.
- fn kill(&mut self) -> io::Result<()>;
- fn wait(&mut self) -> io::Result<ExitStatus>;
-}
-
-impl ChildProcess for Child {
- fn id(&self) -> u32 {
- Child::id(self)
- }
-
- fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
- Child::try_wait(self)
- }
-
- fn kill(&mut self) -> io::Result<()> {
- Child::kill(self)
- }
-
- fn wait(&mut self) -> io::Result<ExitStatus> {
- Child::wait(self)
- }
-}
-
/// A connected pair of Unix sockets: the app's end, and the daemon's, numbered above [`APP_FD`] so
/// placing it on fd 3 in the child never collides with it. Both are close-on-exec here.
+#[cfg(unix)]
pub fn channel_pair() -> io::Result<(UnixStream, OwnedFd)> {
let (app, daemon) = UnixStream::pair()?;
let daemon = OwnedFd::from(daemon);
@@ -326,7 +263,7 @@ fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -
/// descriptor some library of the app opened without close-on-exec never reaches the daemon. Node
/// then marks fd 3 close-on-exec at its own startup (libuv's `uv_disable_stdio_inheritance`), so
/// the daemon's children never get it either (`app-channel.ts` `childInherits` checks that).
-#[cfg(not(target_os = "macos"))]
+#[cfg(all(unix, not(target_os = "macos")))]
fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -> io::Result<Box<dyn ChildProcess>> {
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
@@ -360,7 +297,7 @@ fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -
/// Marks every descriptor from `first` up close-on-exec. Called between fork and exec: system
/// calls only.
-#[cfg(not(target_os = "macos"))]
+#[cfg(all(unix, not(target_os = "macos")))]
fn cloexec_from(first: libc::c_int) {
#[cfg(target_os = "linux")]
if let Ok(low) = libc::c_uint::try_from(first) {
@@ -385,6 +322,7 @@ fn cloexec_from(first: libc::c_int) {
}
/// Sends SIGTERM, waits up to `grace` for a clean exit, then kills.
+#[cfg(unix)]
pub fn stop_child(child: &mut dyn ChildProcess, grace: Duration) {
if !matches!(child.try_wait(), Ok(None)) {
return;
@@ -575,15 +513,27 @@ impl Daemon {
}
fn spawn(&self) -> Result<(), String> {
- let mut slot = self.child.lock().unwrap();
+ self.spawn_locked(self.child.lock().unwrap())
+ }
+
+ fn spawn_locked(&self, mut slot: std::sync::MutexGuard<'_, Option<Box<dyn ChildProcess>>>) -> Result<(), String> {
if let Some(child) = slot.as_mut() {
if matches!(child.try_wait(), Ok(None)) {
return Ok(());
}
}
- let spec = self.launch.clone().unwrap_or_else(|| {
- launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions), self.runtime_dir.as_deref())
- });
+ let spec = match &self.launch {
+ Some(spec) => spec.clone(),
+ None => {
+ validate_packaged_runtime(
+ |key| std::env::var(key).ok(),
+ cfg!(windows) && !cfg!(debug_assertions)
+ && option_env!("GENTLE_DOT_WINDOWS_PACKAGED_REQUIRED") == Some("1"),
+ self.runtime_dir.as_deref(),
+ )?;
+ launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions), self.runtime_dir.as_deref())
+ }
+ };
let log = open_private_log(&self.data_dir).map_err(|e| format!("cannot open daemon.log: {e}"))?;
let pair = match &self.handler {
Some(_) => Some(channel_pair().map_err(|e| format!("cannot open the assistant's channel: {e}"))?),
@@ -644,7 +594,7 @@ impl Daemon {
}
}
-#[cfg(test)]
+#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::app_channel::{AppChannel, Handler};
diff --git a/apps/desktop/src-tauri/src/daemon/launch.rs b/apps/desktop/src-tauri/src/daemon/launch.rs
new file mode 100644
index 0000000..54f0dab
--- /dev/null
+++ b/apps/desktop/src-tauri/src/daemon/launch.rs
@@ -0,0 +1,311 @@
+//! Shared launch contracts and runtime selection, also exercised behind the Windows seam.
+
+#[cfg(any(windows, test))]
+use std::fs;
+use std::io;
+use std::path::{Path, PathBuf};
+use std::process::{Child, ExitStatus};
+#[cfg(windows)]
+use std::time::Duration;
+#[cfg(windows)]
+pub use crate::app_channel::windows::ChildEndpoint;
+
+/// Origins of the `tauri dev` server, allowed only on daemons spawned by debug builds.
+pub const DEV_ALLOWED_ORIGINS: &str = r#"["http://127.0.0.1:5173","http://localhost:5173"]"#;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LaunchSpec {
+ pub program: String,
+ pub args: Vec<String>,
+ pub envs: Vec<(String, String)>,
+}
+
+/// A spawned process the app polls, stops, and reaps: a `std::process::Child`, or on macOS a
+/// daemon spawned with its TCC responsibility disclaimed (`disclaimed`).
+pub trait ChildProcess: Send {
+ fn id(&self) -> u32;
+ /// The exit status once the process ended (reaping it), `None` while it runs.
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>>;
+ /// Sends SIGKILL unless the process was already reaped.
+ fn kill(&mut self) -> io::Result<()>;
+ fn wait(&mut self) -> io::Result<ExitStatus>;
+ #[cfg(windows)]
+ fn launch_failed(&self) -> bool { false }
+ /// Authenticated-stop uncertainty is not permission for failed-startup cleanup.
+ #[cfg(windows)]
+ fn shutdown_requires_channel(&self) -> bool { !self.launch_failed() }
+ #[cfg(windows)]
+ fn retain_failure(&mut self) {}
+ /// Windows requests authenticated stop with the channel open; errors retain ownership.
+ #[cfg(windows)]
+ fn shutdown_owned(&mut self, _grace: Duration) -> io::Result<()> {
+ Err(io::Error::new(io::ErrorKind::Unsupported, "checked Windows child shutdown is unavailable"))
+ }
+ #[cfg(windows)]
+ fn started_owned(&self) -> io::Result<u64> {
+ Err(io::Error::new(io::ErrorKind::Unsupported, "retained Windows creation identity is unavailable"))
+ }
+}
+
+impl ChildProcess for Child {
+ fn id(&self) -> u32 {
+ Child::id(self)
+ }
+
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
+ Child::try_wait(self)
+ }
+
+ fn kill(&mut self) -> io::Result<()> {
+ Child::kill(self)
+ }
+
+ fn wait(&mut self) -> io::Result<ExitStatus> {
+ Child::wait(self)
+ }
+}
+
+/// Admit a package-required launch before selecting any build-machine fallback. Ordinary
+/// checkout builds retain the old contract. A complete explicit Node/script override is
+/// an intentional external runtime, not an accidental fallback; one override alone is not.
+pub fn validate_packaged_runtime(
+ env: impl Fn(&str) -> Option<String>,
+ required: bool,
+ runtime: Option<&Path>,
+) -> Result<(), String> {
+ if !required {
+ return Ok(());
+ }
+ let overridden = |key: &str| env(key).is_some_and(|value| !value.is_empty());
+ if overridden("GENTLE_DOT_NODE") && overridden("GENTLE_DOT_DAEMON_SCRIPT") {
+ return Ok(());
+ }
+ let fail = |detail: String| format!(
+ "The installed Windows runtime is missing or incomplete ({detail}). Reinstall Gentle Dot, \
+ or explicitly select a complete runtime with GENTLE_DOT_RUNTIME_DIR. \
+ To use an external daemon, set both GENTLE_DOT_NODE and GENTLE_DOT_DAEMON_SCRIPT; \
+ this package will not silently use build-machine checkout paths."
+ );
+ let dir = runtime.ok_or_else(|| fail("runtime resource directory unavailable".into()))?;
+ for relative in [
+ "node/bin/node.exe", "daemon/cli.mjs", "daemon/package.json",
+ "daemon/native/windows-stop.node", "daemon/node_modules/gentle-pi/package.json",
+ "bin/engram.exe", "bin/pi.cmd", "ui/index.html",
+ ] {
+ if !dir.join(relative).is_file() {
+ return Err(fail(dir.join(relative).display().to_string()));
+ }
+ }
+ if !dir.join("daemon/node_modules/gentle-pi/.gentle-ai").is_dir() {
+ return Err(fail(dir.join("daemon/node_modules/gentle-pi/.gentle-ai").display().to_string()));
+ }
+ Ok(())
+}
+
+#[cfg(windows)]
+fn node_runtime_path(dir: &Path) -> PathBuf {
+ // Node's entry resolver rejects verbatim drive paths. Only use the ordinary
+ // spelling if Windows resolves it to the same canonical directory; special
+ // namespace paths and names with different Win32 semantics stay untouched.
+ if let Some(rest) = dir.to_str().and_then(|s| s.strip_prefix(r"\\?\")) {
+ let bytes = rest.as_bytes();
+ if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\' {
+ let ordinary = PathBuf::from(rest);
+ if let (Ok(original), Ok(candidate)) = (fs::canonicalize(dir), fs::canonicalize(&ordinary)) {
+ if original == candidate { return ordinary; }
+ }
+ }
+ }
+ dir.to_path_buf()
+}
+
+/// `<node> <daemon script>` (S29.5). With a bundled runtime (`<runtime>/daemon/cli.mjs`
+/// exists) that is the runtime's own Node and daemon, a PATH of the runtime plus the
+/// system folders, and `GENTLE_DOT_RUNTIME`; otherwise the build-time paths and PATH.
+/// `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override the program and script in both.
+pub fn launch_spec(env: impl Fn(&str) -> Option<String>, dev: bool, runtime: Option<&Path>) -> LaunchSpec {
+ let pick = |key: &str, fallback: String| env(key).filter(|v| !v.is_empty()).unwrap_or(fallback);
+ let bundled = runtime.filter(|dir| dir.join("daemon/cli.mjs").is_file());
+ let (node, script, mut envs) = match bundled {
+ Some(dir) => {
+ #[cfg(windows)]
+ let compatible = node_runtime_path(dir);
+ #[cfg(windows)]
+ let dir = compatible.as_path();
+ let root = dir.display().to_string();
+ #[cfg(unix)]
+ let (node, script, path) = (
+ format!("{root}/node/bin/node"),
+ format!("{root}/daemon/cli.mjs"),
+ format!("{root}/bin:{root}/node/bin:/usr/bin:/bin:/usr/sbin:/sbin"),
+ );
+ #[cfg(windows)]
+ let (node, script, path) = {
+ let system = PathBuf::from(env("SystemRoot").filter(|v| !v.is_empty())
+ .unwrap_or_else(|| r"C:\Windows".into()));
+ (
+ dir.join("node/bin/node.exe").display().to_string(),
+ dir.join("daemon/cli.mjs").display().to_string(),
+ format!("{};{};{};{}", dir.join("bin").display(), dir.join("node/bin").display(),
+ system.join("System32").display(), system.display()),
+ )
+ };
+ (
+ node,
+ script,
+ vec![("PATH".to_string(), path), ("GENTLE_DOT_RUNTIME".to_string(), root)],
+ )
+ }
+ None => (
+ env!("GENTLE_DOT_BUILD_NODE").to_string(),
+ env!("GENTLE_DOT_BUILD_DAEMON_SCRIPT").to_string(),
+ vec![("PATH".to_string(), env!("GENTLE_DOT_BUILD_PATH").to_string())],
+ ),
+ };
+ if dev {
+ envs.push(("GENTLE_DOT_ALLOWED_ORIGINS".into(), DEV_ALLOWED_ORIGINS.into()));
+ }
+ LaunchSpec {
+ program: pick("GENTLE_DOT_NODE", node),
+ args: vec![pick("GENTLE_DOT_DAEMON_SCRIPT", script)],
+ envs,
+ }
+}
+
+/// Where a bundled runtime would live: `GENTLE_DOT_RUNTIME_DIR`, else the app's `runtime`
+/// resource. `launch_spec` uses it only when it holds `daemon/cli.mjs`.
+pub fn runtime_dir(env: impl Fn(&str) -> Option<String>, resource_dir: Option<PathBuf>) -> Option<PathBuf> {
+ env("GENTLE_DOT_RUNTIME_DIR")
+ .filter(|v| !v.is_empty())
+ .map(PathBuf::from)
+ .or_else(|| resource_dir.map(|dir| dir.join("runtime")))
+}
+
+#[cfg(test)]
+mod packaged_runtime_tests {
+ use super::*;
+
+ #[cfg(windows)]
+ #[test]
+ fn build_time_windows_script_resolves_in_node_without_running_daemon() {
+ let spec = launch_spec(|_| None, false, None);
+ assert_eq!(spec.program, env!("GENTLE_DOT_BUILD_NODE"));
+ assert_eq!(spec.args.len(), 1);
+ assert_eq!(spec.envs, vec![("PATH".into(), env!("GENTLE_DOT_BUILD_PATH").into())]);
+ // Exercise Node's entry-point realpathSync without importing the daemon.
+ let output = std::process::Command::new(&spec.program)
+ .env_remove("NODE_OPTIONS")
+ .args(["-e", "process.stdout.write(require('node:fs').realpathSync(process.argv[1]))"])
+ .arg(&spec.args[0]).output().unwrap();
+ assert!(output.status.success(), "Node path resolution failed: {}", String::from_utf8_lossy(&output.stderr));
+ assert!(output.stderr.is_empty());
+ let resolved = String::from_utf8(output.stdout).unwrap();
+ assert_eq!(fs::canonicalize(resolved).unwrap(), fs::canonicalize(&spec.args[0]).unwrap());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn bundled_windows_runtime_uses_native_paths_and_preserves_overrides() {
+ let runtime = fixture("launch-spec");
+ let spec = launch_spec(|key| (key == "SystemRoot").then(|| r"D:\Windows".into()), false, Some(&runtime));
+ assert_eq!(spec.program, runtime.join("node/bin/node.exe").display().to_string());
+ assert_eq!(spec.args, vec![runtime.join("daemon/cli.mjs").display().to_string()]);
+ assert_eq!(spec.envs, vec![
+ ("PATH".into(), format!("{};{};D:\\Windows\\System32;D:\\Windows",
+ runtime.join("bin").display(), runtime.join("node/bin").display())),
+ ("GENTLE_DOT_RUNTIME".into(), runtime.display().to_string()),
+ ]);
+ let overridden = launch_spec(|key| match key {
+ "SystemRoot" => Some(r"D:\Windows".into()),
+ "GENTLE_DOT_NODE" => Some(r"E:\custom\node.exe".into()),
+ "GENTLE_DOT_DAEMON_SCRIPT" => Some(r"E:\custom\cli.mjs".into()),
+ _ => None,
+ }, false, Some(&runtime));
+ assert_eq!(overridden.program, r"E:\custom\node.exe");
+ assert_eq!(overridden.args, vec![r"E:\custom\cli.mjs"]);
+ assert_eq!(overridden.envs, spec.envs);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn bundled_windows_paths_work_with_node_without_changing_overrides() {
+ let runtime = fixture("installed path");
+ let extended = fs::canonicalize(&runtime).unwrap();
+ assert!(extended.to_str().unwrap().starts_with(r"\\?\"));
+ let spec = launch_spec(|_| None, false, Some(&extended));
+ let checked = std::process::Command::new(env!("GENTLE_DOT_BUILD_NODE"))
+ .arg("--check").arg(&spec.args[0]).env_remove("NODE_OPTIONS").output().unwrap();
+ assert!(checked.status.success(), "Node rejected bundled entry: {}", String::from_utf8_lossy(&checked.stderr));
+ assert!(checked.stdout.is_empty());
+ assert!(checked.stderr.is_empty());
+ // Use the canonical long spelling even when the temp folder was given as an 8.3 path.
+ let plain = PathBuf::from(&extended.to_str().unwrap()[r"\\?\".len()..]);
+ assert_eq!(spec, launch_spec(|_| None, false, Some(&plain)));
+ assert!(!spec.program.starts_with(r"\\?\"));
+ assert!(!spec.args[0].starts_with(r"\\?\"));
+ for (name, value) in &spec.envs {
+ if name == "PATH" || name == "GENTLE_DOT_RUNTIME" { assert!(!value.contains(r"\\?\")); }
+ }
+ let overridden = launch_spec(|key| match key {
+ "GENTLE_DOT_NODE" => Some("explicit-node".into()),
+ "GENTLE_DOT_DAEMON_SCRIPT" => Some("explicit-entry".into()),
+ _ => None,
+ }, false, Some(&extended));
+ assert_eq!(overridden.program, "explicit-node");
+ assert_eq!(overridden.args, vec!["explicit-entry"]);
+ let absent = extended.join("missing");
+ assert_eq!(launch_spec(|_| None, false, Some(&absent)), launch_spec(|_| None, false, None));
+ }
+
+ fn fixture(name: &str) -> PathBuf {
+ let mut nonce = [0u8; 16];
+ getrandom::fill(&mut nonce).unwrap();
+ let token: String = nonce.iter().map(|b| format!("{b:02x}")).collect();
+ let runtime = std::env::temp_dir().join(format!("gentle {name} {token}"));
+ fs::create_dir_all(runtime.join("daemon")).unwrap();
+ fs::write(runtime.join("daemon/cli.mjs"), "export {};\n").unwrap();
+ // Synthetic fixture retained; no recursive cleanup of user paths.
+ runtime
+ }
+
+ #[test]
+ fn packaged_runtime_requires_every_artifact_and_the_harness_directory() {
+ let runtime = fixture("required-runtime");
+ let artifacts = [
+ "node/bin/node.exe", "daemon/package.json", "daemon/native/windows-stop.node",
+ "daemon/node_modules/gentle-pi/package.json", "bin/engram.exe", "bin/pi.cmd", "ui/index.html",
+ ];
+ for artifact in artifacts {
+ let error = validate_packaged_runtime(env_of(&[]), true, Some(&runtime)).unwrap_err();
+ assert!(error.contains(&runtime.join(artifact).display().to_string()));
+ let path = runtime.join(artifact);
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, b"").unwrap();
+ }
+ let harness = runtime.join("daemon/node_modules/gentle-pi/.gentle-ai");
+ assert!(validate_packaged_runtime(env_of(&[]), true, Some(&runtime)).unwrap_err()
+ .contains(&harness.display().to_string()));
+ fs::create_dir(harness).unwrap();
+ assert!(validate_packaged_runtime(env_of(&[]), true, Some(&runtime)).is_ok());
+ }
+
+ fn env_of<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
+ move |key| pairs.iter().find(|(name, _)| *name == key).map(|(_, value)| (*value).to_string())
+ }
+
+ #[test]
+ fn packaged_runtime_refuses_checkout_fallback_but_preserves_explicit_launches() {
+ assert!(validate_packaged_runtime(env_of(&[]), false, None).is_ok());
+ let error = validate_packaged_runtime(env_of(&[]), true, None).unwrap_err();
+ assert!(error.contains("will not silently use build-machine checkout paths"));
+ assert!(validate_packaged_runtime(env_of(&[("GENTLE_DOT_NODE", "custom-node")]), true, None).is_err());
+ assert!(validate_packaged_runtime(env_of(&[("GENTLE_DOT_DAEMON_SCRIPT", "custom-cli")]), true, None).is_err());
+ assert!(validate_packaged_runtime(env_of(&[
+ ("GENTLE_DOT_NODE", "custom-node"), ("GENTLE_DOT_DAEMON_SCRIPT", ""),
+ ]), true, None).is_err());
+ assert!(validate_packaged_runtime(env_of(&[
+ ("GENTLE_DOT_NODE", "custom-node"), ("GENTLE_DOT_DAEMON_SCRIPT", "custom-cli"),
+ ]), true, None).is_ok());
+ assert!(validate_packaged_runtime(env_of(&[]), true, Some(Path::new(env!("CARGO_MANIFEST_DIR")))).is_err());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/daemon/windows.rs b/apps/desktop/src-tauri/src/daemon/windows.rs
new file mode 100644
index 0000000..36a4af5
--- /dev/null
+++ b/apps/desktop/src-tauri/src/daemon/windows.rs
@@ -0,0 +1,124 @@
+//! Windows launch encoding; the native owned-process adapter lands in later slices.
+
+use std::io;
+
+const DESCRIPTOR_COUNT: usize = 4;
+const FOPEN: u8 = 1;
+const FPIPE: u8 = 8;
+const FDEV: u8 = 64;
+
+/// CRT/libuv lpReserved2: native int count, count flag bytes, then packed native HANDLEs.
+/// Handles are copied as bytes: the handle region is not necessarily aligned on 64-bit Windows.
+/// The caller must retain this buffer until CreateProcessW returns; cbReserved2 is its u16 length.
+/// Entries 0..2 are inherited NUL stdin and file-backed stdout/stderr; entry 3 is the
+/// dedicated connected duplex pipe. Do not reuse this for pipe-backed standard streams.
+/// This buffer does NOT constrain inheritance: an explicit STARTUPINFOEX handle list is required.
+pub(super) fn fd3_bootstrap(handles: [usize; DESCRIPTOR_COUNT]) -> io::Result<Vec<u8>> {
+ packed_bootstrap(&[FOPEN | FDEV, FOPEN, FOPEN, FOPEN | FPIPE], &handles)
+}
+
+fn packed_bootstrap(flags: &[u8], handles: &[usize]) -> io::Result<Vec<u8>> {
+ let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "invalid descriptor bootstrap size");
+ if flags.len() != handles.len() {
+ return Err(invalid());
+ }
+ let count = i32::try_from(handles.len()).map_err(|_| invalid())?;
+ let size = handles.len().checked_mul(std::mem::size_of::<usize>())
+ .and_then(|n| n.checked_add(flags.len()))
+ .and_then(|n| n.checked_add(std::mem::size_of::<i32>()))
+ .ok_or_else(invalid)?;
+ u16::try_from(size).map_err(|_| invalid())?;
+ let mut bytes = Vec::with_capacity(size);
+ bytes.extend_from_slice(&count.to_ne_bytes());
+ bytes.extend_from_slice(flags);
+ for handle in handles {
+ bytes.extend_from_slice(&handle.to_ne_bytes());
+ }
+ Ok(bytes)
+}
+
+/// Always quote each argument using Windows CRT escaping, including empty arguments.
+/// Reject embedded NUL rather than letting CreateProcessW silently truncate a command line.
+/// The executable must also be passed separately as lpApplicationName, never shell-interpreted.
+pub(super) fn command_line(program: &str, args: &[String]) -> io::Result<Vec<u16>> {
+ let mut line = String::new();
+ for arg in std::iter::once(program).chain(args.iter().map(String::as_str)) {
+ if arg.contains('\0') {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in launch argument"));
+ }
+ if !line.is_empty() {
+ line.push(' ');
+ }
+ line.push('"');
+ let mut slashes = 0;
+ for ch in arg.chars() {
+ if ch == '\\' {
+ slashes += 1;
+ continue;
+ }
+ let copies = if ch == '"' { slashes * 2 + 1 } else { slashes };
+ line.extend(std::iter::repeat('\\').take(copies));
+ slashes = 0;
+ line.push(ch);
+ }
+ line.extend(std::iter::repeat('\\').take(slashes * 2));
+ line.push('"');
+ }
+ let mut wide: Vec<u16> = line.encode_utf16().collect();
+ // CreateProcessW's limit includes the terminating NUL.
+ if wide.len() >= 32_767 {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "launch command line too long"));
+ }
+ wide.push(0);
+ Ok(wide)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn fd3_layout_is_packed_and_native_width() {
+ let handles = [0x11usize, 0x22, 0x33, 0x44];
+ let bytes = fd3_bootstrap(handles).unwrap();
+ assert_eq!(&bytes[..4], &4i32.to_ne_bytes());
+ assert_eq!(&bytes[4..8], &[65, 1, 1, 9]);
+ assert_eq!(bytes.len(), 8 + 4 * std::mem::size_of::<usize>());
+ for (i, handle) in handles.iter().enumerate() {
+ let start = 8 + i * std::mem::size_of::<usize>();
+ assert_eq!(&bytes[start..start + std::mem::size_of::<usize>()], &handle.to_ne_bytes());
+ }
+ }
+
+ #[test]
+ fn generic_layout_copies_handles_at_unaligned_offset() {
+ let handle = usize::MAX;
+ let bytes = packed_bootstrap(&[9], &[handle]).unwrap();
+ assert_eq!(&bytes[..4], &1i32.to_ne_bytes());
+ assert_eq!(bytes[4], 9);
+ assert_eq!(&bytes[5..], &handle.to_ne_bytes());
+ assert_eq!(packed_bootstrap(&[], &[]).unwrap(), 0i32.to_ne_bytes());
+ }
+
+ #[test]
+ fn invalid_counts_and_reserved_size_are_refused() {
+ assert!(packed_bootstrap(&[1], &[]).is_err());
+ let flags = vec![1; 65_536];
+ let handles = vec![1; flags.len()];
+ assert!(packed_bootstrap(&flags, &handles).is_err());
+ }
+
+ #[test]
+ fn command_quotes_empty_spaces_quotes_and_trailing_slashes() {
+ let wide = command_line("node.exe", &["".into(), "a b".into(), "a\"b".into(), "tail\\".into()]).unwrap();
+ assert_eq!(wide.last(), Some(&0));
+ let text = String::from_utf16(&wide[..wide.len() - 1]).unwrap();
+ assert_eq!(text, "\"node.exe\" \"\" \"a b\" \"a\\\"b\" \"tail\\\\\"");
+ }
+
+ #[test]
+ fn command_rejects_nul_and_excess_utf16_length() {
+ assert!(command_line("node.exe", &["x\0y".into()]).is_err());
+ assert!(command_line("node.exe", &["x".repeat(32_767)]).is_err());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/daemon_unavailable.rs b/apps/desktop/src-tauri/src/daemon_unavailable.rs
index 96e000d..e2136d9 100644
--- a/apps/desktop/src-tauri/src/daemon_unavailable.rs
+++ b/apps/desktop/src-tauri/src/daemon_unavailable.rs
@@ -9,6 +9,16 @@
#[path = "daemon/windows_record.rs"]
mod windows_record;
+// Exercise the real launch contracts and portable encoding without enabling Windows launch.
+#[cfg(test)]
+#[path = "daemon/launch.rs"]
+mod launch;
+#[cfg(test)]
+pub use launch::{ChildEndpoint, ChildProcess, LaunchSpec};
+#[cfg(test)]
+#[path = "daemon/windows.rs"]
+mod windows;
+
use crate::app_channel::{AppChannel, Handler};
use crate::health::check_health;
use std::path::PathBuf;