A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(desktop): end the daemon with its app, and let the engine own its home
Alan Buscaglia6571560d2fa4
diff --git a/apps/desktop/src-tauri/src/app_channel.rs b/apps/desktop/src-tauri/src/app_channel.rsindex 0828d57..1b0d2f0 100644--- a/apps/desktop/src-tauri/src/app_channel.rs+++ b/apps/desktop/src-tauri/src/app_channel.rs@@ -36,8 +36,12 @@ pub const APP_FD: i32 = 3;pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(150);/// Registering the computer helper waits for the daemon to start reading the channel.pub const REGISTER_TIMEOUT: Duration = Duration::from_secs(60);-/// A frame longer than this closes the channel.+/// A frame longer than this closes the channel. The daemon has the same rule, and a closed channel+/// stops the daemon (S35.2), so neither side ever sends a longer one: an oversized request fails+/// here without being written, and an oversized answer goes out as an error instead.const MAX_FRAME: u64 = 1024 * 1024;+/// Why a frame was not sent.+const TOO_LARGE: &str = "too large to send to the assistant";/// What the panel may ask the daemon through the app (S25.2): connector changes, approving a draft/// (declining one any window may), and importing. The computer helper is registered by the app.@@ -179,6 +183,9 @@ impl AppChannel {self.pending().insert(id, reply);if let Err(error) = self.write(&Frame::Request { id, method: method.into(), params }) {self.pending().remove(&id);+ if error.kind() == io::ErrorKind::InvalidInput {+ return Err(format!("This request is {TOO_LARGE}."));+ }return Err(format!("The assistant could not be reached: {error}"));}let result = answer.recv_timeout(timeout);@@ -209,8 +216,12 @@ impl AppChannel {self.pending.lock().unwrap_or_else(PoisonError::into_inner)}+ /// Writes one frame; one longer than [`MAX_FRAME`] is refused (`InvalidInput`) and nothing is written.fn write(&self, frame: &Frame) -> io::Result<()> {let mut line = serde_json::to_vec(frame).map_err(io::Error::other)?;+ if line.len() as u64 > MAX_FRAME {+ return Err(io::Error::new(io::ErrorKind::InvalidInput, TOO_LARGE));+ }line.push(b'\n');self.writer.lock().unwrap_or_else(PoisonError::into_inner).write_all(&line)}@@ -270,7 +281,10 @@ impl AppChannel {}other => Frame::Response { id, result: None, error: Some(format!("Unknown request: {other}")) },};- let _ = self.write(&frame);+ if self.write(&frame).is_err_and(|error| error.kind() == io::ErrorKind::InvalidInput) {+ let refused = Frame::Response { id, result: None, error: Some(format!("The answer is {TOO_LARGE}.")) };+ let _ = self.write(&refused);+ }}}@@ -542,6 +556,40 @@ mod tests {assert!(channel.command("w", json!({"type": "connector_disconnect", "connectorId": "notion"})).is_err());}+ #[test]+ fn a_frame_the_daemon_would_refuse_is_never_sent_and_the_channel_stays_open() {+ // The daemon closes the channel on a frame over 1 MiB, and then stops (S35.2).+ let (channel, mut daemon) = pair(Arc::new(Recorder::default()));+ let huge = json!({"type": "connector_setup", "connectorId": "slack", "pad": "x".repeat(1024 * 1024)});+ let refused = channel.command("w", huge).unwrap_err();+ assert!(refused.contains("too large"), "{refused}");+ assert!(channel.is_open());+ let waiting = std::thread::spawn({+ let channel = channel.clone();+ move || channel.request("computer_unregister", json!({}), Duration::from_secs(5))+ });+ // The first frame the daemon reads is the small request, not a piece of the large one.+ let Frame::Request { id, method, .. } = daemon.next() else { panic!("expected a request") };+ assert_eq!(method, "computer_unregister");+ daemon.send(&Frame::Response { id, result: Some(json!({})), error: None });+ assert_eq!(waiting.join().unwrap(), Ok(json!({})));+ }++ #[test]+ fn an_answer_too_large_for_the_daemon_becomes_an_error() {+ let handler = Arc::new(WithStore::default());+ let id = "connector/big/value/token";+ handler.store.put(id, &Secret::new("x".repeat(1024 * 1024).as_str())).unwrap();+ let (channel, mut daemon) = pair(handler);+ let Frame::Response { id: answered, result, error } = ask(&mut daemon, 7, "secret_get", json!({"id": id})) else {+ panic!("expected a response")+ };+ assert_eq!(answered, 7);+ assert_eq!(result, None);+ assert!(error.as_deref().is_some_and(|e| e.contains("too large")), "{error:?}");+ assert!(channel.is_open());+ }+#[test]fn closing_the_channel_ends_the_daemons_side() {let (channel, mut daemon) = pair(Arc::new(Recorder::default()));diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rsindex 534e86b..fbcc0c7 100644--- a/apps/desktop/src-tauri/src/daemon.rs+++ b/apps/desktop/src-tauri/src/daemon.rs@@ -1,5 +1,12 @@-//! Attaches to a running daemon or spawns one, and stops what it spawned. A daemon it spawns gets-//! its end of the app's private channel on fd 3 (S25.1, `app_channel`); one it attached to gets none.+//! Spawns the daemon, and stops what it spawned. A daemon it spawns gets its end of the app's+//! private channel on fd 3 (S25.1, `app_channel`) and stops by itself when that channel closes, so it+//! lives as long as this app, crashes included (S35.2).+//!+//! An app with a channel never attaches to a daemon it did not launch: that daemon has no channel,+//! so connectors would stay locked with no way out. When a healthy daemon holds the port at start,+//! the app stops it only if it can prove it launched it (`<data>/daemon.pid`, written at every spawn,+//! 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.pub use crate::app_channel::APP_FD;use crate::app_channel::{AppChannel, Handler};@@ -20,6 +27,139 @@ pub const DEV_ALLOWED_ORIGINS: &str = r#"["http://127.0.0.1:5173","http://localhconst 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.+const ORPHAN_GRACE: Duration = Duration::from_secs(10);+/// How long the port may take to be free after a recorded orphan stopped.+const PORT_RELEASE: Duration = Duration::from_secs(5);+/// `<data>/daemon.pid`: `<pid> <start time>` of the daemon this app launched last.+pub const PID_FILE: &str = "daemon.pid";++/// Why the app neither starts nor uses the assistant: one it 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."+ )+}++/// A daemon this app launched, as the pid file records it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Launched {+ pub pid: u32,+ /// When the process started, in the platform's own units; tells it from a later process with the same pid.+ pub started: u64,+}++/// When `pid` started, while it is a live process (not a zombie); `None` once it is gone.+#[cfg(target_os = "macos")]+pub fn process_started(pid: u32) -> Option<u64> {+ let pid = libc::c_int::try_from(pid).ok()?;+ // SAFETY: an all-zero proc_bsdinfo is valid, and proc_pidinfo writes at most its size.+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };+ let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_bsdinfo>()).ok()?;+ // SAFETY: the buffer is a proc_bsdinfo of `size` bytes, as PROC_PIDTBSDINFO expects.+ let written = unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&mut info as *mut libc::proc_bsdinfo).cast(), size) };+ if written != size || info.pbi_status == libc::SZOMB {+ return None;+ }+ Some(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)+}++/// When `pid` started (clock ticks after boot, `/proc/<pid>/stat`), while it is live; `None` once gone.+#[cfg(target_os = "linux")]+pub fn process_started(pid: u32) -> Option<u64> {+ let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;+ // The name may hold spaces and parentheses; the fields after it do not.+ let fields: Vec<&str> = stat.get(stat.rfind(')')? + 1..)?.split_whitespace().collect();+ if fields.first() == Some(&"Z") {+ return None;+ }+ fields.get(19)?.parse().ok()+}++#[cfg(not(any(target_os = "macos", target_os = "linux")))]+pub fn process_started(_pid: u32) -> Option<u64> {+ None+}++/// Records the daemon just spawned as `pid` (private, 0600).+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 mut file = OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(data_dir.join(PID_FILE))?;+ file.set_permissions(fs::Permissions::from_mode(0o600))?;+ use std::io::Write;+ writeln!(file, "{pid} {started}")+}++/// The daemon the pid file names, if it holds a launch.+pub fn recorded_launch(data_dir: &Path) -> Option<Launched> {+ let text = fs::read_to_string(data_dir.join(PID_FILE)).ok()?;+ let mut parts = text.split_whitespace();+ let launched = Launched { pid: parts.next()?.parse().ok()?, started: parts.next()?.parse().ok()? };+ (parts.next().is_none() && launched.pid > 1).then_some(launched)+}++/// The recorded daemon, while that same process still runs (a reused pid has another start time).+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`.+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));+ }+}++/// 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.+fn stop_orphan(launch: Launched, grace: Duration) {+ let Ok(pid) = libc::pid_t::try_from(launch.pid) else {+ return;+ };+ let same = || process_started(launch.pid) == Some(launch.started);+ for (signal, wait) in [(libc::SIGTERM, grace), (libc::SIGKILL, Duration::from_secs(2))] {+ if !same() {+ return;+ }+ // SAFETY: plain kill(2) on the process the record names, checked just above.+ unsafe { libc::kill(pid, signal) };+ let deadline = Instant::now() + wait;+ while same() && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(50));+ }+ }+}++/// What [`Daemon::ensure_running`] does, from what it finds.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StartPlan {+ /// Use the daemon that answers (an app without a channel loses nothing by attaching).+ Attach,+ /// Start a daemon, or wait for the one this app already started.+ Spawn,+ /// Stop the daemon an earlier app launched (the pid file proves it), then start one.+ ReplaceOrphan,+ /// A daemon this app cannot account for holds the port: neither attach nor stop it.+ Refuse,+}++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 };+ }+ if owns_child {+ StartPlan::Spawn+ } else if orphan {+ StartPlan::ReplaceOrphan+ } else if healthy {+ StartPlan::Refuse+ } else {+ StartPlan::Spawn+ }+}#[derive(Debug, Clone, PartialEq, Eq)]pub struct LaunchSpec {@@ -204,13 +344,29 @@ pub struct Daemon {channel: Mutex<Option<Arc<AppChannel>>>,/// Serves the daemon's requests; without it no channel is made.handler: Option<Arc<dyn Handler>>,+ /// Why the last start neither started nor attached ([`foreign_daemon_message`]).+ refused: Mutex<Option<String>>,/// Replaces [`launch_spec`] (tests).launch: Option<LaunchSpec>,+ /// Replaces the `/health` probe (tests).+ #[cfg(test)]+ health: Option<Arc<dyn Fn() -> bool + Send + Sync>>,}impl Daemon {pub fn new(port: u16, data_dir: PathBuf, runtime_dir: Option<PathBuf>) -> Self {- Self { port, data_dir, runtime_dir, child: Mutex::new(None), channel: Mutex::new(None), handler: None, launch: None }+ Self {+ port,+ data_dir,+ runtime_dir,+ child: Mutex::new(None),+ channel: Mutex::new(None),+ handler: None,+ refused: Mutex::new(None),+ launch: None,+ #[cfg(test)]+ health: None,+ }}/// Every daemon this app spawns gets a channel served by `handler`.@@ -225,6 +381,12 @@ impl Daemon {self}+ #[cfg(test)]+ fn with_health(mut self, health: Arc<dyn Fn() -> bool + Send + Sync>) -> Self {+ self.health = Some(health);+ self+ }+/// The channel to the daemon, only while one this app spawned runs and the channel is open.pub fn channel(&self) -> Option<Arc<AppChannel>> {if !self.owns_running() {@@ -234,9 +396,36 @@ impl Daemon {}pub fn is_healthy(&self) -> bool {+ #[cfg(test)]+ if let Some(health) = &self.health {+ return health();+ }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()+ }++ /// Waits until the daemon the app may use answers: one it launched when it wants a channel, any+ /// otherwise. Fails at once with the refusal when the port is held by a daemon it did not launch.+ pub fn wait_ready(&self, timeout: Duration) -> Result<(), String> {+ let deadline = Instant::now() + timeout;+ loop {+ if let Some(reason) = self.refusal() {+ return Err(reason);+ }+ if (self.handler.is_none() || self.owns_running()) && self.is_healthy() {+ return Ok(());+ }+ if Instant::now() >= deadline {+ return Err(format!("the assistant did not answer on port {} (see daemon.log)", self.port));+ }+ thread::sleep(Duration::from_millis(200));+ }+ }+/// Polls `/health` until it answers or `timeout` elapses.pub fn wait_healthy(&self, timeout: Duration) -> bool {let deadline = Instant::now() + timeout;@@ -251,17 +440,40 @@ impl Daemon {}}- /// Attaches to a healthy daemon, or spawns one. Blocking: call off the main thread.+ /// Spawns the daemon, or waits for the one this app spawned; see [`start_plan`] for a daemon+ /// already on the port. Blocking: call off the main thread.pub fn ensure_running(&self, timeout: Duration) -> Result<(), String> {- if self.is_healthy() {- return Ok(());+ let wants_channel = self.handler.is_some();+ let owns_child = self.owns_running();+ let orphan = if wants_channel && !owns_child { live_orphan(&self.data_dir) } else { None };+ *self.refused.lock().unwrap() = None;+ match start_plan(self.is_healthy(), owns_child, wants_channel, orphan.is_some()) {+ StartPlan::Attach => return Ok(()),+ StartPlan::Refuse => {+ let reason = foreign_daemon_message(self.port);+ *self.refused.lock().unwrap() = Some(reason.clone());+ return Err(reason);+ }+ StartPlan::ReplaceOrphan => {+ if let Some(orphan) = orphan {+ eprintln!("gentle-dot: stopping the assistant an earlier Gentle Dot left running (pid {})", orphan.pid);+ stop_orphan(orphan, ORPHAN_GRACE);+ forget_launch(&self.data_dir, orphan.pid);+ }+ let deadline = Instant::now() + PORT_RELEASE;+ while self.is_healthy() && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(100));+ }+ if self.is_healthy() {+ let reason = foreign_daemon_message(self.port);+ *self.refused.lock().unwrap() = Some(reason.clone());+ return Err(reason);+ }+ }+ StartPlan::Spawn => {}}self.spawn()?;- if self.wait_healthy(timeout) {- Ok(())- } else {- Err(format!("the assistant did not answer on port {} (see daemon.log)", self.port))- }+ self.wait_ready(timeout)}fn spawn(&self) -> Result<(), String> {@@ -284,6 +496,10 @@ impl Daemon {daemon_end.as_fd()});let child = spawn_daemon(&spec, log, channel_end).map_err(|e| format!("cannot start {}: {e}", spec.program))?;+ // A relaunched app can then tell this daemon from one it did not launch (S35.2).+ if let Err(error) = record_launch(&self.data_dir, child.id()) {+ eprintln!("gentle-dot: cannot record the assistant's pid: {error}");+ }*slot = Some(child);// The daemon's end now lives only in the daemon.if let (Some((app_end, _)), Some(handler)) = (pair, &self.handler) {@@ -309,6 +525,7 @@ impl Daemon {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() {channel.close();@@ -317,12 +534,13 @@ impl Daemon {/// Blocking: call off the main thread.pub fn restart(&self, timeout: Duration) -> RestartOutcome {- if !self.owns_running() && self.is_healthy() {+ if self.handler.is_none() && !self.owns_running() && self.is_healthy() {return RestartOutcome::External;}self.stop();match self.ensure_running(timeout) {Ok(()) => RestartOutcome::Restarted,+ Err(_) if self.refusal().is_some() => RestartOutcome::External,Err(message) => RestartOutcome::Failed(message),}}@@ -557,8 +775,9 @@ done"#;assert!(!channel.is_open());}- #[test]- fn a_daemon_the_app_only_attached_to_gets_no_channel() {+ /// A stand-in for a daemon this app did not launch (`pnpm dev`, or one an older app left): it+ /// answers `/health` on a port of its own.+ fn foreign_daemon() -> u16 {let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let port = listener.local_addr().unwrap().port();thread::spawn(move || {@@ -568,13 +787,116 @@ done"#;let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}");}});+ port+ }++ #[test]+ fn the_start_plan_attaches_only_where_no_channel_is_lost() {+ use StartPlan::*;+ // (healthy, owns its child, wants a channel, a live orphan it launched) -> plan+ let cases = [+ ((false, false, true, false), Spawn),+ ((true, true, true, false), Spawn),+ ((true, false, true, false), Refuse),+ ((true, false, true, true), ReplaceOrphan),+ ((false, false, true, true), ReplaceOrphan),+ ((true, true, true, true), Spawn),+ ((true, false, false, false), Attach),+ ((true, false, false, true), Attach),+ ((false, false, false, false), Spawn),+ ];+ for ((healthy, owns, wants, orphan), plan) in cases {+ assert_eq!(start_plan(healthy, owns, wants, orphan), plan, "{healthy} {owns} {wants} {orphan}");+ }+ }++ #[test]+ fn an_app_that_wants_a_channel_never_attaches_to_a_daemon_it_did_not_launch() {+ let port = foreign_daemon();let handler = Arc::new(Opened::default());- let daemon = Daemon::new(port, scratch_dir("channel-attached"), None)- .with_channel(handler.clone())- .with_launch(sh_spec(ECHO));- daemon.ensure_running(Duration::from_secs(5)).unwrap();+ let dir = scratch_dir("channel-foreign");+ let daemon = Daemon::new(port, dir.clone(), None).with_channel(handler.clone()).with_launch(sh_spec(ECHO));+ let refused = daemon.ensure_running(Duration::from_secs(5)).unwrap_err();+ assert_eq!(refused, foreign_daemon_message(port));+ // The message names the way out.+ assert!(refused.contains("pnpm dev") && refused.contains("Restart assistant"), "{refused}");+ assert!(!daemon.owns_running());assert!(daemon.channel().is_none());assert_eq!(*handler.0.lock().unwrap(), 0);+ // The panel gets the same reason instead of a connection to the other daemon.+ assert_eq!(daemon.wait_ready(Duration::from_millis(300)), Err(foreign_daemon_message(port)));+ assert_eq!(daemon.restart(Duration::from_secs(2)), RestartOutcome::External);+ assert!(!dir.join(PID_FILE).exists());+ }++ #[test]+ fn an_app_without_a_channel_still_attaches_to_a_running_daemon() {+ let port = foreign_daemon();+ let daemon = Daemon::new(port, scratch_dir("attach-no-channel"), None).with_launch(sh_spec(ECHO));+ daemon.ensure_running(Duration::from_secs(5)).unwrap();+ assert!(!daemon.owns_running());+ assert_eq!(daemon.wait_ready(Duration::from_millis(300)), Ok(()));+ }++ #[test]+ fn the_pid_file_names_only_the_process_it_recorded() {+ let dir = scratch_dir("pid-file");+ fs::create_dir_all(&dir).unwrap();+ assert_eq!(recorded_launch(&dir), None);+ let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ record_launch(&dir, child.id()).unwrap();+ assert_eq!(mode_of(&dir.join(PID_FILE)), 0o600);+ let recorded = recorded_launch(&dir).expect("a recorded launch");+ assert_eq!(recorded.pid, child.id());+ assert_eq!(live_orphan(&dir), Some(recorded));+ child.kill().unwrap();+ child.wait().unwrap();+ assert_eq!(live_orphan(&dir), None);+ // Another live process under that number (here this test's own) is never taken for it.+ let me = std::process::id();+ fs::write(dir.join(PID_FILE), format!("{me} {}\n", process_started(me).unwrap() + 1)).unwrap();+ assert_eq!(live_orphan(&dir), None);+ fs::write(dir.join(PID_FILE), "not a launch\n").unwrap();+ assert_eq!(recorded_launch(&dir), None);+ }++ #[test]+ fn a_relaunched_app_after_a_crashed_one_gets_a_channel() {+ let dir = scratch_dir("relaunch");+ // The port answers while the daemon named in the pid file runs.+ let health = {+ let dir = dir.clone();+ Arc::new(move || recorded_launch(&dir).is_some_and(|launch| process_started(launch.pid) == Some(launch.started)))+ };+ // An earlier app launched a daemon that outlived it without its channel (an older daemon).+ let orphan_script = "exec 3<&-; exec /bin/sleep 30";+ let crashed = Daemon::new(1, dir.clone(), None)+ .with_channel(Arc::new(Opened::default()))+ .with_launch(sh_spec(orphan_script))+ .with_health(health.clone());+ crashed.spawn().unwrap();+ let orphan = recorded_launch(&dir).expect("the launch is recorded");+ // The app is gone; the orphan is reparented and reaped by init (here, by this thread).+ let mut child = crashed.child.lock().unwrap().take().unwrap();+ drop(crashed);+ let reaper = thread::spawn(move || child.wait());++ let handler = Arc::new(Opened::default());+ let relaunched = Daemon::new(1, dir.clone(), None)+ .with_channel(handler.clone())+ .with_launch(sh_spec(ECHO))+ .with_health(health);+ relaunched.ensure_running(Duration::from_secs(10)).unwrap();+ assert!(reaper.join().unwrap().is_ok());+ assert_eq!(process_started(orphan.pid), None);+ let channel = relaunched.channel().expect("a channel to the new daemon");+ assert_eq!(*handler.0.lock().unwrap(), 1);+ let answer = channel.request("ping", serde_json::json!({}), Duration::from_secs(5)).unwrap();+ assert_eq!(answer, serde_json::json!({"echo": 1}));+ let recorded = recorded_launch(&dir).expect("the new launch is recorded");+ assert_ne!(recorded.pid, orphan.pid);+ relaunched.stop();+ assert!(!dir.join(PID_FILE).exists());}#[test]diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rsindex 291943a..153d98c 100644--- a/apps/desktop/src-tauri/src/shell.rs+++ b/apps/desktop/src-tauri/src/shell.rs@@ -168,15 +168,14 @@ async fn connector_command(app: AppHandle, client_id: String, message: serde_jso.map_err(err)?}-/// Waits until the daemon answers `/health`, then returns its URLs and token.+/// Waits until the daemon this app launched answers `/health`, then returns its URLs and token.+/// A daemon it did not launch is never used (S35.2): the answer is then the reason and its exit.#[tauri::command]async fn connection_info(app: AppHandle) -> CommandResult<ConnectionInfo> {let shell = app.state::<Shell>();let (config, daemon) = (shell.config.clone(), shell.daemon.clone());tauri::async_runtime::spawn_blocking(move || {- if !daemon.wait_healthy(DAEMON_START_TIMEOUT) {- return Err(format!("the assistant is not answering on port {}", config.port));- }+ daemon.wait_ready(DAEMON_START_TIMEOUT)?;read_connection_info(&config)}).await@@ -671,14 +670,12 @@ fn toggle_autostart(app: &AppHandle, menu: &Menu<tauri::Wry>) -> CommandResult {}fn restart_daemon(app: AppHandle) {- let daemon = app.state::<Shell>().daemon.clone();+ let (daemon, port) = (app.state::<Shell>().daemon.clone(), app.state::<Shell>().config.port);thread::spawn(move || match daemon.restart(DAEMON_START_TIMEOUT) {RestartOutcome::Restarted => {}- RestartOutcome::External => show_message(- &app,- MessageDialogKind::Info,- "The assistant was started outside Gentle Dot, so it cannot be restarted from here. Restart it where it was started.",- ),+ RestartOutcome::External => {+ show_message(&app, MessageDialogKind::Warning, &daemon::foreign_daemon_message(port))+ }RestartOutcome::Failed(error) => {show_message(&app, MessageDialogKind::Error, &format!("The assistant could not restart: {error}"))}@@ -789,10 +786,14 @@ pub fn run() {let daemon = Arc::new(Daemon::new(config.port, config.data_dir.clone(), runtime_dir).with_channel(Arc::new(service)),);- let starter = daemon.clone();+ let (starter, notifier) = (daemon.clone(), handle.clone());thread::spawn(move || {if let Err(error) = starter.ensure_running(DAEMON_START_TIMEOUT) {eprintln!("gentle-dot: {error}");+ // Another daemon holds the port (S35.2): say so, with the way out, instead of using it.+ if starter.refusal().is_some() {+ show_message(¬ifier, MessageDialogKind::Warning, &error);+ }}});let rose_hidden = position::load_rose_hidden(&desktop_file(&config));diff --git a/docs/design.md b/docs/design.mdindex 6b3ff35..b4d890e 100644--- a/docs/design.md+++ b/docs/design.md@@ -62,6 +62,7 @@ docs/ design, deployment guide, security checklist## 3. Agent supervisor- Spawns the bundled engine (`node <gentle-pi>/bin/gentle-shell.mjs --home <dataDir>/agent --mode rpc --session-dir <dataDir>/sessions --append-system-prompt <identity file>`) with `cwd` = the assistant's own workspace, `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home. A custom `workspace` (config or `GENTLE_DOT_WORKSPACE`) is never used as `cwd` and nothing is written there; it is passed as one more `--append-system-prompt` text: "The user's preferred working folder is <path>. Use absolute paths there unless told otherwise."+- Engine home (S35.3, #13): gentle-shell runs its first-run setup (the companion packages) only in a `--home` it created: one that did not exist, or that holds its marker `.gentle-shell-home`. The daemon writes `auth.json` and `mcp.json` there before the engine's first start, so at every start, before writing anything there, it writes that marker into the default `<dataDir>/agent` in gentle-shell's own format (`{"createdBy":"gentle-shell","version":"<gentle-pi version>"}`; gentle-shell only checks that the file exists) unless one is already there. A clean install then runs the setup, and an install left without it recovers on the next start. A home chosen with `GENTLE_DOT_AGENT_HOME` is never marked. Because the folder exists before the engine runs, gentle-shell's own bootstrap (the TUI's `tuiMode` and theme in `settings.json`) is skipped; RPC mode uses neither.- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. `GENTLE_PI_AGENTS=0` turns Gentle Shell's subagents off (no `subagent_*` or `orchestrator_*` tools) until S25. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`. The memory server the engine starts there outlives the engine, so when nothing listened on the private port as the daemon started, the daemon stops it when it closes: the PID listening on that port (`lsof`), only when its `/health` `instance_id` matches `<dataDir>/home/.engram/.instance-id`.- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook puts back the connector files from the daemon's in-memory state (§4, Connectors), then points `mcp.json` at the daemon's MCP proxy with a fresh key for this launch (S25.4; the previous key stops working), then hands the approval guard its policy, also from memory, in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, which of them the proxy fronts (`proxied`), and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).@@ -142,13 +143,13 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries, read only with every tool hidden, and never touches the source files; their header and environment values go to the app's secure store (below, Secrets), with references in `connectors.json`. A credential inside an imported address or command-line argument stays where it is (masked when shown; a documented limit).- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600; neither holds a secret. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." A change made to `connectors.json` while the daemon is not running is caught by its signature at the next start with the app (Integrity, below); `mcp.json` is always rewritten from memory. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above).- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, action, and every argument, key fields first) in the desktop app's native dialog, asked over the app channel (below; `DotBridge.askInApp`); windows only show an informational card. Declining, no answer (the app declines after 120 s, the daemon gives up at 130 s), no app to ask, the app quitting while it asks, an answer that is stopped, or a connector changed while it was asked refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).-- Secrets (S25.5, `packages/daemon/src/secret-source.ts`): bot tokens, client secrets, imported header and environment values, and OAuth sign-ins live in the desktop app's secure store (macOS: Keychain items the signed app creates, service `dev.gentleman.gentle-dot.connectors`; `apps/desktop/src-tauri/src/secure_store`). The daemon asks for them over the app channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`, below) and keeps them in memory only, until the channel closes; no secret is written to a file or a log. `connectors.json` holds `{"secretRef": "<id>"}` in each secret's place, with ids `connector/<id>/value/<key>`, `connector/<id>/env/<NAME>`, `connector/<id>/header/<Name>`, `connector/<id>/client-secret`, and `connector/<id>/signin` (pi-mcp's OAuth state as JSON). In a server of the user's own, every environment value, header, and `oauth.clientSecret` is treated as a secret unless it only names a typed field. Before the proxy uses a connector it reads the secrets it refers to; the daemon only reads ids it recorded after its own `put`. Without the app (a daemon it only attached to, `pnpm dev`, the web), a connector that needs a secret fails closed with "Open the Gentle Dot app to use this connector." (the proxy answers it to every request), and a connector without secrets keeps working; there is no file fallback. Removing a connector deletes its items.+- Secrets (S25.5, `packages/daemon/src/secret-source.ts`): bot tokens, client secrets, imported header and environment values, and OAuth sign-ins live in the desktop app's secure store (macOS: Keychain items the signed app creates, service `dev.gentleman.gentle-dot.connectors`; `apps/desktop/src-tauri/src/secure_store`). The daemon asks for them over the app channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`, below) and keeps them in memory only, until the channel closes; no secret is written to a file or a log. `connectors.json` holds `{"secretRef": "<id>"}` in each secret's place, with ids `connector/<id>/value/<key>`, `connector/<id>/env/<NAME>`, `connector/<id>/header/<Name>`, `connector/<id>/client-secret`, and `connector/<id>/signin` (pi-mcp's OAuth state as JSON). In a server of the user's own, every environment value, header, and `oauth.clientSecret` is treated as a secret unless it only names a typed field. Before the proxy uses a connector it reads the secrets it refers to; the daemon only reads ids it recorded after its own `put`. Without the app (a daemon started from a terminal such as `pnpm dev`, the web), a connector that needs a secret fails closed with "Open the Gentle Dot app to use this connector." (the proxy answers it to every request), and a connector without secrets keeps working; there is no file fallback. Removing a connector deletes its items.- Migration (once, when the app's channel is there): text secrets still in `connectors.json`, then the sign-ins of the old sign-in home (`<data>/connector-signin/mcp-auth.json`, the daemon's own, which win) and of the engine's old `<agentHome>/mcp-auth.json` (keyed `mcp__<id>|<url>`), are stored, read back, and compared before they leave the files; if one fails, the files stay as they were and the next start tries again. A sign-in for a connector that is no longer added is dropped (counted in the log). The old sign-in home (its `mcp.json` held the real servers) is removed. A 0-byte sign-in file holds nothing: it is removed and the removal is logged. One that cannot be read or is not a list of sign-ins may hold secrets: it is left as it is and reported, the other files still move, and the migration is not marked done, so the next start tries again (L117 A2). `connectors.json` then says `version: 2`, and a sign-in file that appears afterwards is reported once and left alone, never imported (L114 N1). Until a text secret has moved it stays in the file and is not used. Nothing secret is logged.- Integrity (S25.6, `packages/daemon/src/connector-integrity.ts`): every write of `connectors.json` (a change, a migration, a put-back) carries `mac`, the lowercase hex HMAC-SHA256 of the text `gentle-dot/connectors.json/v1\n` followed by the record without `mac` in canonical JSON (no whitespace; every object's keys sorted by UTF-16 code unit; arrays in order; strings, numbers, booleans, and null as `JSON.stringify` writes them). The key is 32 random bytes, kept as hex in the app's secure store under `integrity/connectors`, created on the first start with the app, and held only in memory; it is never written to a file or logged. At start the daemon listens (so the app's health check answers), then checks the file as it was read before anything rewrites it, watches it, migrates secrets, answers the app, or starts the engine. With the app: a file that was signed before (it has a `mac`, or the key already existed) whose `mac` is missing or wrong was changed while Gentle Dot was closed; it is moved to `<data>/connectors.rejected-<UTC time>.json` (0600; a planted link is moved as a link), the daemon starts with no connectors and a fresh signed record, the log says so once, and every window of that run gets the warning toast "Connectors were changed while Gentle Dot was closed, so they were set aside. Review them in Connectors." The Keychain items are not touched (a reference in the set-aside file is never read). The first start after T23e (an unsigned file and no key) creates the key and signs the file without refusing it. Without the app, the file cannot be checked: it is loaded as it is, the log says it was not verified, connectors that need a secret stay locked, and a signed file is put back byte for byte so its signature survives until a daemon the app launches checks it. With the app but a key that cannot be read or stored, the check fails closed: the file stays as it is, no secret is read, and every window gets "Gentle Dot could not check your connectors, so the ones that need a secret stay locked. Restart Gentle Dot to try again." A signed file deleted while Gentle Dot was closed (the key exists, the file is gone) starts with no connectors and every window gets "Your connectors file was removed while Gentle Dot was closed. Add your connectors again in Connectors." While running, a change is put back as before, signed. Limits: the signature has no counter, so putting back an older signed version of the file (for example one with a connector the user removed since) is accepted; sending actions still need the user's native approval. A same-user process that deletes the key's Keychain item and also removes `mac` makes the next start sign the file as a first start. A `connectors.json` written without the app (a migration rename of a `computer` entry) is unsigned and is refused at the next start with the app once the key exists; the key's Keychain item has the same limits as any other (§8).- Sign-in (S25.5, `packages/daemon/src/connector-oauth.ts`) runs in the daemon with pi-mcp's OAuth, as the engine's `mcp login` did (the CLI is no longer run): a stored refresh token signs in again without the browser; otherwise the authorization code flow (PKCE, dynamic client registration or the user's own client) against a loopback callback (`127.0.0.1`, a random port, or the connector's fixed redirect such as Slack's `http://localhost:38417/callback`). The whole flow keeps its state in memory; only the result is stored, once, with `secret_put`, and a refresh after a 401 stores the new tokens the same way. The daemon relays the authorization URL to the window that started it (`auth_event` `auth_url`, which opens the browser) and offers a `manual_code` prompt: when the browser cannot reach the loopback callback, the user pastes the address it ended on, and the daemon takes the code from it only when it is this sign-in's loopback address (port and path) with its `state`; nothing is fetched. Cancel closes the callback. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed text and codes are never logged (URLs are masked).- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the connector refers to a stored sign-in with tokens and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.-- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses.-- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (an attached daemon, `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.+- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses. A frame longer than 1 MiB closes the channel on either side, and a closed channel stops the daemon (below), so neither side sends one: an oversized request fails before it is written (a daemon approval is then refused), and an oversized answer goes out as an error. Lifetime (S35.2): a daemon launched with a channel stops when it closes, as on SIGTERM (engine, memory, and the connectors' servers stopped, then the process exits), whether the app quit, crashed, or was killed, since the kernel closes the app's end in every case; it stops listening first, so a relaunched app starts a daemon of its own. A daemon started without a channel keeps running until it is stopped.+- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (a daemon started from a terminal such as `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.- Stage 2 integrity (S25.6, Integrity above) covers the user's own servers too: the signature is over the whole record, so a file edited while the daemon is not running cannot add a server that runs a command, turn it on, claim an `origin`, change its command, arguments, URL, env, headers, `enabled`, or `mode`, or plant a secret reference (L117 A1) without being set aside at the next start with the app. Without the app it is still loaded, but connectors that need a secret are locked there.@@ -174,7 +175,7 @@ The assistant can see the screen and operate apps through a built-in MCP server- S24.4 Guards: a fixed blocklist (Gentle Dot itself, System Settings, SecurityAgent, loginwindow, Keychain Access, password managers), 10 actions per second, and a native per-action confirmation for risky actions (send, pay, buy, delete, submit, confirm, transfer, and their Spanish equivalents, by Accessibility role and title, by `return` on a default button, or by the declared `intent`).- S24.5 Permissions: the app reports and requests Accessibility and Screen Recording (`computer_permissions`, `computer_request_permission {kind}`). The Connectors screen shows a built-in "Computer" entry with both statuses, Grant buttons, Check again, the note that debug builds lose the grants on every rebuild (macOS ties them to the code signature), and a note when the current model does not accept images (`ConnectorInfo.noImages`, from the model's `input` in the engine's `get_state` and `set_model` answers).- S24.6 Visible state: the app emits `computer://state {active, endsAt?, reason?}` (`computer_status` gives the current one). While active, the rose shows the "in control" state (`dot-in_control`, mood `control`: accent rim, steady traveling light) and the panel shows "Controlling your Mac · mm:ss left" with Stop (`computer_stop`).-- S24.7 Wiring: the app registers its helper itself, over the app channel, right after it spawns the daemon (`computer_register {url, token}`; the daemon accepts only `http://127.0.0.1:<port>/mcp` and a header-safe key). A window cannot register, repoint, or remove it (L61 closed): the panel only calls `computer_endpoint` to know whether a helper exists. The daemon keeps the endpoint in memory, never in `connectors.json`, and renders `computer: {url, headers: {Authorization: "Bearer <key>"}, exposure: "direct"}` into `mcp.json`, then restarts the engine when idle. The guard's policy lists it under `builtin`, so its tools run without in-engine approval cards. It is removed on `computer_unregister` from the app or when the app's channel closes; windows coming and going do not touch it. A daemon the app only attached to has no channel, so it gets no helper. The key is never logged or sent to a window: `connectors` lists only a built-in "Computer" entry (`builtin: true`) that the connector messages cannot change or remove, no saved or imported connector can take the name `computer`, and the import scan never offers the helper.+- S24.7 Wiring: the app registers its helper itself, over the app channel, right after it spawns the daemon (`computer_register {url, token}`; the daemon accepts only `http://127.0.0.1:<port>/mcp` and a header-safe key). A window cannot register, repoint, or remove it (L61 closed): the panel only calls `computer_endpoint` to know whether a helper exists. The daemon keeps the endpoint in memory, never in `connectors.json`, and renders `computer: {url, headers: {Authorization: "Bearer <key>"}, exposure: "direct"}` into `mcp.json`, then restarts the engine when idle. The guard's policy lists it under `builtin`, so its tools run without in-engine approval cards. It is removed on `computer_unregister` from the app or when the app's channel closes; windows coming and going do not touch it. A daemon without a channel (`pnpm dev`) gets no helper; the app never uses one (§9, Daemon lifecycle). The key is never logged or sent to a window: `connectors` lists only a built-in "Computer" entry (`builtin: true`) that the connector messages cannot change or remove, no saved or imported connector can take the name `computer`, and the import scan never offers the helper.- S24.8 Speed: `batch {steps: [{tool, ...args}], intent?}` runs 1 to 20 steps of `click`, `move`, `drag`, `scroll`, `type`, `key`, `open_app`, or `wait` in one call and returns one screenshot. Each step takes the single tool's path (session and epoch, blocklist, risky confirmation, N1/N2 typing rules, coordinates mapped with the screenshot taken before the batch) and counts as one action for the rate limit; a full window delays the step instead of refusing it. Steps are 100 ms apart (1.5 s after `open_app`) so each step's guards read the screen the previous one left. The batch's `intent` applies to every step on top of the step's own. The first refused, declined, or failed step stops the batch; the error says which steps ran and comes with a fresh screenshot while the session lasts (none after Stop or panic). Malformed batches (empty, over 20, a nested `batch`, `screenshot`, `list_apps`, unknown tools, invalid arguments) run nothing. Actions settle 150 ms before their screenshot (`open_app` 1.5 s); screenshots are JPEG quality 65; debug builds optimize `image`, `zune-*`, and this crate (opt-level 1, because the generic encoder is compiled here).- S24.9 Yolo mode: in memory only, off at launch. `computer_set_yolo {enabled}` and the tray item "Yolo mode" switch it; turning it on asks a native confirmation ("Turn on yolo mode? Gentle Dot will send, pay, delete, and submit without asking you first, for up to 1 hour. Stop and ⌥⇧Esc still work.", Turn On / Cancel). While on, only the risky-action confirmation is skipped; the grant, blocklist, rate limit, Stop, and panic are unchanged, and Stop or panic end the session, not yolo mode. It turns itself off after 1 hour. `computer://state` and `computer_status` add `yolo` and `yoloEndsAt?`; every switch reports the resulting state, so a declined confirmation flips the UI switch back. Connectors → Computer shows a "Yolo mode" switch, the banner shows "Yolo", and the rose carries a yellow mark (`dot-yolo`).- S28 The pink glow where the agent acts:@@ -361,7 +362,7 @@ The app is single-instance (`tauri-plugin-single-instance`; D-Bus on Linux). A s### Daemon lifecycle-On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app gets the app channel on fd 3 (§4); one the app attached to does not, so its connectors cannot be changed from the panel. A daemon spawned by the app is stopped on Quit, which also closes the channel. Restart assistant restarts a spawned daemon, and reports through a dialog when the daemon was started outside the app. The UI connects only after `/health` answers.+On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app gets the app channel on fd 3 (§4) and stops by itself when that channel closes, so it never outlives the app, even after a crash or a kill (S35.2, #22). Each spawn records `<dataDir>/daemon.pid` (0600: the pid and the process start time, from `proc_pidinfo` on macOS and `/proc/<pid>/stat` on Linux); Quit stops the daemon, closes the channel, and removes the file. The app never attaches to a daemon it did not launch, which would have no channel and keep connectors locked. When a daemon answers at launch: if the pid file names a process that is still the same one (same start time), the app stops it (SIGTERM, SIGKILL after 10 s), waits for the port, and starts its own; otherwise (`pnpm dev`, or a daemon left by an app older than this rule) it starts nothing and shows a dialog naming the way out: stop the other one (Ctrl+C where `pnpm dev` runs, or the process on the port), then Restart assistant. The panel then gets that message from `connection_info` instead of a connection. A pid file names a process the app may signal, so a same-user process that rewrites it could make the app stop that process at the next launch, only while a daemon answers on the port; that user can already do so directly. Restart assistant restarts the daemon this app spawned, and shows the same dialog when another one holds the port. The UI connects only after the daemon this app spawned answers `/health`.## 10. Configurationdiff --git a/packages/daemon/src/app-channel.ts b/packages/daemon/src/app-channel.tsindex 9308ace..d2842dd 100644--- a/packages/daemon/src/app-channel.ts+++ b/packages/daemon/src/app-channel.ts@@ -21,7 +21,11 @@ import type { Duplex } from "node:stream";export const APP_FD = 3;/** Longer than the app's own 120 s dialog timeout, which answers "declined" first. */export const APPROVAL_WAIT_MS = 130_000;-/** A frame longer than this closes the channel; nothing legitimate comes close. */+/**+ * A frame longer than this closes the channel; nothing legitimate comes close. The app has the same+ * rule, and a closed channel stops the daemon (S35.2), so neither side ever sends a longer one: an+ * oversized request fails (an approval is refused) and an oversized answer becomes an error.+ */const MAX_FRAME = 1024 * 1024;/** One argument of the action, in the order shown. */@@ -105,13 +109,15 @@ export class AppChannel implements AppLink {request(method: string, params: unknown, timeoutMs: number): Promise<unknown> {if (!this.open) return Promise.reject(new Error("The Gentle Dot app is not connected."));const id = ++this.nextId;+ const line = frameLine({ kind: "request", id, method, params });+ if (!line) return Promise.reject(new Error(`The request ${method} is too large for the Gentle Dot app.`));return new Promise((resolve, reject) => {const timer = setTimeout(() => {this.pending.delete(id);reject(new Error(`The Gentle Dot app did not answer ${method} in time.`));}, timeoutMs);this.pending.set(id, { resolve, reject, timer });- this.write({ kind: "request", id, method, params });+ if (this.open) this.stream.write(line);});}@@ -186,7 +192,10 @@ export class AppChannel implements AppLink {}private write(frame: Frame): void {- if (this.open) this.stream.write(`${JSON.stringify(frame)}\n`);+ const line =+ frameLine(frame) ??+ frameLine({ kind: "response", id: frame.id, error: "The answer is too large to send." });+ if (this.open && line) this.stream.write(line);}private log(line: string): void {@@ -194,6 +203,12 @@ export class AppChannel implements AppLink {}}+/** The frame as one line, or undefined when it is longer than {@link MAX_FRAME}. */+function frameLine(frame: Frame): string | undefined {+ const json = JSON.stringify(frame);+ return Buffer.byteLength(json) > MAX_FRAME ? undefined : `${json}\n`;+}+/*** True when a child spawned the way the daemon spawns its children would hold the socket `identity`* (`dev:ino`) on `fd`. Node offers no way to mark an inherited descriptor close-on-exec; on macOSdiff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex fe4a5b5..d171f1b 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -65,6 +65,8 @@ async function main(): Promise<void> {};process.on("SIGINT", () => shutdown("SIGINT"));process.on("SIGTERM", () => shutdown("SIGTERM"));+ // A daemon the app launched stops itself when the app's channel closes (S35.2); so does the process.+ void daemon.closed.then(() => process.exit(0));}if (process.argv.includes("--self-check")) selfCheck();diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 16a804c..d873819 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -24,7 +24,13 @@ import {policyEnv,} from "./connectors.ts";import { approvalRequest } from "./extensions/approval-guard.ts";-import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemory } from "./isolation.ts";+import {+ claimEngineHome,+ ensureMemoryProject,+ ensurePrivateDir,+ isolatedAgentEnv,+ privateMemory,+} from "./isolation.ts";import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";@@ -64,7 +70,8 @@ export interface DaemonOptions {connectorTransport?: (connector: ProxiedConnector, credentials: UpstreamCredentials) => McpTransport;/*** The desktop app's end of its private channel (fd 3 when the app launched the daemon, S25.1).- * Without it, connector changes and approvals fail closed.+ * Without it, connector changes and approvals fail closed. With it, the daemon stops when the+ * channel closes (S35.2): the app that launched it is gone.*/appChannel?: Duplex;/** How long an approval waits for the app's answer; default 130 s (the app declines at 120 s). */@@ -89,7 +96,10 @@ export interface DotDaemon {url: string;bridge: DotBridge;supervisor: AgentSupervisor;+ /** Stops the daemon; calling it again returns the same stop. */close(): Promise<void>;+ /** Settles once the daemon stopped, whether `close` was called or the app's channel closed. */+ closed: Promise<void>;}const HELLO_TIMEOUT_MS = 5000;@@ -133,6 +143,10 @@ export function startupMessage(url: string, dataDir: string, interactive: booleaexport async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const log = options.log ?? (() => {});const token = ensureToken(options.dataDir);+ // Before anything is written there: the engine skips its first-run setup in a home it did not+ // create (S35.3). Only the assistant's default home; a home the user chose is never marked.+ if (options.agentHome && resolve(options.agentHome) === resolve(options.dataDir, "agent"))+ claimEngineHome(options.agentHome, log);mkdirSync(options.workspace, { recursive: true, mode: 0o700 });ensureMemoryProject(options.workspace);const folderArgs = options.preferredFolder@@ -274,7 +288,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {});} elselog(- "no desktop app channel: connector changes and approvals are refused, and connectors that need a secret fail closed",+ "no desktop app channel: connector changes and approvals are refused, and connectors that need a secret fail closed; to use them, stop this assistant and open the Gentle Dot app, which starts its own",);const server = createServer((req, res) => {@@ -307,18 +321,56 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {});port = (server.address() as AddressInfo).port;+ let stopped = () => {};+ const closed = new Promise<void>((done) => {+ stopped = done;+ });+ const shutdown = async () => {+ // Not listening any more first, so an app relaunched meanwhile starts a daemon of its own.+ const serverClosed = new Promise<void>((done) => server.close(() => done()));+ app?.close();+ for (const client of wss.clients) client.terminate();+ wss.close();+ // Stops waiting approvals and the connectors' servers (stdio ones are processes of the daemon).+ await proxy.close();+ await serverClosed;+ await supervisor.stop();+ connectorStore.close();+ await memory?.stop();+ };+ let stopping: Promise<void> | undefined;+ const close = (): Promise<void> => {+ if (!stopping) {+ stopping = shutdown();+ stopping.then(stopped, (error: Error) => {+ log(`the assistant did not stop cleanly: ${error.message}`);+ stopped();+ });+ }+ return stopping;+ };+ // The daemon lives as long as the app that launched it (S35.2): a daemon left behind with no+ // channel would keep connectors locked, and a relaunched app could not get a channel to it.+ app?.onClose(() => {+ log("the desktop app's channel closed; stopping the assistant");+ void close().catch(() => {});+ });+// Listening first keeps the app's health check answered while its store is asked for the key.await integrity;// Secrets that files still hold move into the app's store, once.- if (app)+ if (app?.connected)void connectorStore.migrate().catch((error: Error) => log(`connector secrets were not moved: ${error.message}`));// The files as the daemon writes them (an older version kept a hash), then watched.- connectorStore.enforce(false);- connectorStore.watch();-- await supervisor.start().catch((error: Error) => log(`agent failed to start: ${error.message}; retrying`));+ if (!stopping) {+ connectorStore.enforce(false);+ connectorStore.watch();+ await supervisor+ .start()+ .catch((error: Error) => log(`agent failed to start: ${error.message}; retrying`));+ }return {port,@@ -326,17 +378,8 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {url: `http://${options.host === "0.0.0.0" ? "127.0.0.1" : options.host}:${port}/#token=${token}`,bridge,supervisor,- async close() {- app?.close();- for (const client of wss.clients) client.terminate();- wss.close();- // Stops waiting approvals and the connectors' servers (stdio ones are processes of the daemon).- await proxy.close();- await new Promise<void>((done) => server.close(() => done()));- await supervisor.stop();- connectorStore.close();- await memory?.stop();- },+ close,+ closed,};}diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex ee03267..3b7d99d 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -2,7 +2,8 @@ import { execFile } from "node:child_process";import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import { homedir } from "node:os";-import { delimiter, join } from "node:path";+import { delimiter, dirname, join } from "node:path";+import { bundledGentleShell } from "./config.ts";import { resolveEngramBin, runtimeDir } from "./runtime.ts";/**@@ -27,6 +28,39 @@ export function ensurePrivateDir(path: string): void {chmodSync(path, 0o700);}+/** The file gentle-shell writes into a home it created (gentle-pi `bin/gentle-shell.mjs`). */+export const ENGINE_HOME_MARKER = ".gentle-shell-home";++/** The bundled gentle-pi's version, which gentle-shell names in its marker; informational only. */+function engineVersion(): string | undefined {+ try {+ const manifest = join(dirname(bundledGentleShell()), "..", "package.json");+ return (JSON.parse(readFileSync(manifest, "utf8")) as { version?: string }).version;+ } catch {+ return undefined;+ }+}++/**+ * Marks the assistant's own engine home as gentle-shell's (S35.3, #13). gentle-shell runs its+ * first-run setup (the companion packages) only in a home it created: one that did not exist, or+ * that holds its marker. The daemon writes `auth.json` and `mcp.json` there before the engine's+ * first start, so without the marker the engine took the home for someone else's and never set+ * it up. The marker has gentle-shell's own format (`{"createdBy":"gentle-shell","version":…}`; it+ * checks only that the file exists). One already there is left as it is. Call it only for the+ * default `<data>/agent`: a home the user chose may be theirs, and is never marked.+ */+export function claimEngineHome(agentHome: string, log: (line: string) => void = () => {}): void {+ ensurePrivateDir(agentHome);+ const content = `${JSON.stringify({ createdBy: "gentle-shell", version: engineVersion() })}\n`;+ try {+ writeFileSync(join(agentHome, ENGINE_HOME_MARKER), content, { flag: "wx", mode: 0o600 });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST")+ log(`could not mark the engine's home as its own: ${(error as Error).message}`);+ }+}+/** Variables that could point the engine back at the user's own setup. */const INHERITED_HOMES = ["PI_CODING_AGENT_DIR", "GENTLE_PI_AGENT_HOME", "GENTLE_SHELL_CONFIG"];diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex 5ef53b0..4c25594 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -163,6 +163,11 @@ export class AgentSupervisor {const term = setTimeout(() => child.kill("SIGTERM"), this.options.stopTimeoutMs ?? 5000);await closed;clearTimeout(term);+ // Stopped while the old process was closing: nothing is started again.+ if (this.stopping) {+ this.setState("stopped");+ return;+ }this.setState("restarting");await this.spawnAndInitialize();}diff --git a/packages/daemon/test/app-channel.test.ts b/packages/daemon/test/app-channel.test.tsindex 24e2764..f823d2c 100644--- a/packages/daemon/test/app-channel.test.ts+++ b/packages/daemon/test/app-channel.test.ts@@ -272,10 +272,11 @@ describe("the desktop app's channel (S25.2, S25.3)", () => {await expect(app.request("computer_register", { url: "http://evil.example/mcp", token: KEY }),).rejects.toThrow();- const pid = d.supervisor.pid;+ // The app quitting also stops the daemon it launched (S35.2).app.close();- await waitFor(() => !servers().computer);- await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ await d.closed;+ expect(servers().computer).toBeUndefined();+ expect(d.supervisor.state).toBe("stopped");});});diff --git a/packages/daemon/test/cli.test.ts b/packages/daemon/test/cli.test.tsindex 5bfa9ec..32bc1d3 100644--- a/packages/daemon/test/cli.test.ts+++ b/packages/daemon/test/cli.test.ts@@ -1,5 +1,6 @@import { spawn } from "node:child_process";import { readFileSync, statSync } from "node:fs";+import { createServer, type Socket, connect as unixConnect } from "node:net";import { join } from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";@@ -36,4 +37,50 @@ describe("gentle-dot command", () => {expect(output).toContain(`the access key is in ${join(dataDir, "token")}`);expect(statSync(dataDir).mode & 0o777).toBe(0o700);});++ it("a daemon launched with the app's channel exits when the app goes (S35.2, #22)", async () => {+ const dataDir = join(tempDir(), "data");+ const { app, daemon } = await socketPair();+ const child = spawn(process.execPath, [CLI], {+ env: {+ ...process.env,+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_PORT: "0",+ GENTLE_DOT_AGENT_BIN: process.execPath,+ GENTLE_DOT_AGENT_ARGS: JSON.stringify([FAKE_AGENT]),+ },+ stdio: ["ignore", "pipe", "pipe", daemon],+ });+ daemon.destroy();+ let output = "";+ const collect = (chunk: Buffer) => {+ output += chunk.toString();+ };+ child.stdout?.on("data", collect);+ child.stderr?.on("data", collect);+ const exited = new Promise<number | null>((resolve) => child.on("close", (code) => resolve(code)));+ try {+ // The daemon is up once it asks the app for something (the connectors' integrity key).+ await new Promise((resolve) => app.once("data", resolve));+ // The app quits, crashes, or is killed: the kernel closes its end of the pair.+ app.destroy();+ expect(await exited).toBe(0);+ } finally {+ child.kill("SIGKILL");+ }+ expect(output).toContain("the desktop app's channel closed; stopping the assistant");+ });});++/** A connected pair of Unix sockets (Node has no socketpair): the app's end and the daemon's. */+async function socketPair(): Promise<{ app: Socket; daemon: Socket }> {+ const path = join(tempDir(), "pair.sock");+ const server = createServer();+ await new Promise<void>((done) => server.listen(path, done));+ const accepted = new Promise<Socket>((resolve) => server.once("connection", resolve));+ const daemon = unixConnect(path);+ await new Promise((resolve) => daemon.once("connect", resolve));+ const app = await accepted;+ server.close();+ return { app, daemon };+}diff --git a/packages/daemon/test/computer.test.ts b/packages/daemon/test/computer.test.tsindex 2baff63..4727270 100644--- a/packages/daemon/test/computer.test.ts+++ b/packages/daemon/test/computer.test.ts@@ -228,7 +228,7 @@ describe("computer control registration (S24.7)", () => {});it("stays while windows come and go, and goes away when the app does", async () => {- const { servers, send, ws, app, connect: other } = await setup();+ const { d, servers, send, ws, app, connect: other } = await setup();const second = await other();send({ type: "computer_register", url: HELPER, token: KEY });await waitFor(() => servers().computer);@@ -236,11 +236,12 @@ describe("computer control registration (S24.7)", () => {ws.close();await settle();expect(servers().computer).toBeDefined();+ expect(computerOf(await second.list())).toBeDefined();+ // The app quitting also stops the daemon it launched (S35.2); the helper is gone from the files.app.close();- await waitFor(() => !servers().computer);- await second.find("connectors", (m) => computerOf(m.connectors) === undefined);- expect(computerOf(await second.list())).toBeUndefined();+ await d.closed;+ expect(servers().computer).toBeUndefined();});it("cannot be changed or removed through the connector messages, and a saved connector with its name is renamed", async () => {diff --git a/packages/daemon/test/connectors-proxy-gateway.test.ts b/packages/daemon/test/connectors-proxy-gateway.test.tsindex 2928ada..8aa1d4d 100644--- a/packages/daemon/test/connectors-proxy-gateway.test.ts+++ b/packages/daemon/test/connectors-proxy-gateway.test.ts@@ -7,11 +7,10 @@ import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { join } from "node:path";import { McpClient, type McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";-import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";+import type { ServerMessage } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { type DotDaemon, startDaemon } from "../src/daemon.ts";-import { NO_APP } from "../src/secret-source.ts";import { fakeApp, sendLikeThePanel } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { oauthOptions } from "./fake-oauth.ts";@@ -238,8 +237,8 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {expect(stale.status).toBe(401);});- it("refuses a sending action when the app quits while asking, and when there is no app", async () => {- const { d, notion, app, send, raw, messages, engineClient } = await setup();+ it("refuses a sending action when the app quits while asking, and then stops (S35.2)", async () => {+ const { d, notion, app, send, messages, engineClient } = await setup();// Connecting restarts the engine, and so does the mode change; each restart rotates the proxy// key, so wait for both before reading the key the engine would use.const beforeConnect = d.supervisor.pid;@@ -262,13 +261,12 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {messages.find((m) => m.type === "ask" && m.ask.title === "Allow Notion to create pages?"),);app.close();- expect((await pending)?.message).toMatch(/did not allow/);+ // Refused by the app being gone, or cancelled by the daemon stopping: either way nothing is sent.+ expect((await pending)?.message).toMatch(/did not allow|Nothing was sent/);- // Without the app its sign-in is gone from memory too: it fails closed before anything is asked.- expect((await failure(client.callTool("notion-create-pages", { title: "y" })))?.message).toBe(NO_APP);+ // The daemon the app launched stops with it: nothing reaches the server afterwards either.+ await d.closed;+ expect(await failure(client.callTool("notion-create-pages", { title: "y" }))).toBeDefined();expect(notion.calls()).toEqual([]);- // And a window cannot turn it back on or change it without the app.- raw({ type: "connector_mode", connectorId: "notion", mode: "read_only" });- await waitFor(() => messages.find((m) => m.type === "error" && m.message === APP_REQUIRED));});});diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex 2debb6b..675232e 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -37,6 +37,7 @@// FAKE_AGENT_START_DELAY_MS answer the first get_state only after this delay// FAKE_AGENT_DROP_CUSTOM load session files without their custom messages (a format drift)// FAKE_AGENT_PROMPTS_FILE append every prompt command (message, images, streamingBehavior) as JSONL+// FAKE_AGENT_MARKER_FILE write whether the `--home` folder held gentle-shell's `.gentle-shell-home` at launch// get_available_models lists MODELS; set_model and set_thinking_level change what// get_state reports, so tests can read the last values back. A model's `input` says whether it// accepts images, like the engine's models.@@ -73,6 +74,12 @@ let thinkingLevel = "medium";const argv = process.argv.slice(2);if (process.env.FAKE_AGENT_ARGS_FILE) writeFileSync(process.env.FAKE_AGENT_ARGS_FILE, JSON.stringify(argv));if (process.env.FAKE_AGENT_CWD_FILE) writeFileSync(process.env.FAKE_AGENT_CWD_FILE, process.cwd());+if (process.env.FAKE_AGENT_MARKER_FILE) {+ const home = argv[argv.indexOf("--home") + 1];+ const marked =+ argv.includes("--home") && home !== undefined && existsSync(join(home, ".gentle-shell-home"));+ writeFileSync(process.env.FAKE_AGENT_MARKER_FILE, JSON.stringify(marked));+}if (process.env.FAKE_AGENT_ENV_FILE) {writeFileSync(process.env.FAKE_AGENT_ENV_FILE,diff --git a/packages/daemon/test/lifecycle.test.ts b/packages/daemon/test/lifecycle.test.tsnew file mode 100644index 0000000..58224ef--- /dev/null+++ b/packages/daemon/test/lifecycle.test.ts@@ -0,0 +1,166 @@+// The daemon lives as long as the app that launched it (S35.2, #22), and the engine owns its home on+// the first start (S35.3, #13).+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { AppChannel } from "../src/app-channel.ts";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeApp } from "./fake-app.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const MARKER = ".gentle-shell-home";++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++async function start(+ options: { appChannel?: ReturnType<typeof fakeApp>; agentHome?: string; dataDir?: string } = {},+) {+ const dataDir = options.dataDir ?? tempDir();+ const markerFile = join(tempDir(), "marker.json");+ const logs: string[] = [];+ const fake = fakeAuthRuntime();+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome: options.agentHome ?? join(dataDir, "agent"),+ agentEnv: { ...process.env, FAKE_AGENT_MARKER_FILE: markerFile },+ backoffMs: [50],+ authRuntime: async () => fake.runtime,+ ...(options.appChannel ? { appChannel: options.appChannel.daemonEnd } : {}),+ log: (line) => logs.push(line),+ });+ daemons.push(d);+ const markedAtSpawn = () => JSON.parse(readFileSync(markerFile, "utf8")) as boolean;+ return { d, dataDir, logs, markedAtSpawn };+}++const health = (port: number) =>+ fetch(`http://127.0.0.1:${port}/health`).then(+ (res) => res.ok,+ () => false,+ );++const alive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+};++describe("the daemon's lifetime (S35.2)", () => {+ it("a daemon started by the app stops when its app channel closes", async () => {+ const app = fakeApp();+ const { d, logs } = await start({ appChannel: app });+ const engine = d.supervisor.pid;+ expect(engine).toBeDefined();+ expect(await health(d.port)).toBe(true);+ let stopped = false;+ void d.closed.then(() => {+ stopped = true;+ });++ app.close();+ await waitFor(() => stopped, 10_000);+ expect(d.supervisor.state).toBe("stopped");+ expect(alive(engine as number)).toBe(false);+ expect(await health(d.port)).toBe(false);+ expect(logs.join("\n")).toMatch(/channel closed.*stopping/);+ });++ it("a daemon without a channel keeps running as today", async () => {+ const { d } = await start();+ let stopped = false;+ void d.closed.then(() => {+ stopped = true;+ });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(stopped).toBe(false);+ expect(d.supervisor.state).toBe("ready");+ expect(await health(d.port)).toBe(true);+ });++ it("closing twice, or closing while the app quits, stops once", async () => {+ const app = fakeApp();+ const { d } = await start({ appChannel: app });+ const first = d.close();+ app.close();+ await Promise.all([first, d.close(), d.closed]);+ expect(d.supervisor.state).toBe("stopped");+ });+});++describe("frames the app would refuse are never sent (S35.2: a refused frame would close the channel)", () => {+ it("an approval too large for one frame is refused here and the channel stays open", async () => {+ const app = fakeApp(["allow"]);+ const channel = new AppChannel(app.daemonEnd);+ const huge = { name: "text", value: "x".repeat(1024 * 1024) };+ expect(await channel.approve({ connector: "Notion", action: "create pages", preview: [huge] })).toBe(+ false,+ );+ expect(app.asked).toEqual([]);+ expect(channel.connected).toBe(true);+ expect(+ await channel.approve({+ connector: "Notion",+ action: "create pages",+ preview: [{ name: "t", value: "x" }],+ }),+ ).toBe(true);+ channel.close();+ });+});++describe("the engine's own home (S35.3)", () => {+ const engineVersion = (+ createRequire(import.meta.url)("gentle-pi/package.json" as string) as { version: string }+ ).version;++ it("a fresh default data dir is marked as the engine's own before the first spawn", async () => {+ const { dataDir, markedAtSpawn } = await start();+ expect(markedAtSpawn()).toBe(true);+ const marker = JSON.parse(readFileSync(join(dataDir, "agent", MARKER), "utf8"));+ // The format gentle-shell writes itself (bin/gentle-shell.mjs, writeHomeOwnershipMarker).+ expect(marker).toEqual({ createdBy: "gentle-shell", version: engineVersion });+ });++ it("an overridden agent home is never marked", async () => {+ const chosen = tempDir();+ const { markedAtSpawn } = await start({ agentHome: chosen });+ expect(markedAtSpawn()).toBe(false);+ expect(existsSync(join(chosen, MARKER))).toBe(false);+ });++ it("an install stuck without the marker recovers on the next start", async () => {+ // What #13 left behind: the daemon's files in the home, and no marker.+ const dataDir = tempDir();+ const home = join(dataDir, "agent");+ mkdirSync(home, { recursive: true, mode: 0o700 });+ writeFileSync(join(home, "auth.json"), "{}\n");+ writeFileSync(join(home, "mcp.json"), `${JSON.stringify({ mcpServers: {} })}\n`);+ const { markedAtSpawn } = await start({ dataDir });+ expect(markedAtSpawn()).toBe(true);+ expect(readFileSync(join(home, "auth.json"), "utf8")).toBe("{}\n");+ });++ it("a marker gentle-shell already wrote is kept as it is", async () => {+ const dataDir = tempDir();+ const home = join(dataDir, "agent");+ mkdirSync(home, { recursive: true, mode: 0o700 });+ const own = `${JSON.stringify({ createdBy: "gentle-shell", version: "3.9.0" })}\n`;+ writeFileSync(join(home, MARKER), own);+ await start({ dataDir });+ expect(readFileSync(join(home, MARKER), "utf8")).toBe(own);+ });+});diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.tsindex 5e31410..e9c2e35 100644--- a/packages/daemon/test/supervisor.test.ts+++ b/packages/daemon/test/supervisor.test.ts@@ -132,6 +132,17 @@ describe("AgentSupervisor", () => {expect(events.some((e) => e.type === "interrupted")).toBe(false);});+ it("a stop during a restart starts nothing again (S35.2: the app quitting does both)", async () => {+ const { supervisor } = track(fakeSupervisor());+ await supervisor.start();+ const restarting = supervisor.restart();+ await supervisor.stop();+ await restarting;+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(supervisor.state).toBe("stopped");+ expect(supervisor.pid).toBeUndefined();+ });+it("stops cleanly and reports the stopped state", async () => {const { supervisor } = track(fakeSupervisor());await supervisor.start();