//! The Node web console as a supervised child: `console.mjs open` starts a //! detached server and prints the session's JSON, `stop` ends it, and a plain //! GET on the session URL is the health check. Knows nothing about Tauri. use std::io::{Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use serde::Serialize; use crate::session_reader; /// How long a health check waits for the console before calling it dead. The /// server is on loopback, so anything longer is a hang, not a slow network. const HEALTH_TIMEOUT: Duration = Duration::from_secs(3); /// The second, longer look a server gets before it is restarted, as the /// console's own `open` gives one: a machine busy with a test run can keep a /// healthy server from answering inside the first. const BUSY_HEALTH_TIMEOUT: Duration = Duration::from_secs(5); /// A running console session, as `console.mjs open` reports it. #[derive(Clone, Serialize)] pub struct ConsoleSession { pub sid: String, pub url: String, pub pid: u32, pub port: u16, /// The console says it can be framed by the app. An older one does not /// print this, and its page would be refused in the frame. pub embed: bool, } /// What the person is told when the installed console is too old for the app. pub const OLD_CONSOLE: &str = "The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again."; /// A supervisor's health check, copied out of it (`ConsoleSupervisor::probe`). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ConsoleProbe { url: String, stopped: bool, } impl ConsoleProbe { /// Was the supervisor stopped on purpose when the probe was taken. pub fn stopped(&self) -> bool { self.stopped } /// A GET on the session URL: any HTTP answer means the server is alive. pub fn health(&self) -> bool { self.health_within(HEALTH_TIMEOUT) } /// `health`, then once more with the longer timeout: a machine busy with /// a test run can keep a healthy server from answering inside the first. pub fn alive(&self) -> bool { self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) } fn health_within(&self, timeout: Duration) -> bool { if self.stopped { return false; } let Ok((host, port, path)) = split_url(&self.url) else { return false; }; let Some(addr) = (host.as_str(), port) .to_socket_addrs() .ok() .and_then(|mut a| a.next()) else { return false; }; let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else { return false; }; let _ = stream.set_read_timeout(Some(timeout)); let _ = stream.set_write_timeout(Some(timeout)); let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"); if stream.write_all(request.as_bytes()).is_err() { return false; } let mut status = [0u8; 64]; match stream.read(&mut status) { Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"), Err(_) => false, } } } /// One supervised console for one project folder. pub struct ConsoleSupervisor { console_dir: PathBuf, project_dir: PathBuf, embed_origin: String, workflow: String, session: ConsoleSession, stopped: bool, } fn err(e: E) -> String { e.to_string() } /// A `node console.mjs ...` call with no console window on Windows: the app is /// a GUI program, so a bare Command would flash one open per call. fn node_command(console_dir: &Path) -> Command { let mut command = Command::new("node"); // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's // directories (Task 9.9): run `node` with the PATH that finds it anyway. command.env("PATH", crate::node_check::resolved_path()); command.arg(console_dir.join("console.mjs")); #[cfg(windows)] { use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); // CREATE_NO_WINDOW } // Ctrl+C and a closing terminal signal the app's whole process group: a stop running there // would end before it stopped its console. #[cfg(unix)] { use std::os::unix::process::CommandExt; command.process_group(0); } command } /// The origin the app's own page has, which is what the console's embed mode /// must be told to allow as the frame parent. Tauri serves the page on /// `http://tauri.localhost` on Windows (and Android) and `tauri://localhost` /// on macOS and Linux. pub fn app_origin() -> &'static str { if cfg!(windows) { "http://tauri.localhost" } else { "tauri://localhost" } } /// The origin (`scheme://host[:port]`) of the app page's own URL, which is what /// the console's embed mode must allow as the frame parent. In a release build /// that is `app_origin()`, but `tauri dev` serves the page from its own dev /// server on a loopback port, so the real URL is asked rather than assumed. pub fn origin_of(url: &str) -> Option { let (scheme, rest) = url.split_once("://")?; let authority = rest.split(['/', '?', '#']).next()?; if authority.is_empty() || !matches!(scheme, "http" | "https" | "tauri") { return None; } Some(format!("{scheme}://{authority}")) } /// Where the installed console lives: an explicit override first (tests and /// dev), then the file the console keeps for the app, then the skill install. pub fn find_console_dir() -> Result { let has_console = |dir: &Path| dir.join("console.mjs").is_file(); if let Ok(dir) = std::env::var("PLAN2CODE_CONSOLE_DIR") { let dir = PathBuf::from(dir); if has_console(&dir) { return Ok(dir); } } // The console writes its pointer under PLAN2CODE_CONSOLE_HOME when that // relocates it, else under ~/.plan2code/console. let pointer = match std::env::var("PLAN2CODE_CONSOLE_HOME") { Ok(home) => PathBuf::from(home).join("console-dir"), Err(_) => { let home = std::env::home_dir().ok_or("no home folder found")?; home.join(".plan2code").join("console").join("console-dir") } }; if let Ok(text) = std::fs::read_to_string(&pointer) { let dir = PathBuf::from(text.trim()); if has_console(&dir) { return Ok(dir); } } let dir = std::env::home_dir() .ok_or("no home folder found")? .join(".agents") .join("skills") .join("plan2code") .join("references") .join("web-console"); if has_console(&dir) { return Ok(dir); } Err(format!( "the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, {} and {})", pointer.display(), dir.display() )) } /// Parse the one JSON object `console.mjs open` prints on stdout. fn parse_open_output(stdout: &[u8]) -> Result { let text = String::from_utf8_lossy(stdout); let line = text .lines() .rev() .find(|l| l.trim_start().starts_with('{')) .ok_or_else(|| format!("console open printed no JSON: {}", text.trim()))?; let value: serde_json::Value = serde_json::from_str(line.trim()).map_err(err)?; let get = |key: &str| value.get(key).and_then(|v| v.as_str().map(String::from)); let num = |key: &str| value.get(key).and_then(|v| v.as_u64()); Ok(ConsoleSession { sid: get("sid").ok_or("console open: no sid in output")?, url: get("url").ok_or("console open: no url in output")?, pid: num("pid").ok_or("console open: no pid in output")? as u32, port: num("port").ok_or("console open: no port in output")? as u16, embed: num("embed").is_some_and(|n| n >= 1), }) } /// Split `http://:` into its parts; the console only ever /// listens on loopback http. fn split_url(url: &str) -> Result<(String, u16, String), String> { let rest = url .strip_prefix("http://") .ok_or_else(|| format!("not an http url: {url}"))?; let (authority, path) = match rest.split_once('/') { Some((a, p)) => (a, format!("/{p}")), None => (rest, "/".to_string()), }; let (host, port) = authority .rsplit_once(':') .ok_or_else(|| format!("no port in url: {url}"))?; let port: u16 = port .parse() .map_err(|_| format!("bad port in url: {url}"))?; Ok((host.to_string(), port, path)) } impl ConsoleSupervisor { /// Find the installed console, run `open --workflow dashboard --no-open` in /// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the /// session it prints. pub fn start(project_dir: PathBuf, embed_origin: String) -> Result { Self::start_with_workflow(project_dir, embed_origin, "dashboard") } /// `start` for another workflow: today only `setup`, the agent-less page /// the app itself opens for Set up an agent (the one exception to the /// app never starting a console of its own). pub fn start_with_workflow( project_dir: PathBuf, embed_origin: String, workflow: &str, ) -> Result { let console_dir = find_console_dir()?; let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None, workflow)?; Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, workflow: workflow.to_string(), session, stopped: false, }) } /// `open` for the dashboard, or, with `resume`, the same session again on /// a new server (so the page and its place in a skill survive a dead server). /// A console the agent's `open` started and announced: this supervisor /// now owns its health and its stop, though it did not start it. pub fn adopt( project_dir: PathBuf, embed_origin: String, url: &str, sid: &str, ) -> Result { let console_dir = find_console_dir()?; let (_, port, _) = split_url(url)?; let session = ConsoleSession { sid: sid.to_string(), url: url.to_string(), pid: 0, port, embed: true, }; Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, workflow: "dashboard".to_string(), session, stopped: false, }) } fn open_session( console_dir: &Path, project_dir: &Path, embed_origin: &str, resume: Option<&str>, workflow: &str, ) -> Result { let mut command = node_command(console_dir); command.arg("open"); match resume { Some(sid) => command.args(["--resume", sid, "--no-open"]), None => command.args(["--workflow", workflow, "--no-open"]), }; let output = command .current_dir(project_dir) .env("PLAN2CODE_EMBED_ORIGIN", embed_origin) .output() .map_err(err)?; if !output.status.success() { return Err(format!( "console open failed: {}", String::from_utf8_lossy(&output.stderr).trim() )); } let session = parse_open_output(&output.stdout)?; if !session.embed { // Do not leave an old console running that the frame cannot show. let _ = node_command(console_dir) .args(stop_args(&session.sid)) .current_dir(project_dir) .output(); return Err(OLD_CONSOLE.to_string()); } Ok(session) } pub fn session(&self) -> &ConsoleSession { &self.session } /// The console moved to another address or session (an announced page that /// is not the one this supervisor opened): health, stop and the restart /// brief follow it from now on. An announced page is a running console, so /// a supervisor the person stopped is no longer stopped. pub fn follow(&mut self, url: &str, sid: &str) { self.stopped = false; if self.session.url == url && self.session.sid == sid { return; } if let Ok((_, port, _)) = split_url(url) { self.session.port = port; } self.session.url = url.to_string(); self.session.sid = sid.to_string(); } /// Was `stop()` called on this supervisor. pub fn stopped(&self) -> bool { self.stopped } /// A GET on the session URL: any HTTP answer means the server is alive. pub fn health(&self) -> bool { self.health_within(HEALTH_TIMEOUT) } fn health_within(&self, timeout: Duration) -> bool { self.probe().health_within(timeout) } /// What a health check needs, copied out, so a caller can check with the /// app's console lock released: the announce thread takes that lock to /// follow a new page, and a check can wait seconds on a busy machine. pub fn probe(&self) -> ConsoleProbe { ConsoleProbe { url: self.session.url.clone(), stopped: self.stopped, } } /// Health check plus a fresh `open` when the server is gone. Returns true /// when a new session was started. Never loops: the caller (the bar) asks /// and shows the outcome. pub fn restart_if_dead(&mut self) -> Result { if self.stopped || self.probe().alive() { return Ok(false); } self.reopen()?; Ok(true) } /// A fresh `open` on the same session (a new one only when it is gone from /// disk), with no health check: for a console the caller already found /// dead, or one the person stopped and now starts again. Clears `stopped`. pub fn reopen(&mut self) -> Result<(), String> { let sid = self.session.sid.clone(); let on_disk = session_on_disk(&sid); let (console_dir, project_dir, embed_origin, workflow) = ( &self.console_dir, &self.project_dir, &self.embed_origin, &self.workflow, ); self.session = resume_or_fresh(&sid, on_disk, |resume| { Self::open_session(console_dir, project_dir, embed_origin, resume, workflow) })?; self.stopped = false; Ok(()) } /// `console.mjs stop --session --force`: the console's own orderly /// shutdown. `--force` because the app's shutdown is not the agent's ending: /// the session may be unfinished, and `stop` refuses a session with no finish. pub fn stop(&mut self) -> Result<(), String> { if self.stopped { return Ok(()); } let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid); // Only a stop that could not run at all leaves the flag clear, as before. if !matches!(result, Err(StopError::NotRun(_))) { self.stopped = true; } result.map_err(StopError::into_message) } } /// `console.mjs stop --session --force` for any session, run in the /// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console /// this app does not supervise (one an agent announced and the window has /// since moved on from). pub fn stop_console_session( console_dir: &Path, project_dir: &Path, sid: &str, ) -> Result<(), String> { run_stop(console_dir, project_dir, sid).map_err(StopError::into_message) } /// One console an agent announced. `left` once that agent has ended while the /// window still showed the console: nothing needs it after the window moves on. struct Announced { sid: String, left: bool, } /// The console sessions this app's agents announced on macOS and Linux, by /// sid, in the order they came: the ones to stop when the agent that opened /// them ends, when the window moves on from one an ended agent left, or when /// the app quits. Consoles the app started itself are never recorded here, and /// one the app stopped for good is forgotten; the bar's stop, which keeps the /// session to start it again, leaves it recorded. Also holds the threads still /// stopping consoles after an agent's end or a new page, so a quit can wait for /// them. #[derive(Default)] pub struct AnnouncedConsoles { consoles: Mutex>, stops: Mutex>>, } impl AnnouncedConsoles { fn lock(&self) -> MutexGuard<'_, Vec> { self.consoles .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Remember `sid`, announced by a running agent; one already recorded is /// kept once, and is no longer left: the new agent joined it. pub fn record(&self, sid: &str) { let mut consoles = self.lock(); match consoles.iter_mut().find(|known| known.sid == sid) { Some(known) => known.left = false, None => consoles.push(Announced { sid: sid.to_string(), left: false, }), } } /// Remember `sid` as left by an agent that has ended; one a new agent /// announced in the meantime stays that agent's. fn leave(&self, sid: &str) { let mut consoles = self.lock(); if !consoles.iter().any(|known| known.sid == sid) { consoles.push(Announced { sid: sid.to_string(), left: true, }); } } /// Drop `sid` from the record: the app stopped that console itself. pub fn forget(&self, sid: &str) { self.lock().retain(|known| known.sid != sid); } /// Every recorded sid, in record order, and an empty record after. pub fn take_all(&self) -> Vec { std::mem::take(&mut *self.lock()) .into_iter() .map(|known| known.sid) .collect() } /// Every console left by an agent that has ended, but for the one the /// window follows, no longer recorded after. fn take_left(&self, followed: Option<&str>) -> Vec { let mut consoles = self.lock(); let (left, kept) = std::mem::take(&mut *consoles) .into_iter() .partition(|known| known.left && followed != Some(known.sid.as_str())); *consoles = kept; left.into_iter().map(|known| known.sid).collect() } /// The window follows `followed` now: stop each console an agent that has /// ended left under it, with `stop` on a thread of its own, since a stop /// runs `node`. A console of an agent still running is never touched. pub fn stop_left(&self, followed: &str, stop: F) where F: Fn(&str) + Send + 'static, { let sids = self.take_left(Some(followed)); if sids.is_empty() { return; } self.keep_stop(std::thread::spawn(move || { for sid in sids { stop(&sid); } })); } /// Keep a thread that is stopping consoles, so `finish_stops` can wait /// for it; threads already done are let go. fn keep_stop(&self, stop: std::thread::JoinHandle<()>) { let mut stops = self .stops .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); stops.retain(|kept| !kept.is_finished()); stops.push(stop); } /// Wait for every console stop still running on a thread, after an agent's /// end or a new page: the app may exit straight after, which would cut it /// short. pub fn finish_stops(&self) { let stops = std::mem::take( &mut *self .stops .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()), ); for stop in stops { let _ = stop.join(); } } } /// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`): /// it takes every console `announced` holds at once, inside the hook, so a /// console the next agent announces later is never taken by mistake, then /// stops each with `stop` on a thread of its own, since a stop runs `node` and /// the hook must return quickly. The console the window follows (`followed`) /// is left to the supervisor and recorded again, as left: stopped under the /// window, the bar's health poll would only start it again as a server no one /// tracks. It is stopped once the window moves on (`stop_left`), here if that /// happened while this thread was deciding, or at the quit. `followed` is asked /// on that thread too: it takes the console lock, held across `node` runs, /// while the hook runs with the agent manager locked. A caller about to stop /// the followed console waits for the thread first (`finish_stops`), so it is /// never recorded again after that stop. /// The macOS and Linux stand-in for Windows' Job Object, which ends every /// console an agent opened along with it. pub fn stop_announced_on_end( announced: Arc, followed: K, stop: F, ) -> Arc where K: Fn() -> Option + Send + Sync + 'static, F: Fn(&str) + Send + Sync + 'static, { let followed = Arc::new(followed); let stop = Arc::new(stop); Arc::new(move || { let sids = announced.take_all(); if sids.is_empty() { return; } let (followed, stop, record) = ( Arc::clone(&followed), Arc::clone(&stop), Arc::clone(&announced), ); announced.keep_stop(std::thread::spawn(move || { let shown = followed(); let mut left = false; for sid in sids { if shown.as_deref() == Some(sid.as_str()) { record.leave(&sid); left = true; } else { stop(&sid); } } if left { // A page that took the window since the question above found // nothing left to stop yet. for sid in record.take_left(followed().as_deref()) { stop(&sid); } } })); }) } /// Why a stop failed: it never ran (`node` could not be started), or it ran /// and the console said no. enum StopError { NotRun(String), Failed(String), } impl StopError { fn into_message(self) -> String { match self { StopError::NotRun(message) | StopError::Failed(message) => message, } } } fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> { let output = node_command(console_dir) .args(stop_args(sid)) .current_dir(project_dir) .output() .map_err(|e| StopError::NotRun(err(e)))?; if !output.status.success() { return Err(StopError::Failed(format!( "console stop failed: {}", String::from_utf8_lossy(&output.stderr).trim() ))); } Ok(()) } /// Is the session's folder still in the console's home. Unknown (no home /// directory) counts as there, so the answer never throws a session away. A /// sid that is not a plain folder name (empty, `..`, a path) is never there. pub fn session_on_disk(sid: &str) -> bool { if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) { return false; } session_reader::console_home() .is_none_or(|home| session_reader::session_dir(&home, sid).is_dir()) } /// The same session, so the page and a skill's place in it survive, tried /// twice. Only a session gone from disk starts a new one: falling back to a /// fresh dashboard while the folder is still there once swapped a build's page /// for an empty dashboard mid-run, and the agent went on posting to a session /// the window no longer showed. A failure is the bar's to report, with Retry. fn resume_or_fresh(sid: &str, on_disk: bool, mut open: F) -> Result where F: FnMut(Option<&str>) -> Result, { if !on_disk { return open(None); } open(Some(sid)).or_else(|_| open(Some(sid))) } impl Drop for ConsoleSupervisor { /// The app going away takes the console it started with it. `stop` is /// idempotent, so a session ended by hand just returns early here. fn drop(&mut self) { let _ = self.stop(); } } /// The arguments of the app's own `stop`: always `--force`, since the app's /// shutdown is not the agent's ending and `stop` refuses a session with no finish. fn stop_args(sid: &str) -> [&str; 4] { ["stop", "--session", sid, "--force"] } #[cfg(test)] mod tests { use super::*; #[test] fn announced_consoles_are_taken_once_in_order_without_duplicates() { let announced = AnnouncedConsoles::default(); announced.record("s1"); announced.record("s2"); announced.record("s1"); assert_eq!(announced.take_all(), vec!["s1", "s2"]); assert!(announced.take_all().is_empty(), "taking clears the record"); } #[test] fn forget_drops_one_console_and_keeps_the_rest() { let announced = AnnouncedConsoles::default(); announced.record("s1"); announced.record("s2"); announced.forget("s1"); announced.forget("never-recorded"); assert_eq!(announced.take_all(), vec!["s2"]); } #[test] fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() { // The hook runs with the agent manager locked, and the followed check // takes the console lock, which is held across `node` runs: asked // there, typing into the terminal stalled behind a console stop. let announced = Arc::new(AnnouncedConsoles::default()); let asked_on = Arc::new(Mutex::new(Vec::new())); let log = Arc::clone(&asked_on); let hook = stop_announced_on_end( Arc::clone(&announced), move || { log.lock().unwrap().push(std::thread::current().id()); None }, |_| {}, ); announced.record("s1"); hook(); announced.finish_stops(); let asked_on = asked_on.lock().unwrap(); assert_eq!(asked_on.len(), 1, "asked once"); assert_ne!(asked_on[0], std::thread::current().id()); } #[test] fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() { // New Session ends the old agent while the window still shows its // console: stopping it there only had the bar's poll bring it back as // a server nobody tracked, which then outlived the quit. let announced = Arc::new(AnnouncedConsoles::default()); let stopped = Arc::new(Mutex::new(Vec::::new())); let log = Arc::clone(&stopped); let hook = stop_announced_on_end( Arc::clone(&announced), || Some("followed".to_string()), move |sid| log.lock().unwrap().push(sid.to_string()), ); announced.record("followed"); announced.record("other"); hook(); announced.finish_stops(); assert_eq!(*stopped.lock().unwrap(), vec!["other"]); assert_eq!( announced.take_all(), vec!["followed"], "kept for the quit, or until the window moves on" ); } /// An agent that ended while the window showed its console `sid`. fn left_under_the_window(sid: &'static str) -> Arc { let announced = Arc::new(AnnouncedConsoles::default()); announced.record(sid); let hook = stop_announced_on_end( Arc::clone(&announced), move || Some(sid.to_string()), |sid| panic!("{sid} was stopped under the window"), ); hook(); announced.finish_stops(); announced } /// What `stop_left` stops once the window follows `followed`. fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec { let stopped = Arc::new(Mutex::new(Vec::::new())); let log = Arc::clone(&stopped); announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into())); announced.finish_stops(); let stopped = stopped.lock().unwrap().clone(); stopped } #[test] fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() { let announced = left_under_the_window("old"); announced.record("new"); assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown"); assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]); assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once"); assert_eq!(announced.take_all(), vec!["new"]); } #[test] fn the_window_moving_on_never_stops_a_running_agents_console() { // One agent may open a second session and still use the first. let announced = AnnouncedConsoles::default(); announced.record("first"); announced.record("second"); assert!(stopped_by_moving_to(&announced, "second").is_empty()); // A new agent that joins the console an ended one left makes it its own. let announced = left_under_the_window("joined"); announced.record("joined"); announced.record("second"); assert!(stopped_by_moving_to(&announced, "second").is_empty()); assert_eq!(announced.take_all(), vec!["joined", "second"]); } /// An agent's end whose console `old` the window shows, where `meanwhile` /// runs right after the hook asked which console that is: what it stopped. fn stopped_by_an_end_while(meanwhile: M) -> (Vec, Vec) where M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static, { let announced = Arc::new(AnnouncedConsoles::default()); let stopped = Arc::new(Mutex::new(Vec::::new())); let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced)); let shown = Mutex::new("old"); let hook = stop_announced_on_end( Arc::clone(&announced), move || { let mut shown = shown.lock().unwrap(); let answer = shown.to_string(); if answer == "old" { *shown = meanwhile(&record); } Some(answer) }, move |sid| log.lock().unwrap().push(sid.to_string()), ); announced.record("old"); hook(); announced.finish_stops(); let stopped = stopped.lock().unwrap().clone(); (stopped, announced.take_all()) } #[test] fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() { let (stopped, recorded) = stopped_by_an_end_while(|announced| { announced.record("new"); announced.stop_left("new", |sid| panic!("{sid} is not left yet")); "new" }); assert_eq!(stopped, vec!["old"]); assert_eq!(recorded, vec!["new"]); } #[test] fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() { let (stopped, recorded) = stopped_by_an_end_while(|announced| { announced.record("old"); announced.record("new"); "new" }); assert!(stopped.is_empty(), "{stopped:?}"); assert_eq!(recorded, vec!["old", "new"]); } #[test] fn finish_stops_waits_for_the_stop_a_new_page_started() { // Quitting right after New Session: the exit must not cut it short. let announced = left_under_the_window("old"); let stopped = Arc::new(Mutex::new(Vec::::new())); let log = Arc::clone(&stopped); announced.stop_left("new", move |sid| { std::thread::sleep(Duration::from_millis(300)); log.lock().unwrap().push(sid.to_string()); }); assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread"); announced.finish_stops(); assert_eq!(*stopped.lock().unwrap(), vec!["old"]); } #[test] fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() { // Quitting right after an agent ended: the exit must not cut its // consoles' stops short. let announced = Arc::new(AnnouncedConsoles::default()); let stopped = Arc::new(Mutex::new(Vec::::new())); let log = Arc::clone(&stopped); let hook = stop_announced_on_end( Arc::clone(&announced), || None, move |sid| { std::thread::sleep(Duration::from_millis(300)); log.lock().unwrap().push(sid.to_string()); }, ); announced.record("s1"); hook(); assert!( stopped.lock().unwrap().is_empty(), "the stop runs on a thread" ); announced.finish_stops(); assert_eq!(*stopped.lock().unwrap(), vec!["s1"]); } #[cfg(unix)] #[test] fn a_console_call_runs_in_a_process_group_of_its_own() { // Ctrl+C and a closing terminal signal the app's whole group: a stop // already running there ended before it stopped its console. let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"); let mut child = node_command(&console) .arg("help") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .spawn() .expect("node starts"); let pid = child.id() as i32; // SAFETY: getpgid only reads; the child is not waited for yet, so its id is its own. let group = unsafe { libc::getpgid(pid) }; let _ = child.wait(); assert_eq!(group, pid); } #[test] fn the_apps_stop_calls_pass_force() { let args = stop_args("20261101-120000-abcdef"); assert_eq!( args, ["stop", "--session", "20261101-120000-abcdef", "--force"] ); } #[test] fn splits_the_session_url() { let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap(); assert_eq!( (host.as_str(), port, path.as_str()), ("127.0.0.1", 51617, "/s/abc/") ); let (_, _, path) = split_url("http://localhost:9").unwrap(); assert_eq!(path, "/"); assert!(split_url("https://127.0.0.1:1/x").is_err()); assert!(split_url("http://127.0.0.1/x").is_err()); } #[test] fn origin_comes_from_the_pages_own_url() { assert_eq!( origin_of("http://127.0.0.1:1430/index.html").as_deref(), Some("http://127.0.0.1:1430") ); assert_eq!( origin_of("http://tauri.localhost/").as_deref(), Some("http://tauri.localhost") ); assert_eq!( origin_of("https://tauri.localhost").as_deref(), Some("https://tauri.localhost") ); assert_eq!( origin_of("tauri://localhost/index.html?x=1").as_deref(), Some("tauri://localhost") ); assert_eq!(origin_of("file:///x"), None); assert_eq!(origin_of("not a url"), None); assert_eq!(origin_of("http:///x"), None); } #[test] fn an_announced_console_is_adopted_with_its_port() { // Only needs a console to be installed; skipped where there is none. let Ok(dir) = find_console_dir() else { return }; let _ = dir; let mut sup = ConsoleSupervisor::adopt( PathBuf::from("."), "http://tauri.localhost".into(), "http://127.0.0.1:5555/s/t/", "sid-9", ) .unwrap(); assert_eq!( (sup.session().port, sup.session().sid.as_str()), (5555, "sid-9") ); assert!(sup.session().embed); assert!( ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err() ); sup.follow("http://127.0.0.1:6000/s/u/", "sid-10"); assert_eq!( (sup.session().port, sup.session().sid.as_str()), (6000, "sid-10") ); // Never started a server here: nothing for Drop to stop. sup.stopped = true; } fn opened(sid: &str) -> ConsoleSession { ConsoleSession { sid: sid.to_string(), url: "http://127.0.0.1:5/s/t/".into(), pid: 1, port: 5, embed: true, } } #[test] fn only_a_plain_folder_name_can_be_a_session_on_disk() { // `/sessions/` and `` are folders too: these must not pass. for sid in ["", ".", "..", "../x", "a/b", "a\\b"] { assert!(!session_on_disk(sid), "{sid:?} counted as a session"); } } #[test] fn a_failed_resume_of_a_session_still_on_disk_never_opens_a_fresh_dashboard() { // A build's console that was slow to answer: swapping its page for a // new dashboard left the agent posting to a session nobody could see. let mut calls = Vec::new(); let result = resume_or_fresh("s1", true, |resume| { calls.push(resume.map(str::to_string)); Err("busy".to_string()) }); assert!(result.is_err(), "the failure is reported, not papered over"); assert!( calls.iter().all(|c| c.as_deref() == Some("s1")), "only ever resumed: {calls:?}" ); assert_eq!(calls.len(), 2, "the resume is tried twice"); } #[test] fn a_resume_that_works_the_second_time_keeps_the_session() { let mut tries = 0; let session = resume_or_fresh("s1", true, |resume| { tries += 1; assert_eq!(resume, Some("s1")); if tries == 1 { Err("busy".to_string()) } else { Ok(opened("s1")) } }) .unwrap(); assert_eq!(session.sid, "s1"); } #[test] fn a_session_gone_from_disk_starts_a_fresh_dashboard() { let mut calls = Vec::new(); let session = resume_or_fresh("s1", false, |resume| { calls.push(resume.map(str::to_string)); Ok(opened(if resume.is_some() { "s1" } else { "s2" })) }) .unwrap(); assert_eq!(session.sid, "s2"); assert_eq!(calls, vec![None], "nothing on disk to resume"); } #[test] fn parses_open_output() { let json = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1} "#; let session = parse_open_output(json).unwrap(); assert_eq!( (session.sid.as_str(), session.port, session.pid), ("s1", 5, 42) ); assert!(session.embed); let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#; assert!( !parse_open_output(old).unwrap().embed, "a console that does not say it embeds is too old" ); assert!(parse_open_output(b"not json\n").is_err()); assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err()); } }