diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs new file mode 100644 index 00000000..77fda33e --- /dev/null +++ b/crates/ledger-host/src/app_server.rs @@ -0,0 +1,415 @@ +//! The app's books server: a child process of the window (plan P15 3.1). +//! +//! ```text +//! GOAL: the desktop app is the host. It starts the books server from its +//! own executable when the window starts and closes it by closing +//! the server's input when the window closes; a window that dies +//! any way at all leaves no server behind and no book half-closed; +//! and no window ever waits forever on a server that will not exit. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server as a +//! child, from its own executable, and closes it by closing its +//! input, exactly as the host does), D-77 (the app is the host), +//! D-84 (a child and not a thread: a crash in the window or its +//! graphics driver closes the server's input, and the books +//! close cleanly), WB-app-1, WB-app-2, WB-app-4; host.rs +//! INVARIANTS 3 and 10 (the host's own way: close the input, +//! never kill). +//! INVARIANTS: +//! 1. A start is refused, in words, when another program has these +//! books open: a host holds `run/host.lock`, or a server holds +//! `run/server.lock` (one still finishing after its window went +//! included). The locks are the existing ones; nothing is added to +//! them. Nothing is touched by a refused start. +//! 2. The server is this program's own executable, started as +//! `wanderbooks server --open IDS` (the companies the window +//! restored as tabs; `none` when there are none), its input a pipe +//! this struct holds, its output read for the ready line, its error +//! output the root's `run/server.log`. On Windows it has no console +//! window of its own. +//! 3. The server's input is closed when [`AppServer::stop`] is called, +//! when the value is dropped, and when this process ends for any +//! reason (the system closes the pipe): the server then closes as +//! local.rs INVARIANT 6 says. Nothing here sends it a signal or +//! kills it, ever. +//! 4. [`AppServer::stop`] waits for the exit at most as long as it is +//! told and then says the server is still closing: the window can +//! end while the server finishes its backup alone, and the next +//! start is refused, in words (1), until it has. +//! 5. A server that exits on its own is known as soon as it has +//! (`exited`), and every call that needs it says so, in words. +//! 6. A book is opened or closed in the server only by an admin +//! request, waiting for the server to be ready first; a close that +//! says its last backup was not whole is returned as a notice, never +//! as a plain success. +//! 7. Starting writes `run/app-hosted`, a file with nothing in it: the +//! root is this app's from then on, and the agents' bridge says +//! "Wanderbooks isn't running" for it, instead of starting a host +//! (bridge.rs INVARIANT 12). +//! ``` + +use crate::host::{SERVER_LOG, children_executable, open_log, private_options}; +use crate::opener::{host_lock_held, server_lock_held}; +use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; +use ledger_store::root::Root; +use std::io::BufRead; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +/// The file in `run/` that says the root is the desktop app's +/// (INVARIANT 7). +pub const APP_MARKER: &str = "app-hosted"; + +/// How long a server may take to say it is ready: it opens and verifies +/// every company it was told to, and a large one rebuilding a drifted +/// database takes a while. +pub const READY_WAIT: Duration = Duration::from_secs(300); + +/// How long [`AppServer::stop`] callers wait for a close, by default: the +/// last backup of a company is allowed 60 s (local.rs `BACKUP_AT_CLOSE`), +/// and running calls finish first. +pub const STOP_WAIT: Duration = Duration::from_secs(90); + +/// What a refused start says (INVARIANT 1). +pub const ANOTHER_HAS_THEM: &str = "Another program has these books open: another Wanderbooks window, `wanderbooks serve`, or a books server that is still finishing its last backup. Close it (`wanderbooks close` closes the books) or wait a moment, then start Wanderbooks again."; + +/// Where the server is in its life. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Phase { + /// Started, not yet ready. + Starting, + /// Ready: its sockets are bound and the companies tried. + Ready, + /// Gone, and how (in words). + Exited(String), +} + +struct Shared { + phase: Mutex, + changed: Condvar, +} + +impl Shared { + fn phase(&self) -> std::sync::MutexGuard<'_, Phase> { + self.phase.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn set(&self, to: Phase) { + let mut phase = self.phase(); + // Exited is final; Ready only follows Starting. + match (&*phase, &to) { + (Phase::Exited(_), _) | (Phase::Ready, Phase::Starting) => {} + _ => *phase = to, + } + self.changed.notify_all(); + } +} + +/// What [`AppServer::stop`] came to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stopped { + /// The server has exited: every company is closed and let go. + Closed, + /// The server was told to close and has not exited within the wait; + /// it goes on closing by itself (INVARIANT 4). + StillClosing, +} + +/// The books server, a child process of this one. +pub struct AppServer { + run: PathBuf, + /// The server's input: dropping it closes the books (INVARIANT 3). + stdin: Mutex>, + shared: Arc, + pid: u32, +} + +/// Whether the root whose `run/` folder this is belongs to the desktop +/// app (INVARIANT 7). +pub fn app_hosted(run: &Path) -> bool { + run.join(APP_MARKER).is_file() +} + +/// Whether a books server runs for the app now: the root is the app's, +/// no host holds it, and a server does. +pub fn the_apps_server_runs(run: &Path) -> bool { + app_hosted(run) && !host_lock_held(run) && server_lock_held(run) +} + +impl AppServer { + /// Start the server of the data root (`root`, else this account's), + /// from this program's own executable, with the companies `open` open + /// (INVARIANTS 1, 2). It returns at once; [`AppServer::wait_ready`] + /// waits for the ready line. + pub fn start(root: Option<&Path>, open: &[String]) -> Result { + Self::start_in(&children_executable(), root, open, |_| {}) + } + + /// [`AppServer::start`] from the program `exe`, `configure` having the + /// last word on its command (tests give it an environment of its own). + pub fn start_in( + exe: &Path, + root: Option<&Path>, + open: &[String], + configure: impl FnOnce(&mut Command), + ) -> Result { + let found = Root::find(root).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + if host_lock_held(&run) || server_lock_held(&run) { + return Err(ANOTHER_HAS_THEM.into()); + } + private_options() + .create(true) + .truncate(false) + .write(true) + .open(run.join(APP_MARKER)) + .map_err(|e| format!("can't mark these books as the app's: {}", e.kind()))?; + let log = open_log(&run.join(SERVER_LOG)) + .map_err(|e| format!("can't open the server's log: {}", e.kind()))?; + let mut command = Command::new(exe); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.arg0("wanderbooks"); + } + command.arg("server"); + if let Some(root) = root { + command.arg("--root").arg(root); + } + command.arg("--open").arg(open_argument(open)); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // CREATE_NO_WINDOW: a console of its own that nobody sees, so + // the window's own Ctrl+C never reaches it (it closes by its + // input alone). + command.creation_flags(0x0800_0000); + } + configure(&mut command); + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(log) + .spawn() + .map_err(|e| format!("can't start the books server: {e}"))?; + let stdin = child.stdin.take(); + let stdout = child.stdout.take(); + let pid = child.id(); + let shared = Arc::new(Shared { + phase: Mutex::new(Phase::Starting), + changed: Condvar::new(), + }); + if let Some(stdout) = stdout { + let shared = shared.clone(); + std::thread::Builder::new() + .name("app-server-ready".into()) + .spawn(move || { + // Read to the end, whatever it says: a pipe nobody + // reads could stop the server one day. + for line in std::io::BufReader::new(stdout).lines() { + match line { + Ok(line) if line == ledger_mcp::local::READY => { + shared.set(Phase::Ready); + } + Ok(_) => {} + Err(_) => break, + } + } + }) + .map_err(|e| format!("can't watch the books server: {e}"))?; + } + { + let shared = shared.clone(); + std::thread::Builder::new() + .name("app-server-exit".into()) + .spawn(move || { + let said = match child.wait() { + Ok(status) => format!("the books server stopped ({status})"), + Err(e) => format!("the books server stopped ({})", e.kind()), + }; + shared.set(Phase::Exited(said)); + }) + .map_err(|e| format!("can't watch the books server: {e}"))?; + } + Ok(Self { + run, + stdin: Mutex::new(stdin), + shared, + pid, + }) + } + + /// The server's process id (tests; never signalled by this program). + pub fn pid(&self) -> u32 { + self.pid + } + + /// The root's `run/` folder. + pub fn run_dir(&self) -> &Path { + &self.run + } + + /// Why the server is gone, if it is (INVARIANT 5). + pub fn exited(&self) -> Option { + match &*self.shared.phase() { + Phase::Exited(why) => Some(why.clone()), + _ => None, + } + } + + /// Wait at most `within` for the server to be ready: Ok when it is, + /// else why not, in words (it exited, or is still opening). + pub fn wait_ready(&self, within: Duration) -> Result<(), String> { + let deadline = Instant::now() + within; + let mut phase = self.shared.phase(); + loop { + match &*phase { + Phase::Ready => return Ok(()), + Phase::Exited(why) => { + return Err(format!( + "{why}: its log is {} in the books' run folder", + SERVER_LOG + )); + } + Phase::Starting => {} + } + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return Err(format!( + "the books server is still opening the companies after {} s", + within.as_secs() + )); + }; + phase = self + .shared + .changed + .wait_timeout(phase, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + } + + /// Open the company `id` in the server, so assistants can reach it + /// (INVARIANT 6): `Ok(None)` when it is open now, `Err` with why not. + /// It waits for the server to be ready, and for the open. + pub fn open_book(&self, id: &str) -> Result, String> { + self.wait_ready(READY_WAIT)?; + match self.ask(Request::OpenBook { id: id.into() })? { + Response::OpenBook { outcome, .. } => match outcome { + OpenOutcome::Opened | OpenOutcome::AlreadyOpen => Ok(None), + OpenOutcome::NoSuchBook => Err(format!( + "there are no books called {id:?}, so assistants can't reach them" + )), + OpenOutcome::CouldNotOpen(why) => Err(format!( + "{id} couldn't be opened for your assistants: {why}. You can still read it in this window." + )), + }, + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// Close the company `id` in the server (INVARIANT 6): running calls + /// on it finish, its assistants' sessions end, its last backup is made + /// and it is let go. `Ok(None)` when that is all so; `Ok(Some(words))` + /// when it is closed but its last backup wasn't whole; `Err` when the + /// request itself failed (the company may still be open). + pub fn close_book(&self, id: &str) -> Result, String> { + self.wait_ready(READY_WAIT)?; + match self.ask(Request::CloseBook { id: id.into() })? { + Response::CloseBook { outcome, .. } => match outcome { + CloseOutcome::Closed | CloseOutcome::WasNotOpen | CloseOutcome::NoSuchBook => { + Ok(None) + } + CloseOutcome::ClosedBackupIncomplete(why) => Ok(Some(format!( + "{id} is closed to your assistants, but its last backup wasn't whole: {why}. What it holds since the last good backup isn't backed up." + ))), + }, + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// One admin request, answered or why not in words. + fn ask(&self, request: Request) -> Result { + if let Some(why) = self.exited() { + return Err(why); + } + admin::call(&self.run.join(ledger_mcp::local::ADMIN_SOCKET), request) + .map_err(|e| e.to_string()) + } + + /// Close the server's input: it begins to close the books and exits + /// when it is done (INVARIANT 3). Does not wait. + pub fn close_input(&self) { + *self.stdin.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + + /// Close the server's input and wait at most `within` for it to exit + /// (INVARIANTS 3, 4). Never kills it. + pub fn stop(&self, within: Duration) -> Stopped { + self.close_input(); + let deadline = Instant::now() + within; + let mut phase = self.shared.phase(); + loop { + if matches!(&*phase, Phase::Exited(_)) { + return Stopped::Closed; + } + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return Stopped::StillClosing; + }; + phase = self + .shared + .changed + .wait_timeout(phase, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + } +} + +/// `--open`'s value for these companies. +fn open_argument(open: &[String]) -> String { + if open.is_empty() { + "none".into() + } else { + open.join(",") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_company_is_none_and_the_rest_are_a_list() { + assert_eq!(open_argument(&[]), "none"); + assert_eq!(open_argument(&["acme".into()]), "acme"); + assert_eq!(open_argument(&["acme".into(), "beta".into()]), "acme,beta"); + } + + #[test] + fn a_server_that_has_exited_stays_exited() { + let shared = Shared { + phase: Mutex::new(Phase::Starting), + changed: Condvar::new(), + }; + shared.set(Phase::Ready); + assert_eq!(*shared.phase(), Phase::Ready); + shared.set(Phase::Starting); + assert_eq!(*shared.phase(), Phase::Ready, "ready doesn't go back"); + shared.set(Phase::Exited("gone".into())); + shared.set(Phase::Ready); + assert_eq!(*shared.phase(), Phase::Exited("gone".into())); + } + + #[test] + fn a_root_is_the_apps_only_once_marked() { + let dir = tempfile::tempdir().unwrap(); + assert!(!app_hosted(dir.path())); + std::fs::write(dir.path().join(APP_MARKER), b"").unwrap(); + assert!(app_hosted(dir.path())); + // No server runs there: not the app's server. + assert!(!the_apps_server_runs(dir.path())); + } +} diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 09f08b4c..4bdfb238 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -6,7 +6,9 @@ //! no call the agent made can ever run twice. //! SOURCE: plan/served.md 3.9 ("The bridge and slow starts", "Closing", //! "Restarting"), 3.1 (the bridge never reads the books; it has -//! no data-dir flag); the plan's tests bridge_opens_closed_books, +//! no data-dir flag); plan/p15-app-and-relay.md 3.1 (the bridge +//! is a thin line to the running app and says in words when it +//! can't be), D-44, D-77, WB-app-3; the plan's tests bridge_opens_closed_books, //! bridge_survives_server_restart, bridge_initializes_during_cold_start, //! no_local_agent_tcp, close_now_ends_every_lease (in //! ledger-cli's open_while_held.rs, under names of their own); @@ -52,6 +54,19 @@ //! refusal, which says how the human makes one; but when the token //! file is there and couldn't be read, with that instead: the token //! is not said to be missing. The token is never written to the agent or to stderr. +//! 12. For a root the desktop app serves (app_server.rs INVARIANT 7) with +//! no host running, the bridge is a thin line to the app's server +//! and nothing more: it holds no lease and starts no host (a +//! detached host is not how the desktop runs). With the app not +//! running, every call is answered "Wanderbooks isn't running: +//! start Wanderbooks and open BOOK." (`not_running_words`); with +//! the app running but BOOK not open in it, "Company BOOK isn't +//! open: open it in Wanderbooks." (`not_open_words`, for the +//! server's `closed` refusal at the door). Neither is final: the +//! call after the app starts, or the company opens, goes through, +//! in a session that was already running. A root no app has served, +//! and any root a host holds, behave as in 1 to 11 (`wanderbooks +//! serve`, the headless host). //! ``` use crate::knobs::{FLAG, Knobs}; @@ -83,6 +98,17 @@ const NO_SESSION: &str = "Not Found: Session not found"; /// What a call cut off after it was sent is answered with (INVARIANT 4). const MAYBE_RAN: &str = "the connection to the books server broke while this call was running, so it may or may not have been done: check before trying it again (books.digest shows the latest changes)"; +/// What the agent is told when the app is not running (INVARIANT 12). +fn not_running_words(book: &str) -> String { + format!("Wanderbooks isn't running: start Wanderbooks and open {book}.") +} + +/// What the agent is told when the app runs but the company is not open +/// in it (INVARIANT 12). +fn not_open_words(book: &str) -> String { + format!("Company {book} isn't open: open it in Wanderbooks.") +} + /// What the agent is told once the owner closed the books (INVARIANT 6). const CLOSED_BY_OWNER: &str = "the owner closed the books (Close the books, or `wanderbooks close`): nothing more can be done in this session. Start a new agent session to open them again."; @@ -164,6 +190,9 @@ struct Bridge { pending: Mutex>, /// The server's channel, for its owner check (INVARIANT 9). endpoint: ledger_mcp::ipc::Endpoint, + /// Whether this is the line to the desktop app's server, with no host + /// and no lease (INVARIANT 12). + app: bool, } /// Who has the server's socket, when it isn't plainly this account. @@ -516,6 +545,7 @@ impl Bridge { if refused.as_deref() == Some(REFUSED_CLOSING.as_bytes()) { return Sent::NotRun(NotRun::Closing); } + let closed = refused.as_deref() == Some(b"closed".as_slice()); let refused = refused.is_some(); let is_stream = response .headers() @@ -524,11 +554,15 @@ impl Bridge { .is_some_and(|t| t.starts_with("text/event-stream")); let body = match response.text().await { Ok(b) => b, - Err(_) if refused => return Sent::Refused("the books server refused the call".into()), + Err(_) if refused => { + return Sent::Refused( + self.refusal_words(closed, "the books server refused the call"), + ); + } Err(_) => return Sent::MaybeRan, }; if refused { - return Sent::Refused(body.trim().chars().take(500).collect()); + return Sent::Refused(self.refusal_words(closed, &body)); } let answered = |messages: Vec| { // The server's "closing: not run" (INVARIANT 4). @@ -612,6 +646,10 @@ impl Bridge { .and_then(|v| v.to_str().ok()) .map(str::to_string); let status = response.status(); + let closed = response + .headers() + .get(ledger_mcp::local::REFUSED_HEADER) + .is_some_and(|v| v.as_bytes() == b"closed"); let is_stream = response .headers() .get("content-type") @@ -624,7 +662,7 @@ impl Bridge { // initialize the server won't take): the server's words. Not // asked again until the next call. 404 | 503 if !body.starts_with(CLOSING) => { - return Err(Some(body.trim().chars().take(500).collect())); + return Err(Some(self.refusal_words(closed, &body))); } 400..=499 => return Err(Some(body.trim().chars().take(500).collect())), _ => return Err(None), @@ -883,6 +921,9 @@ impl Bridge { // Not "opening now": closed by the owner, or can't open. Some(Link::Closed) => return self.answer(&id, error(&id, CLOSED_BY_OWNER)), Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)), + // The desktop app can't be reached, or the company isn't open + // in it: said now, not "opening" (INVARIANT 12). + Some(Link::Refused(why)) if self.app => return self.answer(&id, error(&id, why)), _ => None, }; let result = result.unwrap_or_else(|| { @@ -1010,6 +1051,78 @@ impl Bridge { } } + /// The words for a refusal at the server's door: for the desktop app's + /// `closed` refusal, the bridge's own (INVARIANT 12); else the + /// server's. + fn refusal_words(&self, closed: bool, body: &str) -> String { + if self.app && closed { + not_open_words(&self.book) + } else { + body.trim().chars().take(500).collect() + } + } + + /// The line to the desktop app's server (INVARIANT 12): no lease, no + /// host. Whenever a session is wanted it looks for the app's socket: + /// none answering is `Refused` with the words for it, which every + /// call is answered with and which the next call looks at again; the + /// company not open is the server's own refusal, in the bridge's + /// words. + async fn keep_in_app(self: Arc, run_dir: PathBuf) { + let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); + let account = crate::tokens::Account::new(&root, &self.book, &self.token_name); + let _ = self.token_file.set((account, run_dir)); + let mut epoch = 0u64; + loop { + if matches!(&*self.link.borrow(), Link::Opening) { + match self.socket_is_ours() { + Err(Owner::Other(why)) => { + self.link.send_replace(Link::Failed(why)); + return; + } + Err(Owner::Unreachable) => { + self.link + .send_replace(Link::Refused(not_running_words(&self.book))); + } + Ok(()) => match self.open_session(epoch + 1).await { + Ok(up) => { + epoch = up.epoch; + self.after_new_session(&up).await; + self.link.send_replace(Link::Ready(Arc::new(up))); + } + Err(Some(why)) => { + self.link.send_replace(Link::Refused(why)); + } + // Not answering yet (opening, or on its way out): + // look again soon, answering nothing meanwhile. + Err(None) => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + }, + } + } + // Until a session is wanted again: the agent initialized, or + // a session is found gone, or a call asks again. + self.renew.notified().await; + let stale = match &*self.link.borrow() { + Link::Ready(up) => { + up.init.is_none() + && self + .agent_init + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_some() + } + Link::Refused(_) => true, + _ => false, + }; + if stale { + self.link.send_replace(Link::Opening); + } + } + } + /// A session with the server: with the agent's initialize when it /// sent one, else none (a client without the handshake), within /// UPSTREAM_WAIT. @@ -1269,6 +1382,13 @@ async fn skip_line(input: &mut R) -> bool { } } +/// Whether the bridge is the line to the desktop app's server for the +/// root whose `run/` folder this is (INVARIANT 12): an app has served the +/// root, and no host holds it. +fn serves_the_app(run: &std::path::Path) -> bool { + crate::app_server::app_hosted(run) && !crate::opener::host_lock_held(run) +} + fn usage(prog: &str) { // (`--root DIR` too, for tests: the bridge never needs a folder.) eprintln!("usage: {prog} --book ID [--token NAME]"); @@ -1314,6 +1434,10 @@ pub fn run( .map_err(|e| e.to_string())? .to_string(); let opener = Opener::new(root.as_deref(), knobs, Kind::Bridge, Some(book.clone()))?; + // The desktop app's root with no host on it: the line to the app's + // server, no lease (INVARIANT 12). Settled once, here. + let app = serves_the_app(opener.run_dir()); + let run_dir = opener.run_dir().to_path_buf(); // Kept for the whole session: the client reaches the channel by it. let endpoint = ledger_mcp::ipc::Endpoint::new(opener.run_dir(), ledger_mcp::local::MCP_SOCKET) .map_err(|e| format!("can't reach the books server: {e}"))?; @@ -1346,8 +1470,13 @@ pub fn run( next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, + app, }); - let keeper = tokio::spawn(bridge.clone().keep(opener)); + let keeper = if app { + tokio::spawn(bridge.clone().keep_in_app(run_dir)) + } else { + tokio::spawn(bridge.clone().keep(opener)) + }; let writer = tokio::spawn(async move { let mut out = tokio::io::stdout(); while let Some(message) = outbox.recv().await { @@ -1662,6 +1791,20 @@ mod against_a_server { } fn bridge_at(socket: &Path, knobs: Knobs) -> (Arc, mpsc::UnboundedReceiver) { + bridge_for(socket, knobs, false) + } + + /// A bridge that is the line to the desktop app's server (INVARIANT + /// 12). + fn app_bridge_at(socket: &Path, knobs: Knobs) -> (Arc, mpsc::UnboundedReceiver) { + bridge_for(socket, knobs, true) + } + + fn bridge_for( + socket: &Path, + knobs: Knobs, + app: bool, + ) -> (Arc, mpsc::UnboundedReceiver) { let endpoint = ledger_mcp::ipc::Endpoint::new( socket.parent().unwrap(), socket.file_name().and_then(|n| n.to_str()).unwrap(), @@ -1691,6 +1834,7 @@ mod against_a_server { next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, + app, }); (bridge, rx) } @@ -2456,4 +2600,113 @@ mod against_a_server { let mut r = tokio::io::BufReader::new(&b""[..]); assert!(!skip_line(&mut r).await); } + + #[test] + fn the_two_messages_are_plain_and_name_the_company() { + assert_eq!( + not_running_words("acme"), + "Wanderbooks isn't running: start Wanderbooks and open acme." + ); + assert_eq!( + not_open_words("acme"), + "Company acme isn't open: open it in Wanderbooks." + ); + } + + #[test] + fn a_root_is_the_apps_only_when_marked_and_no_host_holds_it() { + let dir = tempfile::tempdir().unwrap(); + assert!(!serves_the_app(dir.path()), "no app has served it"); + std::fs::write(dir.path().join(crate::app_server::APP_MARKER), b"").unwrap(); + assert!(serves_the_app(dir.path())); + // A host holding the root is the headless path, marked or not. + let lock = std::fs::File::create(dir.path().join(crate::lease::HOST_LOCK)).unwrap(); + lock.lock().unwrap(); + assert!(!serves_the_app(dir.path())); + } + + const CLOSED_WORDS: &str = "The books \"acme\" aren't open: open them in Wanderbooks."; + + fn closed_reply() -> Reply { + Reply { + status: 503, + headers: vec![(ledger_mcp::local::REFUSED_HEADER, "closed".into())], + body: CLOSED_WORDS.into(), + cut: false, + } + } + + #[tokio::test] + async fn with_the_app_not_running_every_call_is_answered_in_words() { + let dir = tempfile::tempdir().unwrap(); + // Nothing listens here. + let (b, mut rx) = app_bridge_at(&dir.path().join("mcp.sock"), knobs(3000, 3000)); + let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf())); + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}}}); + b.waiting(&json!(1)); + b.clone().request(init).await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + let call: Value = serde_json::from_str(CALL).unwrap(); + b.waiting(&json!(7)); + b.clone() + .request_on(call.clone(), json!(7), "tools/call") + .await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + // Asked again, the same: the answer is not final, it is looked at + // afresh at each call (the app may have started since). + b.waiting(&json!(8)); + b.clone().request_on(call, json!(8), "tools/call").await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + keeper.abort(); + } + + #[tokio::test] + async fn with_the_app_running_a_company_that_is_not_open_is_said_in_words() { + let server = Server::start(); + let (b, mut rx) = app_bridge_at(&server.socket, knobs(3000, 3000)); + let dir = tempfile::tempdir().unwrap(); + let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf())); + let call: Value = serde_json::from_str(CALL).unwrap(); + // A call with no session first (a client without the handshake). + server.script([closed_reply()]); + b.waiting(&json!(7)); + b.clone().request_on(call, json!(7), "tools/call").await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_open_words("acme") + ); + // The agent's initialize: refused at the door, said as it is. + server.script([closed_reply(), closed_reply()]); + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}}}); + b.waiting(&json!(1)); + b.clone().request(init).await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_open_words("acme") + ); + keeper.abort(); + } + + #[tokio::test] + async fn a_host_bridge_passes_the_servers_words_on_as_they_are() { + let server = Server::start(); + let (b, _rx) = bridge_at(&server.socket, knobs(1000, 1000)); + let message: Value = serde_json::from_str(CALL).unwrap(); + server.script([closed_reply()]); + assert_eq!( + what(&b.send(&message, &up(1)).await), + format!("refused {CLOSED_WORDS}") + ); + } } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index e1b22d2e..f4ec92a9 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1129,12 +1129,20 @@ pub fn new_books(common: &Common, id: &str, currency: &str) -> Result Result { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; let run = found.run_dir().map_err(|e| e.to_string())?; + // The app's own server: no host to ask (it isn't "closed": it is open). + if crate::app_server::the_apps_server_runs(&run) { + return Err(APP_HAS_THEM.into()); + } match crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)? { None => Ok("The books are closed.".into()), Some(HostMsg::Done { detail }) => Ok(detail diff --git a/crates/ledger-host/src/host.rs b/crates/ledger-host/src/host.rs index a9f5be9f..16e29dcf 100644 --- a/crates/ledger-host/src/host.rs +++ b/crates/ledger-host/src/host.rs @@ -83,7 +83,7 @@ pub const EXIT_ANOTHER_HOST: i32 = 3; /// File options for what the host makes: mode 0600 on Unix; on Windows /// the file takes the owner-only DACL its folder carries (P11c). -fn private_options() -> std::fs::OpenOptions { +pub(crate) fn private_options() -> std::fs::OpenOptions { #[allow(unused_mut)] let mut options = std::fs::OpenOptions::new(); #[cfg(unix)] @@ -182,7 +182,7 @@ fn take_host_lock_within(run: &Path, wait: Duration) -> Result std::io::Result { +pub(crate) fn open_log(path: &Path) -> std::io::Result { open_log_within(path, LOG_LIMIT) } @@ -195,7 +195,7 @@ fn open_log_within(path: &Path, limit: u64) -> std::io::Result { } /// The executable the server is started from (INVARIANT 3). -fn children_executable() -> PathBuf { +pub(crate) fn children_executable() -> PathBuf { if cfg!(target_os = "linux") { PathBuf::from("/proc/self/exe") } else { diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 65a76939..e49ba2d4 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -11,6 +11,7 @@ //! viewer's Books menu does). Agents' tokens are kept in files under the data root //! ([`tokens`]). +pub mod app_server; pub mod bridge; pub mod channel; pub mod commands; diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index e0638566..4d2d5f62 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -28,6 +28,12 @@ //! 5. A holder that has held before, turned away because the owner //! closed the books, stays closed (HoldError::ClosedByOwner); a new //! holder waits for a new host. +//! 6. A root the desktop app has served (app_server.rs INVARIANT 7) +//! with the app's own server running and no host: a command's or +//! the viewer's hold is a lease on that server with no host behind +//! it (ready at once, never ended: the app decides when the books +//! close), no host is started beside it, and `wanderbooks serve` +//! is told the app has the books. //! ``` use crate::knobs::Knobs; @@ -109,6 +115,15 @@ pub struct Opener { pub struct Lease { /// Its number. pub id: u64, + /// The host's connection; none for the lease on the app's own server + /// (INVARIANT 6). + link: Option, + /// Whether `Ready` was said yet, for a lease with no host. + told_ready: bool, +} + +/// A lease's connection to the host. +struct HostLink { lines: tokio::io::Lines>>, _write: ledger_mcp::ipc::ConnectedWrite, } @@ -117,8 +132,17 @@ impl Lease { /// The host's next word: `Ready`, or `Ending` with why; `None` when /// the host is gone without a word. pub async fn next(&mut self) -> Option { + let Some(link) = self.link.as_mut() else { + // The app's own server: ready now, and no host to say more + // (INVARIANT 6). + if !self.told_ready { + self.told_ready = true; + return Some(HostMsg::Ready); + } + return std::future::pending().await; + }; loop { - match self.lines.next_line().await { + match link.lines.next_line().await { Ok(Some(line)) => match serde_json::from_str::(&line) { Ok(msg) => return Some(msg), Err(_) => continue, @@ -206,6 +230,22 @@ impl Opener { pub async fn hold(&mut self) -> Result { let mut started: Option = None; loop { + // The app has the books: its own server serves them, and no + // host is started beside it (INVARIANT 6). + if crate::app_server::the_apps_server_runs(&self.run) { + if self.kind == Kind::Serve { + return Err(HoldError::Failed( + "Wanderbooks (the app) has these books open: close it first, or use it" + .into(), + )); + } + self.has_held = true; + return Ok(Lease { + id: 0, + link: None, + told_ready: false, + }); + } wait_for_restart(&self.run).await; let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) .map_err(|e| format!("can't reach the books' host: {e}"))?; @@ -308,8 +348,11 @@ impl Opener { Ok(match first { HostMsg::Held { lease } => Asked::Held(Lease { id: lease, - lines, - _write: write, + link: Some(HostLink { + lines, + _write: write, + }), + told_ready: false, }), HostMsg::Ending { reason: Reason::ServerFailed, diff --git a/docs/spec/claims/app.md b/docs/spec/claims/app.md new file mode 100644 index 00000000..132f228a --- /dev/null +++ b/docs/spec/claims/app.md @@ -0,0 +1,85 @@ +# Claims: app + +Wanderbooks' own product rules for the desktop app as the host of the books +(plan P15, `plan/p15-app-and-relay.md`). No authority outside this product +states them: bookspec's rules are about the books, and these are about who +holds them open and how an assistant is told. They are `WB-app-`. + +Rules: none from bookspec's list; these are product rules only. + +--- + +### Product rules + +**WB-app-1 The app is the host: the books server is its child, and no one +else's.** Starting Wanderbooks starts the books server as a child process, +from the app's own executable; closing the window closes the server's +input, and the server closes as it always does (running calls finish, +nothing is killed, the last backup of each company is made). A window that +dies any way at all (a crash, a kill, a driver fault) closes the same +input, because the system closes the pipe, so no server is left behind and +no company is half closed. Starting is refused, in words, when another +program already has these books open: the host's lock (`run/host.lock`) or +the server's (`run/server.lock`) is held, the second including a server +still finishing a backup after its window went. The server is a process and +not a thread so that a fault in the window can never take a book down in +the middle of a write (D-84). +*Enforced:* `ledger_host::app_server::AppServer` (`start_in`, `stop`, its +`Drop`), `ANOTHER_HAS_THEM`; the server's own close, ledger-mcp +`local::run` (INVARIANT 6). +*Checked:* `ledger-cli` `app_server.rs` (`the_server_is_a_child_that_closes_when_its_input_does`, +`a_window_that_dies_leaves_no_server_and_no_half_closed_book`, +`a_start_is_refused_when_another_program_has_the_books`, +`a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`). + +**WB-app-2 A tab is a company open in the server.** A company has a tab +exactly while the server has it open to assistants: the companies the +window restores as tabs are opened when the server starts, opening a tab +asks the server to open that company, closing a tab asks it to close that +company. The window itself reads the journal on its own, read-only, and +never writes the books. A request that fails is shown to the person in +words and is never swallowed: a close that says its last backup was not +whole, a company that would not open for assistants, a server that stopped +or never started. A request for one company never waits for another's. +*Enforced:* `ledger_gui::serving::Serving` (`start`, `open`, `close`, +`take_notices`), `ledger_gui::app::App::open` and `App::close`, +`ledger_host::app_server::AppServer::open_book` and `close_book`. +*Checked:* `ledger-gui` `tests/serving.rs` (`a_tab_opening_asks_the_server_to_open_that_company`, +`a_tab_closing_asks_the_server_to_close_that_company`, +`the_companies_the_window_restores_are_the_servers_to_open`, +`a_close_that_was_not_whole_is_said_to_the_person`, +`a_refused_start_is_said_and_nothing_is_asked_of_the_server`); +`ledger-cli` `app_server.rs` (`opening_and_closing_a_company_drives_the_servers_book`). + +**WB-app-3 The bridge speaks to the running app and says so in words.** +`wanderbooks mcp --book X` connects to the root's `run/mcp.sock`. For a +root the app has served (it wrote `run/app-hosted`) with no host holding +it, the bridge holds no lease and starts no host. With the app not +running, every call is answered "Wanderbooks isn't running: start +Wanderbooks and open X."; with the app running but the company not open in +it, "Company X isn't open: open it in Wanderbooks." Neither answer is +final: the call after the app starts, or the company is opened, goes +through, in a session already running. A root no app has served, and any +root a host holds (`wanderbooks serve`, the headless host), behave as they +did: the bridge holds a lease and starts a host. +*Enforced:* `ledger_host::bridge` (`serves_the_app`, `keep_in_app`, +`not_running_words`, `not_open_words`), INVARIANT 12. +*Checked:* `ledger-host` bridge tests (`with_the_app_not_running_every_call_is_answered_in_words`, +`with_the_app_running_a_company_that_is_not_open_is_said_in_words`, +`a_host_bridge_passes_the_servers_words_on_as_they_are`); +`ledger-cli` `app_server.rs` (`the_bridge_says_the_app_isnt_running_then_works_once_it_is`, +`the_bridge_says_a_company_isnt_open_until_its_tab_is`). + +**WB-app-4 Closing the window is bounded and visible.** Asked to close, the +window stays up and says it is closing the books (finishing what is +running, making each company's last backup) until the server has exited, +or until 90 seconds have passed; then it closes anyway and says the server +is finishing by itself. It never kills the server. A close does not begin +while a job that changes the books is running (a restore, a format +upgrade: they hold the window already). A server that has exited on its own +is shown to the person at once, as a notice that assistants cannot reach +their companies. +*Enforced:* `ledger_gui::app::App` (`guard_server_close`), +`ledger_gui::serving::Serving::begin_stop`, `ledger_host::app_server::STOP_WAIT`. +*Checked:* `ledger-gui` `tests/serving.rs` (`closing_the_window_stops_the_server_and_waits_for_it`, +`a_server_that_will_not_exit_is_left_closing_and_the_window_closes`).