Skip to content

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

TypeScript

feat(desktop): activate the native Windows daemon lifecycle

Marcelito36f27aedab52
diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs
index bdda68c..b672b89 100644
--- a/apps/desktop/src-tauri/src/daemon.rs
+++ b/apps/desktop/src-tauri/src/daemon.rs
@@ -8,20 +8,21 @@
//! names the pid and the process start time); otherwise it refuses with
//! [`foreign_daemon_message`], which names the exit. An app without a channel attaches as before.
-// Windows stop/owner record codec. It is pure parsing, so its tests also run here; the
-// Windows lifecycle that writes and reads the record lands later in the chain.
+// Windows native launch adapter; Node channel adoption/exclusion remains separately guarded.
#[cfg(any(windows, test))]
mod windows_record;
mod launch;
pub use launch::*;
-#[cfg(test)]
+#[cfg(any(windows, 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};
+#[cfg(unix)]
+use std::fs;
+use std::fs::File;
#[cfg(unix)]
use std::fs::OpenOptions;
use std::io;
@@ -53,6 +54,7 @@ runs, or quit the process listening on port {port}), then choose \"Restart assis
}
/// A daemon this app launched, as the pid file records it.
+#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Launched {
pub pid: u32,
@@ -87,7 +89,7 @@ pub fn process_started(pid: u32) -> Option<u64> {
fields.get(19)?.parse().ok()
}
-#[cfg(not(any(target_os = "macos", target_os = "linux")))]
+#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
pub fn process_started(_pid: u32) -> Option<u64> {
None
}
@@ -189,6 +191,7 @@ fn stop_orphan(launch: Launched, grace: Duration) {
}
/// What [`Daemon::ensure_running`] does, from what it finds.
+#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartPlan {
/// Use the daemon that answers (an app without a channel loses nothing by attaching).
@@ -201,6 +204,7 @@ pub enum StartPlan {
Refuse,
}
+#[cfg(unix)]
pub fn start_plan(healthy: bool, owns_child: bool, wants_channel: bool, orphan: bool) -> StartPlan {
if !wants_channel {
return if healthy { StartPlan::Attach } else { StartPlan::Spawn };
@@ -216,6 +220,11 @@ pub fn start_plan(healthy: bool, owns_child: bool, wants_channel: bool, orphan:
}
}
+#[cfg(windows)]
+pub fn open_private_log(data_dir: &Path) -> io::Result<File> {
+ windows::open_private_log(data_dir)
+}
+
/// 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)]
@@ -227,6 +236,11 @@ pub fn open_private_log(data_dir: &Path) -> io::Result<File> {
Ok(log)
}
+#[cfg(windows)]
+pub fn channel_pair() -> io::Result<(crate::app_channel::ChannelStream, ChildEndpoint)> {
+ crate::app_channel::windows::channel_pair()
+}
+
/// 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)]
@@ -292,6 +306,19 @@ fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -
Ok(Box::new(command.spawn()?))
}
+#[cfg(windows)]
+fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<&ChildEndpoint>, data_dir: &Path) -> Result<windows::WindowsChild, windows::SpawnFailure> {
+ let channel = channel.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported,
+ "Windows channel-less launch awaits its equivalent graceful-stop adapter"))?;
+ windows::spawn(spec, log, channel, data_dir)
+}
+
+/// Checked Windows owned shutdown; keep the dedicated channel open until this succeeds.
+#[cfg(windows)]
+pub fn stop_child(child: &mut dyn ChildProcess, grace: Duration) -> io::Result<()> {
+ child.shutdown_owned(grace)
+}
+
/// Marks every descriptor from `first` up close-on-exec. Called between fork and exec: system
/// calls only.
#[cfg(all(unix, not(target_os = "macos")))]
@@ -350,11 +377,21 @@ pub enum RestartOutcome {
Failed(String),
}
+#[cfg(windows)]
+struct WindowsRecovery {
+ owner: windows::RecoveredLaunch,
+ // First failure is latched: never reconnect/re-send or reacquire this launch.
+ failure: Option<String>,
+}
+
pub struct Daemon {
port: u16,
data_dir: PathBuf,
runtime_dir: Option<PathBuf>,
child: Mutex<Option<Box<dyn ChildProcess>>>,
+ /// Every access is serialized by child first, including partial recovery owners.
+ #[cfg(windows)]
+ recovered: Mutex<Option<WindowsRecovery>>,
/// The private channel to the daemon this app spawned; attached daemons have none.
channel: Mutex<Option<Arc<AppChannel>>>,
/// Serves the daemon's requests; without it no channel is made.
@@ -377,6 +414,8 @@ impl Daemon {
data_dir,
runtime_dir,
child: Mutex::new(None),
+ #[cfg(windows)]
+ recovered: Mutex::new(None),
channel: Mutex::new(None),
handler: None,
refused: Mutex::new(None),
@@ -400,13 +439,13 @@ impl Daemon {
self
}
- #[cfg(test)]
+ #[cfg(all(test, unix))]
fn with_launch(mut self, spec: LaunchSpec) -> Self {
self.launch = Some(spec);
self
}
- #[cfg(test)]
+ #[cfg(all(test, unix))]
fn with_health(mut self, health: Arc<dyn Fn() -> bool + Send + Sync>) -> Self {
self.health = Some(health);
self
@@ -475,6 +514,142 @@ impl Daemon {
Ok(())
}
+ #[cfg(windows)]
+ fn windows_child_admission(&self, child: &Option<Box<dyn ChildProcess>>) -> Result<(), String> {
+ if child.as_ref().is_some_and(|child| child.launch_failed()) {
+ let mut refused = self.refused.lock().unwrap();
+ // Keep the original startup and cleanup errors for this retained owner. A later
+ // admission refusal must not erase the evidence explaining why it is retained.
+ let reason = refused.get_or_insert_with(||
+ "a failed Windows launch retains unfinished owned cleanup; stop must be retried".to_string());
+ return Err(reason.clone());
+ }
+ Ok(())
+ }
+
+ #[cfg(windows)]
+ fn windows_channel_admission(&self, channel: &Option<Arc<AppChannel>>) -> Result<(), String> {
+ // Caller holds child -> channel. A retained logically closed channel must be cleared
+ // by explicit successful checked stop, never forgotten or implicitly replaced by start.
+ if let Some(channel) = channel.as_ref().filter(|channel| !channel.is_open()) {
+ let detail = channel.close_error().map_or_else(
+ || "native closure not yet established".to_string(),
+ |code| format!("Windows error {code}"),
+ );
+ let reason = format!("the assistant's channel shutdown is unfinished ({detail})");
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ Ok(())
+ }
+
+ #[cfg(windows)]
+ fn windows_refuse(&self, reason: String) -> String {
+ self.refused.lock().unwrap().get_or_insert(reason).clone()
+ }
+
+ // Stop callers need this attempt's reason, not an unrelated sticky admission refusal.
+ #[cfg(windows)]
+ fn windows_stop_failure(&self, reason: String) -> Result<(), String> {
+ self.windows_refuse(reason.clone());
+ Err(reason)
+ }
+
+ #[cfg(windows)]
+ fn windows_wait_port(&self) -> Result<(), String> {
+ let deadline = Instant::now() + PORT_RELEASE;
+ while self.is_healthy() && Instant::now() < deadline { thread::sleep(Duration::from_millis(100)); }
+ if self.is_healthy() { return Err(foreign_daemon_message(self.port)); }
+ Ok(())
+ }
+
+ /// Caller holds child throughout acquisition, stop, exact deletion and port release.
+ /// The installed failure latch prevents all later admissions and stop reconnects.
+ /// Retirement deletes the exact launch record but leaves the owner witness as a
+ /// non-authoritative tombstone, removed by the next launch's `publish_owner`.
+ /// A leftover witness never becomes stop authority (#129).
+ #[cfg(windows)]
+ fn windows_recovery_admission(&self, child: &Option<Box<dyn ChildProcess>>) -> Result<(), String> {
+ if child.is_some() { return Ok(()); }
+ let mut slot = self.recovered.lock().unwrap();
+ if slot.is_none() {
+ windows::ensure_record_directory(&self.data_dir)
+ .map_err(|error| self.windows_refuse(format!("Windows record ancestry admission failed: {error}")))?;
+ // A launch whose owning app exited needs no stop: the kernel already ended its
+ // Job. A witnessed launch that is not proven ended is refused; only legacy records
+ // without a witness continue to the existing recovered-launch route.
+ match windows::retire_if_owner_exited(&self.data_dir) {
+ Ok(true) => {
+ eprintln!("gentle-dot: previous Windows launch retired after its owning app exited");
+ return Ok(());
+ }
+ Ok(false) => {}
+ Err(error) => {
+ let reason = format!("Windows previous launch admission refused: {error}");
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ }
+ match windows::acquire_recovered_launch(&self.data_dir) {
+ Ok(None) => return Ok(()),
+ Ok(Some(owner)) => *slot = Some(WindowsRecovery { owner, failure: None }),
+ Err(failure) => {
+ let reason = format!("Windows recorded launch admission refused: {}", failure.error);
+ if let Some(owner) = failure.retained {
+ *slot = Some(WindowsRecovery { owner, failure: Some(reason.clone()) });
+ }
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ }
+ }
+ let recovery = slot.as_mut().unwrap();
+ if let Some(reason) = &recovery.failure {
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason.clone());
+ }
+ let completion = recovery.owner.stop(ORPHAN_GRACE)
+ .and_then(|()| recovery.owner.delete_record())
+ .map_err(|error| format!("Windows recorded launch shutdown/deletion is unfinished: {error}"))
+ .and_then(|()| self.windows_wait_port());
+ if let Err(reason) = completion {
+ recovery.failure = Some(reason.clone());
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ drop(slot.take());
+ Ok(())
+ }
+
+ #[cfg(windows)]
+ fn start(&self, timeout: Duration) -> Result<(), String> {
+ let mut slot = self.child.lock().unwrap();
+ self.windows_child_admission(&slot)?;
+ self.windows_channel_admission(&self.channel.lock().unwrap())?;
+ self.windows_recovery_admission(&slot)?;
+ let owns_child = match slot.as_mut() {
+ Some(child) => match child.try_wait() {
+ Ok(None) => true,
+ Ok(Some(_)) => false,
+ Err(error) => {
+ child.retain_failure();
+ return Err(self.windows_refuse(format!("Windows owned launch status is uncertain: {error}")));
+ }
+ },
+ None => false,
+ };
+ *self.refused.lock().unwrap() = None;
+ if !owns_child && slot.is_none() && self.is_healthy() {
+ if self.handler.is_none() { return Ok(()); }
+ let reason = foreign_daemon_message(self.port);
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ self.spawn_locked(slot)?;
+ self.wait_ready(timeout)
+ }
+
+ #[cfg(unix)]
fn start(&self, timeout: Duration) -> Result<(), String> {
let wants_channel = self.handler.is_some();
let owns_child = self.owns_running();
@@ -509,16 +684,60 @@ impl Daemon {
self.wait_ready(timeout)
}
+ #[cfg(any(unix, test))]
fn spawn(&self) -> Result<(), String> {
self.spawn_locked(self.child.lock().unwrap())
}
fn spawn_locked(&self, mut slot: std::sync::MutexGuard<'_, Option<Box<dyn ChildProcess>>>) -> Result<(), String> {
+ #[cfg(windows)]
+ let mut channel_slot = self.channel.lock().unwrap();
+ // Recheck under both ownership guards before any launch work; keep the channel
+ // installed/locked until replacement installation has completed.
+ #[cfg(windows)]
+ self.windows_child_admission(&slot)?;
+ #[cfg(windows)]
+ self.windows_channel_admission(&channel_slot)?;
if let Some(child) = slot.as_mut() {
- if matches!(child.try_wait(), Ok(None)) {
- return Ok(());
+ #[cfg(unix)]
+ if matches!(child.try_wait(), Ok(None)) { return Ok(()); }
+ #[cfg(windows)]
+ match child.try_wait() {
+ Ok(None) => return Ok(()),
+ Ok(Some(_)) => child.shutdown_owned(Duration::ZERO)
+ .map_err(|error| self.windows_refuse(format!("cannot replace unfinished owned Windows daemon: {error}")))?,
+ Err(error) => {
+ child.retain_failure();
+ return Err(self.windows_refuse(format!("cannot establish owned Windows daemon status: {error}")));
+ }
}
}
+ #[cfg(windows)]
+ {
+ if slot.is_some() {
+ if let Err(reason) = self.windows_wait_port() {
+ slot.as_mut().unwrap().retain_failure();
+ return Err(self.windows_refuse(reason));
+ }
+ if let Some(channel) = channel_slot.as_ref() {
+ if let Err(error) = channel.close() {
+ return Err(self.windows_refuse(format!("cannot replace unfinished Windows channel: {error}")));
+ }
+ }
+ drop(channel_slot.take());
+ drop(slot.take());
+ }
+ // Direct spawn has the same fallible admission, under the same guard.
+ self.windows_recovery_admission(&slot)?;
+ if self.is_healthy() { return Err(self.windows_refuse(foreign_daemon_message(self.port))); }
+ *self.refused.lock().unwrap() = None;
+ }
+ #[cfg(windows)]
+ if self.handler.is_none() {
+ let reason = "Windows channel-less launch awaits its equivalent graceful-stop adapter".to_string();
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
let spec = match &self.launch {
Some(spec) => spec.clone(),
None => {
@@ -536,17 +755,60 @@ impl Daemon {
Some(_) => Some(channel_pair().map_err(|e| format!("cannot open the assistant's channel: {e}"))?),
None => None,
};
+ #[cfg(unix)]
let channel_end = pair.as_ref().map(|(_, daemon_end)| {
use std::os::fd::AsFd;
daemon_end.as_fd()
});
+ #[cfg(unix)]
let child = spawn_daemon(&spec, log, channel_end).map_err(|e| format!("cannot start {}: {e}", spec.program))?;
+ #[cfg(windows)]
+ let mut child = match spawn_daemon(&spec, log, pair.as_ref().map(|(_, endpoint)| endpoint), &self.data_dir) {
+ Ok(child) => child,
+ Err(mut failure) => {
+ let reason = format!("cannot start Windows daemon: {}; cleanup: {}", failure.primary,
+ failure.cleanup.as_ref().map_or_else(|| "no unfinished cleanup".to_string(), ToString::to_string));
+ if let Some(owner) = failure.unfinished.take() { *slot = Some(Box::new(owner)); }
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ };
// A relaunched app can then tell this daemon from one it did not launch (S35.2).
+ #[cfg(unix)]
if let Err(error) = record_launch(&self.data_dir, child.id()) {
eprintln!("gentle-dot: cannot record the assistant's pid: {error}");
}
- *slot = Some(child);
+ #[cfg(windows)]
+ {
+ // No channel-less adapter is claimed. Constructor above refuses that route.
+ let reader = match (pair, self.handler.as_ref()) {
+ (Some((endpoint, _)), Some(handler)) => AppChannel::start(endpoint, handler.clone()),
+ _ => Err(io::Error::new(io::ErrorKind::Unsupported, "Windows channel-present launch required")),
+ };
+ let channel = match reader {
+ Ok(channel) => channel,
+ Err(error) => {
+ child.reject_launch();
+ let cleanup = child.shutdown_owned(Duration::ZERO);
+ let reason = format!("cannot establish Windows daemon channel: {error}; cleanup: {}",
+ cleanup.as_ref().err().map_or_else(|| "completed".to_string(), ToString::to_string));
+ // Even completed channel-start failure retires only after an explicit
+ // checked stop/port release; do not discard its launch diagnosis.
+ *slot = Some(Box::new(child));
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ };
+ *slot = Some(Box::new(child));
+ *channel_slot = Some(channel.clone());
+ drop(channel_slot);
+ drop(slot);
+ if let Some(handler) = &self.handler { handler.opened(&channel); }
+ }
+ #[cfg(unix)]
+ { *slot = Some(child); }
// The daemon's end now lives only in the daemon.
+ #[cfg(unix)]
if let (Some((app_end, _)), Some(handler)) = (pair, &self.handler) {
match AppChannel::start(app_end, handler.clone()) {
Ok(channel) => {
@@ -562,27 +824,109 @@ impl Daemon {
/// True while a daemon spawned by this app is still running.
pub fn owns_running(&self) -> bool {
let mut slot = self.child.lock().unwrap();
- slot.as_mut().is_some_and(|child| matches!(child.try_wait(), Ok(None)))
+ #[cfg(unix)]
+ { slot.as_mut().is_some_and(|child| matches!(child.try_wait(), Ok(None))) }
+ #[cfg(windows)]
+ {
+ match slot.as_mut() {
+ None => false,
+ Some(child) => match child.try_wait() {
+ Ok(None) => true,
+ Ok(Some(_)) => false,
+ Err(error) => {
+ child.retain_failure();
+ self.windows_refuse(format!("Windows owned launch status is uncertain: {error}"));
+ false
+ }
+ },
+ }
+ }
}
/// Stops the daemon only if this app spawned it, and closes its channel.
+ #[cfg(unix)]
pub fn stop(&self) {
let child = self.child.lock().unwrap().take();
if let Some(mut child) = child {
stop_child(child.as_mut(), STOP_GRACE);
forget_launch(&self.data_dir, child.id());
}
- if let Some(channel) = self.channel.lock().unwrap().take() {
+ let channel = self.channel.lock().unwrap().take();
+ if let Some(channel) = channel {
channel.close();
}
}
+ /// Windows keeps ownership installed until checked close succeeds. The child guard
+ /// serializes stop with both start-plan admission and actual launch/replacement.
+ /// Returns this checked stop's outcome independently of the admission refusal latch.
+ #[cfg(windows)]
+ pub fn stop(&self) -> Result<(), String> {
+ let mut child_slot = self.child.lock().unwrap();
+ let mut channel_slot = self.channel.lock().unwrap();
+ // Only failed-launch cleanup may close first: its listener may not exist.
+ // Established launches must authenticate while fd3 remains open, otherwise
+ // daemon-side EOF aborts drain and prevents a clean managed root exit.
+ let close_first = child_slot.as_ref().map_or(true, |child| !child.shutdown_requires_channel());
+ if close_first {
+ if let Some(channel) = channel_slot.as_ref() {
+ if let Err(error) = channel.close() {
+ return self.windows_stop_failure(format!("the assistant's channel shutdown is unfinished: {error}"));
+ }
+ }
+ }
+ if let Some(child) = child_slot.as_mut() {
+ if child.shutdown_requires_channel() && channel_slot.is_none() {
+ let reason = "Windows channel-less graceful shutdown awaits its equivalent adapter".to_string();
+ *self.refused.lock().unwrap() = Some(reason.clone());
+ return Err(reason);
+ }
+ let grace = if child.shutdown_requires_channel() { STOP_GRACE } else { Duration::ZERO };
+ if let Err(error) = stop_child(child.as_mut(), grace) {
+ return self.windows_stop_failure(format!("owned Windows daemon shutdown/deletion is unfinished: {error}"));
+ }
+ if let Err(reason) = self.windows_wait_port() {
+ child.retain_failure();
+ return self.windows_stop_failure(reason);
+ }
+ }
+ if !close_first {
+ if let Some(channel) = channel_slot.as_ref() {
+ if let Err(error) = channel.close() {
+ // Even after exact retirement, unfinished parent I/O retains both
+ // installed owners. Never turn cancellation uncertainty into success.
+ return self.windows_stop_failure(format!("the assistant's channel shutdown is unfinished: {error}"));
+ }
+ }
+ }
+ let has_recovered = self.recovered.lock().unwrap().is_some();
+ if has_recovered { self.windows_recovery_admission(&child_slot)?; }
+ drop(child_slot.take());
+ drop(channel_slot.take());
+ Ok(())
+ }
+
/// Blocking: call off the main thread.
pub fn restart(&self, timeout: Duration) -> RestartOutcome {
if self.handler.is_none() && !self.owns_running() && self.is_healthy() {
return RestartOutcome::External;
}
+ #[cfg(unix)]
self.stop();
+ #[cfg(windows)]
+ if let Err(reason) = self.stop() { return RestartOutcome::Failed(reason); }
+ #[cfg(windows)]
+ {
+ let child = self.child.lock().unwrap();
+ let channel = self.channel.lock().unwrap();
+ if self.recovered.lock().unwrap().is_some()
+ || child.as_ref().is_some_and(|child| child.launch_failed())
+ || channel.as_ref().is_some_and(|channel| !channel.is_open())
+ || (child.is_some() && channel.is_none()) {
+ return RestartOutcome::Failed(self.refusal().unwrap_or_else(||
+ "owned Windows daemon shutdown is unfinished".into()));
+ }
+ }
match self.ensure_running(timeout) {
Ok(()) => RestartOutcome::Restarted,
Err(_) if self.refusal().is_some() => RestartOutcome::External,
@@ -591,6 +935,309 @@ impl Daemon {
}
}
+#[cfg(all(test, windows))]
+mod windows_ownership_tests {
+ use super::*;
+ use std::process::ExitStatus;
+ use std::sync::{mpsc, Barrier, TryLockError};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct RefusingHandler;
+ impl Handler for RefusingHandler {
+ fn approve(&self, _: &crate::approvals::ApprovalRequest) -> bool { false }
+ }
+ // Only the existing-child readiness branch is synthetic. No process is launched and
+ // these tests make no native-launch, adoption, or descendant-exclusion claim.
+ struct LiveChild;
+ impl ChildProcess for LiveChild {
+ fn id(&self) -> u32 { 1 }
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { Ok(None) }
+ fn kill(&mut self) -> io::Result<()> { panic!("no native child in ownership test") }
+ fn wait(&mut self) -> io::Result<ExitStatus> { panic!("no native child in ownership test") }
+ }
+
+ struct FailedChild;
+ impl ChildProcess for FailedChild {
+ fn id(&self) -> u32 { 2 }
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { Err(io::Error::other("unfinished launch")) }
+ fn kill(&mut self) -> io::Result<()> { panic!("no native child in admission test") }
+ fn wait(&mut self) -> io::Result<ExitStatus> { panic!("no native child in admission test") }
+ fn launch_failed(&self) -> bool { true }
+ }
+
+ #[test]
+ fn repeated_failed_launch_admission_preserves_primary_and_cleanup_errors() {
+ let ready = Arc::new(AtomicUsize::new(0));
+ let daemon = Daemon::new(1, PathBuf::new(), None).on_ready(Arc::new({
+ let ready = ready.clone(); move || { ready.fetch_add(1, Ordering::SeqCst); }
+ }));
+ *daemon.child.lock().unwrap() = Some(Box::new(FailedChild));
+ let original = "cannot start node.exe: resume failed; owned cleanup failed".to_string();
+ *daemon.refused.lock().unwrap() = Some(original.clone());
+ for with_closed_channel in [false, true] {
+ let peer = if with_closed_channel {
+ let (endpoint, peer) = channel_pair().unwrap();
+ let channel = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ channel.close().unwrap();
+ assert!(!channel.is_open());
+ *daemon.channel.lock().unwrap() = Some(channel);
+ Some(peer)
+ } else { None };
+ for _ in 0..2 {
+ assert_eq!(daemon.ensure_running(Duration::ZERO), Err(original.clone()));
+ assert_eq!(daemon.spawn(), Err(original.clone()));
+ assert_eq!(daemon.refusal(), Some(original.clone()));
+ assert!(daemon.child.lock().unwrap().as_ref().unwrap().launch_failed());
+ assert_eq!(ready.load(Ordering::SeqCst), 0);
+ }
+ drop(peer);
+ }
+ drop(daemon.channel.lock().unwrap().take());
+ drop(daemon.child.lock().unwrap().take());
+ }
+
+ #[test]
+ fn authenticated_stop_failure_keeps_channel_open_and_both_owners() {
+ struct StopChild { channel: Arc<AppChannel>, calls: Arc<AtomicUsize> }
+ impl ChildProcess for StopChild {
+ fn id(&self) -> u32 { 2 }
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { Ok(None) }
+ fn kill(&mut self) -> io::Result<()> { panic!("no native process in ordering test") }
+ fn wait(&mut self) -> io::Result<ExitStatus> { panic!("no native process in ordering test") }
+ fn shutdown_owned(&mut self, _: Duration) -> io::Result<()> {
+ assert!(self.channel.is_open(), "authenticated request must precede channel close");
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Err(io::Error::other("synthetic authenticated stop uncertainty"))
+ }
+ }
+ let daemon = Daemon::new(1, PathBuf::new(), None);
+ let (endpoint, peer) = channel_pair().unwrap();
+ let channel = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ let calls = Arc::new(AtomicUsize::new(0));
+ *daemon.child.lock().unwrap() = Some(Box::new(StopChild {
+ channel: channel.clone(), calls: calls.clone(),
+ }));
+ *daemon.channel.lock().unwrap() = Some(channel.clone());
+ let stale = "synthetic unrelated startup refusal".to_string();
+ *daemon.refused.lock().unwrap() = Some(stale.clone());
+ for _ in 0..2 {
+ // Debug permits a behavioral RED against the existing unit-returning stop,
+ // without requiring a missing diagnostic API to fail compilation instead.
+ let diagnostic = format!("{:?}", daemon.stop());
+ assert!(channel.is_open());
+ assert!(daemon.child.lock().unwrap().is_some());
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &channel));
+ assert_eq!(daemon.refusal(), Some(stale.clone()), "retain the admission latch independently");
+ assert_eq!(diagnostic, format!("{:?}", Err::<(), String>(
+ "owned Windows daemon shutdown/deletion is unfinished: synthetic authenticated stop uncertainty".into())),
+ "exit needs this stop attempt's exact reason, not the stale admission refusal");
+ }
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ drop(daemon.child.lock().unwrap().take());
+ let _ = daemon.stop(); // Cleanup only: the child was already dropped.
+ drop(peer);
+ }
+
+ #[test]
+ fn successful_windows_stop_has_no_exit_diagnostic_despite_stale_refusal() {
+ let mut daemon = Daemon::new(1, PathBuf::new(), None);
+ daemon.health = Some(Arc::new(|| false));
+ let (endpoint, peer) = channel_pair().unwrap();
+ let channel = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ *daemon.channel.lock().unwrap() = Some(channel.clone());
+ let stale = "synthetic unrelated startup refusal".to_string();
+ *daemon.refused.lock().unwrap() = Some(stale.clone());
+ let diagnostic = format!("{:?}", daemon.stop());
+ assert!(!channel.is_open());
+ assert!(daemon.child.lock().unwrap().is_none());
+ assert!(daemon.channel.lock().unwrap().is_none());
+ assert_eq!(daemon.refusal(), Some(stale));
+ assert_eq!(diagnostic, format!("{:?}", Ok::<(), String>(())),
+ "successful checked stop must not report a stale refusal at exit");
+ drop(peer);
+ }
+
+ #[test]
+ fn retained_failed_launch_cannot_be_healthy_or_replaced_and_failed_stop_keeps_both_owners() {
+ let ready = Arc::new(AtomicUsize::new(0));
+ let mut daemon = Daemon::new(1, PathBuf::new(), None)
+ .with_channel(Arc::new(RefusingHandler))
+ .on_ready(Arc::new({ let ready = ready.clone(); move || { ready.fetch_add(1, Ordering::SeqCst); } }));
+ daemon.health = Some(Arc::new(|| true));
+ *daemon.child.lock().unwrap() = Some(Box::new(FailedChild));
+ let (endpoint, peer) = channel_pair().unwrap();
+ let retained = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ *daemon.channel.lock().unwrap() = Some(retained.clone());
+ retained.test_inject_cancel_error(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as i32);
+ assert!(daemon.stop().is_err());
+ assert!(daemon.child.lock().unwrap().is_some());
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &retained));
+ assert!(!daemon.owns_running());
+ assert!(daemon.ensure_running(Duration::ZERO).is_err());
+ assert!(daemon.spawn().is_err());
+ assert_eq!(ready.load(Ordering::SeqCst), 0);
+ retained.test_inject_cancel_error(0);
+ assert!(daemon.stop().is_err()); // Synthetic child's unsupported checked cleanup must also retain both.
+ assert!(daemon.child.lock().unwrap().is_some());
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &retained));
+ assert!(matches!(daemon.restart(Duration::ZERO), RestartOutcome::Failed(_)));
+ drop(daemon.child.lock().unwrap().take());
+ let _ = daemon.stop(); // Cleanup only: the child was already dropped.
+ drop(peer);
+ }
+
+ struct CompletedChild(Arc<AtomicUsize>);
+ impl ChildProcess for CompletedChild {
+ fn id(&self) -> u32 { 3 }
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
+ use std::os::windows::process::ExitStatusExt;
+ Ok(Some(ExitStatus::from_raw(1))) // A forced exit is not a clean exit.
+ }
+ fn kill(&mut self) -> io::Result<()> { panic!("synthetic completed child") }
+ fn wait(&mut self) -> io::Result<ExitStatus> { panic!("synthetic completed child") }
+ fn shutdown_owned(&mut self, _: Duration) -> io::Result<()> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn completed_child_close_failure_blocks_restart_until_checked_retry() {
+ let mut daemon = Daemon::new(1, PathBuf::new(), None).with_channel(Arc::new(RefusingHandler));
+ daemon.health = Some(Arc::new(|| false));
+ let calls = Arc::new(AtomicUsize::new(0));
+ *daemon.child.lock().unwrap() = Some(Box::new(CompletedChild(calls.clone())));
+ let (endpoint, peer) = channel_pair().unwrap();
+ let retained = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ *daemon.channel.lock().unwrap() = Some(retained.clone());
+ retained.test_inject_cancel_error(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as i32);
+ let error = daemon.stop().unwrap_err();
+ assert!(error.starts_with("the assistant's channel shutdown is unfinished:"));
+ match daemon.restart(Duration::ZERO) {
+ RestartOutcome::Failed(reason) => assert_eq!(reason, error),
+ _ => panic!("restart must propagate checked stop failure"),
+ }
+ assert!(daemon.child.lock().unwrap().is_some());
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &retained));
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ retained.test_inject_cancel_error(0);
+ daemon.stop().unwrap();
+ assert!(daemon.child.lock().unwrap().is_none());
+ assert!(daemon.channel.lock().unwrap().is_none());
+ drop(peer);
+ }
+
+ #[test]
+ fn exited_root_replacement_retains_both_owners_when_old_channel_close_fails() {
+ let mut daemon = Daemon::new(1, PathBuf::new(), None).with_channel(Arc::new(RefusingHandler));
+ daemon.health = Some(Arc::new(|| false));
+ // Regression must stop before this deliberately invalid launcher is reached.
+ daemon.launch = Some(LaunchSpec { program: "must-not-launch".into(), args: vec![], envs: vec![] });
+ let calls = Arc::new(AtomicUsize::new(0));
+ *daemon.child.lock().unwrap() = Some(Box::new(CompletedChild(calls.clone())));
+ let (endpoint, peer) = channel_pair().unwrap();
+ let retained = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ *daemon.channel.lock().unwrap() = Some(retained.clone());
+ retained.test_inject_cancel_error(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as i32);
+ assert!(daemon.spawn().unwrap_err().starts_with("cannot replace unfinished Windows channel:"));
+ assert!(daemon.child.lock().unwrap().is_some());
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &retained));
+ assert!(retained.close_error().is_some());
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert!(daemon.spawn().is_err());
+ assert_eq!(calls.load(Ordering::SeqCst), 1, "admission rejects a logically closed retained channel");
+ retained.test_inject_cancel_error(0);
+ daemon.stop().unwrap();
+ assert!(daemon.child.lock().unwrap().is_none());
+ assert!(daemon.channel.lock().unwrap().is_none());
+ drop(peer);
+ }
+
+ fn failed_close_serializes_start(direct_spawn: bool) {
+ let ready = Arc::new(AtomicUsize::new(0));
+ let mut daemon = Daemon::new(1, PathBuf::new(), None)
+ .with_channel(Arc::new(RefusingHandler))
+ .on_ready(Arc::new({
+ let ready = ready.clone();
+ move || { ready.fetch_add(1, Ordering::SeqCst); }
+ }));
+ daemon.health = Some(Arc::new(|| true));
+ let daemon = Arc::new(daemon);
+ let (endpoint, peer) = channel_pair().unwrap();
+ let retained = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ *daemon.channel.lock().unwrap() = Some(retained.clone());
+ retained.test_inject_cancel_error(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as i32);
+ let entered = Arc::new(Barrier::new(2));
+ let release = Arc::new(Barrier::new(2));
+ retained.test_close_barriers(entered.clone(), release.clone());
+ let stopping = thread::spawn({ let daemon = daemon.clone(); move || daemon.stop() });
+ entered.wait();
+ // A controlled pause INSIDE checked close proves both ownership guards remain held:
+ // no empty slot can be observed and neither admission nor replacement can pass.
+ let child_locked = matches!(daemon.child.try_lock(), Err(TryLockError::WouldBlock));
+ let channel_locked = matches!(daemon.channel.try_lock(), Err(TryLockError::WouldBlock));
+ let (attempt_tx, attempt_rx) = mpsc::channel();
+ let (result_tx, result_rx) = mpsc::channel();
+ let starting = thread::spawn({
+ let daemon = daemon.clone();
+ move || {
+ attempt_tx.send(()).unwrap();
+ let result = if direct_spawn { daemon.spawn() } else { daemon.ensure_running(Duration::ZERO) };
+ result_tx.send(result).unwrap();
+ }
+ });
+ attempt_rx.recv().unwrap();
+ let premature_result = result_rx.try_recv().ok();
+ let completed_early = premature_result.is_some();
+ // Release/join the controlled stop before asserting invariants, including on a
+ // regression: an assertion must not strand a thread at the test-only barrier.
+ release.wait();
+ let stopped = stopping.join().unwrap();
+ let result = premature_result.unwrap_or_else(|| result_rx.recv_timeout(Duration::from_secs(2)).unwrap());
+ starting.join().unwrap();
+ assert!(child_locked, "start admission must remain blocked by checked stop");
+ assert!(channel_locked, "retained channel must remain installed and guarded");
+ assert!(!completed_early, "start must not complete during checked close");
+ assert!(result.is_err());
+ assert!(stopped.is_err(), "the controlled checked close must fail");
+ assert!(Arc::ptr_eq(daemon.channel.lock().unwrap().as_ref().unwrap(), &retained));
+ assert!(retained.close_error().is_some());
+ assert!(daemon.refusal().is_some());
+ assert_eq!(ready.load(Ordering::SeqCst), 0);
+
+ // Explicit checked retry, not start, is what permits the slot to be cleared.
+ retained.test_inject_cancel_error(0);
+ assert_eq!(daemon.stop(), Ok(()));
+ assert!(daemon.channel.lock().unwrap().is_none());
+ assert_eq!(retained.close_error(), None);
+ drop(peer);
+ // Exercise successful readiness after retry without invoking the absent launcher.
+ let (endpoint, next_peer) = channel_pair().unwrap();
+ let replacement = AppChannel::start(endpoint, Arc::new(RefusingHandler)).unwrap();
+ {
+ let mut child = daemon.child.lock().unwrap();
+ let mut channel = daemon.channel.lock().unwrap();
+ daemon.windows_channel_admission(&channel).unwrap();
+ *child = Some(Box::new(LiveChild));
+ *channel = Some(replacement.clone());
+ }
+ daemon.ensure_running(Duration::ZERO).unwrap();
+ assert_eq!(ready.load(Ordering::SeqCst), 1);
+ drop(daemon.child.lock().unwrap().take()); // Drop the synthetic child, never signal a PID.
+ let _ = daemon.stop(); // Cleanup only: the child was already dropped.
+ drop(next_peer);
+ }
+
+ #[test]
+ fn failed_close_blocks_start_plan_and_ready_until_checked_retry() {
+ failed_close_serializes_start(false);
+ }
+ #[test]
+ fn failed_close_blocks_actual_spawn_replacement_until_checked_retry() {
+ failed_close_serializes_start(true);
+ }
+}
+
#[cfg(all(test, unix))]
mod tests {
use super::*;
diff --git a/apps/desktop/src-tauri/src/daemon/windows.rs b/apps/desktop/src-tauri/src/daemon/windows.rs
index 18831a9..91c4788 100644
--- a/apps/desktop/src-tauri/src/daemon/windows.rs
+++ b/apps/desktop/src-tauri/src/daemon/windows.rs
@@ -1,6 +1,6 @@
//! Windows launch encoding and the native owned, channel-present process adapter.
//! Explicit transfer, suspended Job assignment and verification precede child execution.
-//! Owner-exit retirement and the daemon lifecycle that calls these land in later slices.
+//! The daemon lifecycle in daemon.rs drives these adapters, including owner-exit retirement.
use std::io;
@@ -75,6 +75,9 @@ pub(super) fn command_line(program: &str, args: &[String]) -> io::Result<Vec<u16
Ok(wide)
}
+#[cfg(windows)]
+pub(super) use native::{acquire_recovered_launch, ensure_record_directory, open_private_log, retire_if_owner_exited, spawn, RecoveredLaunch, SpawnFailure, WindowsChild};
+
#[cfg(windows)]
mod native {
use super::{command_line, fd3_bootstrap};
@@ -1919,10 +1922,10 @@ try {{
#[cfg(test)]
mod owner_exit_tests {
use super::*;
- use super::super::super::{windows_record, PID_FILE};
+ use super::super::super::{windows_record, Daemon, PID_FILE};
use crate::app_channel::windows::channel_pair;
use std::{fs, thread};
- use std::sync::mpsc;
+ use std::sync::{mpsc, Arc};
// Owner-exit recovery runs the launching app in a child copy of this test binary, so
// killing that exact child handle (never a PID lookup) closes the only Job handle.
@@ -2016,6 +2019,11 @@ setTimeout(()=>process.exit(74),60000);
run.helper.kill().unwrap();
run.helper.wait().unwrap();
}
+ fn recovering_daemon(dir: &Path) -> Daemon {
+ let mut daemon = Daemon::new(1, dir.to_path_buf(), None);
+ daemon.health = Some(Arc::new(|| false));
+ daemon
+ }
struct Sentinel(std::process::Child);
impl Drop for Sentinel {
fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); }
@@ -2035,13 +2043,19 @@ setTimeout(()=>process.exit(74),60000);
let witness = fs::read(run.dir.join(OWNER_FILE)).unwrap();
// Guards: a live witnessed owner refuses retirement; only its exit plus root
// exit permits exact deletion. Removing the live-owner check must fail here.
- let error = retire_if_owner_exited(&run.dir).unwrap_err();
- assert_eq!(error.to_string(), "the previous launch's owning app is still running; record retained");
+ let live = recovering_daemon(&run.dir);
+ let error = live.windows_recovery_admission(&None).unwrap_err();
+ assert_eq!(error, "Windows previous launch admission refused: \
+ the previous launch's owning app is still running; record retained");
+ assert_eq!(live.refusal(), Some(error));
assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), record);
assert_eq!(fs::read(run.dir.join(OWNER_FILE)).unwrap(), witness);
assert!(!exits_within(&run.root, 0) && !exits_within(&run.descendant, 0), "nothing was stopped");
+ drop(live);
kill_owner(&mut run);
- assert!(retire_if_owner_exited(&run.dir).unwrap());
+ let daemon = recovering_daemon(&run.dir);
+ assert_eq!(daemon.windows_recovery_admission(&None), Ok(()));
+ assert_eq!(daemon.refusal(), None);
assert!(!run.dir.join(PID_FILE).exists(), "exact record retired");
assert!(exits_within(&run.root, 0), "retirement waits for the recorded root");
assert!(exits_within(&run.descendant, 5000), "the kernel ended the whole owned Job");
@@ -2065,6 +2079,12 @@ setTimeout(()=>process.exit(74),60000);
assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), record,
"legacy records still need authorized manual recovery");
assert!(!run.dir.join(OWNER_FILE).exists());
+ let daemon = recovering_daemon(&run.dir);
+ let error = daemon.windows_recovery_admission(&None).unwrap_err();
+ assert!(error.starts_with("Windows recorded launch admission refused:"), "{error}");
+ assert_eq!(daemon.refusal(), Some(error));
+ assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), record,
+ "failed recovered admission retains the legacy record");
}
#[test]
@@ -2077,8 +2097,11 @@ setTimeout(()=>process.exit(74),60000);
let witness = fs::read(&path).unwrap();
// A damaged witness is not a legacy record: refuse rather than try the recovered stop.
fs::write(&path, b"not an owner witness\n").unwrap();
- let error = retire_if_owner_exited(&run.dir).unwrap_err();
- assert_eq!(error.to_string(), "Windows owner witness is invalid or unreadable; record retained");
+ let daemon = recovering_daemon(&run.dir);
+ let error = daemon.windows_recovery_admission(&None).unwrap_err();
+ assert_eq!(error, "Windows previous launch admission refused: \
+ Windows owner witness is invalid or unreadable; record retained");
+ assert_eq!(daemon.refusal(), Some(error));
assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), record);
assert_eq!(fs::read(&path).unwrap(), b"not an owner witness\n");
assert!(!exits_within(&run.root, 0) && !exits_within(&run.descendant, 0), "nothing was stopped");
@@ -2088,8 +2111,11 @@ setTimeout(()=>process.exit(74),60000);
fs::write(&path, &unbound).unwrap();
kill_owner(&mut run);
assert!(exits_within(&run.root, 5000));
- let error = retire_if_owner_exited(&run.dir).unwrap_err();
- assert_eq!(error.to_string(), "Windows owner witness does not match the recorded launch; record retained");
+ let daemon = recovering_daemon(&run.dir);
+ let error = daemon.windows_recovery_admission(&None).unwrap_err();
+ assert_eq!(error, "Windows previous launch admission refused: \
+ Windows owner witness does not match the recorded launch; record retained");
+ assert_eq!(daemon.refusal(), Some(error));
assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), record);
assert_eq!(fs::read(&path).unwrap(), unbound);
}
@@ -2113,9 +2139,12 @@ setTimeout(()=>process.exit(74),60000);
let created = ((created.dwHighDateTime as u64) << 32) | created.dwLowDateTime as u64;
let witness = windows_record::Owner::new(record.nonce(), other.id(), created).unwrap().encode();
fs::write(run.dir.join(OWNER_FILE), &witness).unwrap();
+ let daemon = recovering_daemon(&run.dir);
let started = Instant::now();
- let error = retire_if_owner_exited(&run.dir).unwrap_err();
- assert_eq!(error.to_string(), "recorded Windows root is still running after its owner exited; record retained");
+ let error = daemon.windows_recovery_admission(&None).unwrap_err();
+ assert_eq!(error, "Windows previous launch admission refused: \
+ recorded Windows root is still running after its owner exited; record retained");
+ assert_eq!(daemon.refusal(), Some(error));
assert!(started.elapsed() >= Duration::from_secs(9), "bounded wait for the recorded root");
assert_eq!(fs::read(run.dir.join(PID_FILE)).unwrap(), bytes);
assert_eq!(fs::read(run.dir.join(OWNER_FILE)).unwrap(), witness);
diff --git a/apps/desktop/src-tauri/src/daemon_unavailable.rs b/apps/desktop/src-tauri/src/daemon_unavailable.rs
deleted file mode 100644
index 8d08f03..0000000
--- a/apps/desktop/src-tauri/src/daemon_unavailable.rs
+++ /dev/null
@@ -1,180 +0,0 @@
-//! Temporary seam of the Windows port (gentle-dot#89). `daemon.rs` spawns the daemon with Unix
-//! primitives (fd 3, signals, file modes); its Windows side lands later in the chain and replaces
-//! this file. Until then the shell builds and opens on Windows, and every start fails instead of
-//! spawning anything: with [`foreign_daemon_message`] when a daemon this app did not launch holds
-//! the port (as on Unix, an app with a channel never attaches to one), else with [`UNAVAILABLE`].
-
-// The stop/owner record codec is tested on Windows too, ahead of the lifecycle that uses it.
-#[cfg(test)]
-#[path = "daemon/windows_record.rs"]
-mod windows_record;
-
-// Exercise the real launch contracts and portable encoding without enabling Windows launch.
-// Not every item is used until the Windows lifecycle replaces this file (runtime_dir, for one).
-#[cfg(test)]
-#[path = "daemon/launch.rs"]
-#[allow(dead_code)]
-mod launch;
-#[cfg(test)]
-pub use launch::{ChildEndpoint, ChildProcess, LaunchSpec, PID_FILE};
-#[cfg(test)]
-#[path = "daemon/windows.rs"]
-#[allow(dead_code)]
-mod windows;
-
-use crate::app_channel::{AppChannel, Handler};
-use crate::health::check_health;
-use std::path::PathBuf;
-use std::sync::{Arc, Mutex};
-use std::thread;
-use std::time::{Duration, Instant};
-
-const HEALTH_TIMEOUT: Duration = Duration::from_millis(300);
-
-/// Why the assistant does not start on Windows yet.
-pub const UNAVAILABLE: &str = "The Gentle Dot assistant does not run on Windows yet.";
-
-/// Same message as the Unix build: one the app did not launch holds the port.
-pub fn foreign_daemon_message(port: u16) -> String {
- format!(
- "Another Gentle Dot assistant is already running on port {port}, and this app did not start it \
-(for example `pnpm dev`, or one left running by an older version of the app). Gentle Dot only uses an \
-assistant it started itself, so connectors stay safe. Stop the other one (press Ctrl+C where `pnpm dev` \
-runs, or quit the process listening on port {port}), then choose \"Restart assistant\" in the Gentle Dot menu."
- )
-}
-
-/// Where a bundled runtime would live, as on Unix.
-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")))
-}
-
-#[derive(Debug, PartialEq, Eq)]
-pub enum RestartOutcome {
- Restarted,
- /// The daemon answers but was not started by this app.
- External,
- Failed(String),
-}
-
-/// The Unix `Daemon`'s interface, without a daemon behind it.
-pub struct Daemon {
- port: u16,
- wants_channel: bool,
- refused: Mutex<Option<String>>,
-}
-
-impl Daemon {
- pub fn new(port: u16, _data_dir: PathBuf, _runtime_dir: Option<PathBuf>) -> Self {
- Self { port, wants_channel: false, refused: Mutex::new(None) }
- }
-
- pub fn with_channel(mut self, _handler: Arc<dyn Handler>) -> Self {
- self.wants_channel = true;
- self
- }
-
- pub fn on_ready(self, _ready: Arc<dyn Fn() + Send + Sync>) -> Self {
- self
- }
-
- pub fn channel(&self) -> Option<Arc<AppChannel>> {
- None
- }
-
- pub fn is_healthy(&self) -> bool {
- check_health(self.port, HEALTH_TIMEOUT)
- }
-
- /// Why the last start refused the daemon on the port, if it did.
- pub fn refusal(&self) -> Option<String> {
- self.refused.lock().unwrap().clone()
- }
-
- pub fn wait_ready(&self, _timeout: Duration) -> Result<(), String> {
- Err(self.refusal().unwrap_or_else(|| UNAVAILABLE.into()))
- }
-
- pub fn wait_healthy(&self, timeout: Duration) -> bool {
- let deadline = Instant::now() + timeout;
- while Instant::now() < deadline {
- if self.is_healthy() {
- return true;
- }
- thread::sleep(Duration::from_millis(100));
- }
- false
- }
-
- /// This app never launches a daemon here, so with a channel it refuses any on the port.
- pub fn ensure_running(&self, _timeout: Duration) -> Result<(), String> {
- let refusal = (self.wants_channel && self.is_healthy()).then(|| foreign_daemon_message(self.port));
- *self.refused.lock().unwrap() = refusal.clone();
- Err(refusal.unwrap_or_else(|| UNAVAILABLE.into()))
- }
-
- pub fn owns_running(&self) -> bool {
- false
- }
-
- pub fn stop(&self) {}
-
- pub fn restart(&self, timeout: Duration) -> RestartOutcome {
- match self.ensure_running(timeout) {
- Ok(()) => RestartOutcome::Restarted,
- Err(_) if self.refusal().is_some() => RestartOutcome::External,
- Err(message) => RestartOutcome::Failed(message),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn every_start_fails_with_the_unavailable_message() {
- let daemon = Daemon::new(0, PathBuf::new(), None);
- assert_eq!(daemon.ensure_running(Duration::ZERO), Err(UNAVAILABLE.to_string()));
- assert_eq!(daemon.wait_ready(Duration::ZERO), Err(UNAVAILABLE.to_string()));
- assert_eq!(daemon.restart(Duration::ZERO), RestartOutcome::Failed(UNAVAILABLE.to_string()));
- assert!(daemon.channel().is_none());
- assert!(!daemon.owns_running());
- assert_eq!(daemon.refusal(), None);
- }
-
- /// A healthy `/health` answer on a free port, for as many probes as `answers`.
- fn foreign_daemon(answers: usize) -> u16 {
- let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
- let port = listener.local_addr().unwrap().port();
- thread::spawn(move || {
- for mut stream in listener.incoming().take(answers).flatten() {
- use std::io::{Read, Write};
- let _ = stream.read(&mut [0u8; 1024]);
- let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
- }
- });
- port
- }
-
- struct NoHandler;
- impl Handler for NoHandler {
- fn approve(&self, _request: &crate::approvals::ApprovalRequest) -> bool {
- false
- }
- }
-
- #[test]
- fn an_app_with_a_channel_refuses_a_daemon_it_did_not_launch() {
- let port = foreign_daemon(2);
- let daemon = Daemon::new(port, PathBuf::new(), None).with_channel(Arc::new(NoHandler));
- assert_eq!(daemon.ensure_running(Duration::ZERO), Err(foreign_daemon_message(port)));
- assert_eq!(daemon.refusal(), Some(foreign_daemon_message(port)));
- assert_eq!(daemon.wait_ready(Duration::ZERO), Err(foreign_daemon_message(port)));
- assert_eq!(daemon.restart(Duration::ZERO), RestartOutcome::External);
- assert!(daemon.channel().is_none());
- }
-}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 46e45da..ce18d00 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3,12 +3,6 @@ pub mod app_channel;
pub mod approvals;
pub mod computer;
pub mod config;
-#[cfg(unix)]
-pub mod daemon;
-// Temporary seam of the Windows port (gentle-dot#89): the daemon lifecycle is Unix only until its
-// Windows side lands, so on Windows the shell starts with an assistant that refuses to start.
-#[cfg(windows)]
-#[path = "daemon_unavailable.rs"]
pub mod daemon;
#[cfg(target_os = "macos")]
pub mod disclaimed;
diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs
index ac7cd0b..704e5da 100644
--- a/apps/desktop/src-tauri/src/shell.rs
+++ b/apps/desktop/src-tauri/src/shell.rs
@@ -898,7 +898,12 @@ pub fn run() {
.expect("failed to build Gentle Dot")
.run(|app, event| {
if let RunEvent::Exit = event {
+ #[cfg(unix)]
app.state::<Shell>().daemon.stop();
+ #[cfg(windows)]
+ if let Err(reason) = app.state::<Shell>().daemon.stop() {
+ eprintln!("gentle-dot: Windows shutdown was not confirmed: {reason}");
+ }
}
});
}