test(app): the child's lifetime, tabs driving the server, and the bridge's two messages

The server child starts, closes on input close and on the window's death (a
killed stand-in window leaves no server and a whole book), a stop that runs out
of time leaves it closing and says so, a start is refused while a server or host
holds the books; a tab opened or closed opens or closes that company, in order,
with failures said in words; closing the window waits in view and asks the owner
once; the bridge answers 'Wanderbooks isn't running' and 'Company X isn't open'
in one running session, starting no host. Claims for WB-app-1 to WB-app-4 name
them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 09:07:34 -07:00
1 parent f476c95a64
commit 7357a30c73
4 files changed
+984 -21

No files matched your search

+426
View File
@@ -0,0 +1,426 @@
//! The app as the host (ledger-host app_server.rs and bridge.rs INVARIANT
//! 12; plan/p15-app-and-relay.md 3.1; WB-app-1, WB-app-3): the books
//! server is a child process of the window, and the bridge talks to the
//! running app and says so in words when it cannot.
//!
//! ```text
//! GOAL: the child starts, answers, opens and closes one company at a
//! time on request, closes cleanly when its input does (the
//! window's close, or the window's death), is never killed, and a
//! start is refused while another program holds the books; and an
//! agent's bridge is told, in words, that the app isn't running or
//! that the company isn't open, then goes through once it is.
//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server as a
//! child and closes it by closing its input; the bridge answers
//! "Wanderbooks isn't running" or "Company X isn't open"), D-44,
//! D-77, D-84, WB-app-1, WB-app-3.
//! INVARIANTS:
//! 1. A server started by `AppServer` is `wanderbooks server` of this
//! program on the test's own root alone, says ready, and holds
//! run/server.lock until it exits.
//! 2. Closing its input (`stop`) closes the books as the host does:
//! exit 0, the lock let go, the socket removed.
//! 3. A window that is killed outright leaves no server: its input
//! closes with it and the books close cleanly.
//! 4. A start is refused, in words, while a server or a host holds the
//! books, and touches nothing.
//! 5. A stop that runs out of time says the server is still closing and
//! leaves it alone: nothing is signalled.
//! 6. A tab's company is opened and closed in the server by request; a
//! company closed is not reachable, one opened is.
//! 7. The bridge, for a root the app has served and with no host:
//! "Wanderbooks isn't running" with the app not running, "Company X
//! isn't open" with it running and the company not, and neither once
//! both are so, in a session that was already running; it starts no
//! host.
//! ```
mod common;
use common::{BOOK, Home, Server, clean_env};
use ledger_host::app_server::{ANOTHER_HAS_THEM, APP_MARKER, AppServer, Stopped, app_hosted};
use ledger_host::opener::{host_lock_held, server_lock_held};
use ledger_mcp::admin::{Request, Response};
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
fn exe() -> &'static Path {
Path::new(env!("CARGO_BIN_EXE_wanderbooks"))
}
/// The server the app starts, on `home`'s root alone, with `open` open.
fn start(home: &Home, open: &[String]) -> AppServer {
let dir = home.dir.path().to_path_buf();
AppServer::start_in(exe(), Some(&home.root()), open, move |c: &mut Command| {
clean_env(c, &dir);
c.env("XDG_CONFIG_HOME", dir.join(".config"));
})
.unwrap_or_else(|why| panic!("{why}"))
}
/// Wait until `ok`, at most a minute.
fn until(what: &str, mut ok: impl FnMut() -> bool) {
let end = Instant::now() + Duration::from_secs(60);
while !ok() {
assert!(Instant::now() < end, "never: {what}");
std::thread::sleep(Duration::from_millis(20));
}
}
/// Whether the books `id` are open, by the server's own list.
fn open_in_server(home: &Home, id: &str) -> bool {
match home.admin(Request::List) {
Response::Books(books) => books.iter().any(|b| b.id == id && b.open),
other => panic!("{other:?}"),
}
}
#[test]
fn the_server_is_a_child_that_closes_when_its_input_does() {
let home = Home::new("app-child");
let run = home.run();
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
assert!(app_hosted(&run), "the root is the app's from now on");
assert!(server_lock_held(&run), "it holds the server lock");
assert!(!host_lock_held(&run), "no host was started beside it");
assert!(
matches!(home.admin(Request::List), Response::Books(_)),
"it answers on its admin socket"
);
assert_eq!(server.exited(), None);
// Closed by closing its input, as the host does.
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
assert!(
server
.exited()
.is_some_and(|how| how.contains("exit status: 0") || how.contains("exit code: 0")),
"it exited cleanly: {:?}",
server.exited()
);
until("the lock is let go", || !server_lock_held(&run));
#[cfg(unix)]
assert!(
!run.join("admin.sock").exists() && !run.join("mcp.sock").exists(),
"its sockets are removed"
);
}
#[test]
fn opening_and_closing_a_company_drives_the_servers_book() {
let home = Home::new("app-tabs");
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
home.create(BOOK, "USD");
assert!(open_in_server(&home, BOOK));
// A tab closed: the book is closed in the server.
assert_eq!(server.close_book(BOOK), Ok(None));
assert!(!open_in_server(&home, BOOK));
// Closed again, or one that isn't there: nothing to say.
assert_eq!(server.close_book(BOOK), Ok(None));
// A tab opened: the book is open again.
assert_eq!(server.open_book(BOOK), Ok(None));
assert!(open_in_server(&home, BOOK));
assert_eq!(server.open_book(BOOK), Ok(None), "already open: fine");
// A company that isn't in the root is said in words.
let refused = server.open_book("nope").unwrap_err();
assert!(refused.contains("no books called"), "{refused}");
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
// After it, a request says so rather than hanging.
assert!(server.open_book(BOOK).is_err());
}
#[test]
fn a_start_is_refused_when_another_program_has_the_books() {
let home = Home::new("app-refused");
let run = home.run();
let dir = home.dir.path().to_path_buf();
let try_start = || {
let dir = dir.clone();
AppServer::start_in(exe(), Some(&home.root()), &[], move |c: &mut Command| {
clean_env(c, &dir);
})
};
// A books server holds them (another window, or one still finishing).
let other = Server::start_with(&home, &["--open", "none"]);
let refused = try_start().err().expect("refused");
assert_eq!(refused, ANOTHER_HAS_THEM);
assert!(!run.join(APP_MARKER).exists(), "a refusal touches nothing");
other.close();
until("the other let go", || !server_lock_held(&run));
// A host holds them.
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(run.join("host.lock"))
.unwrap();
lock.lock().unwrap();
assert_eq!(try_start().err().expect("refused"), ANOTHER_HAS_THEM);
assert!(!run.join(APP_MARKER).exists());
drop(lock);
// Held by nobody: it starts.
let server = try_start().expect("started");
server.wait_ready(Duration::from_secs(60)).unwrap();
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// What the helper process below says, one line each.
const CHILD_PID: &str = "wb-app-child-pid ";
const READY: &str = "wb-app-ready";
/// Not a test of its own: the "window" the next test kills. It starts the
/// books server as the app does and then waits to be killed; run by any
/// other means it does nothing.
#[test]
fn a_window_that_is_about_to_die() {
let Some(home) = std::env::var_os("WB_APP_DYING_HOME") else {
return;
};
let home = std::path::PathBuf::from(home);
let root = ledger_store::root::default_root(&home);
let dir = home.clone();
let server = AppServer::start_in(exe(), Some(&root), &[], move |c: &mut Command| {
clean_env(c, &dir);
c.env("XDG_CONFIG_HOME", dir.join(".config"));
})
.expect("started");
server.wait_ready(Duration::from_secs(60)).unwrap();
println!("{CHILD_PID}{}", server.pid());
println!("{READY}");
let _ = std::io::stdout().flush();
std::thread::sleep(Duration::from_secs(600));
}
#[test]
fn a_window_that_dies_leaves_no_server_and_no_half_closed_book() {
let home = Home::new("app-dies");
let run = home.run();
let mut window = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "a_window_that_is_about_to_die", "--nocapture"])
.env("WB_APP_DYING_HOME", home.dir.path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
// Whatever happens, the stand-in window does not outlive this test.
struct Reap(Child);
impl Drop for Reap {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let mut lines = BufReader::new(window.stdout.take().unwrap()).lines();
let mut server_pid = None;
loop {
let line = lines.next().expect("the window said ready").unwrap();
if let Some(pid) = line.strip_prefix(CHILD_PID) {
server_pid = pid.trim().parse::<u32>().ok();
}
if line == READY {
break;
}
}
let mut window = Reap(window);
assert!(server_lock_held(&run), "the server is running");
home.create(BOOK, "USD");
// The window is killed outright: no chance to close anything.
window.0.kill().unwrap();
window.0.wait().unwrap();
until("the server let go of the books", || !server_lock_held(&run));
#[cfg(unix)]
{
let pid = server_pid.expect("the window gave the server's pid") as i32;
until("the server's process is gone", || {
// SAFETY: signal 0 only asks whether the process exists; the
// pid is the server this test's own helper started.
unsafe { libc::kill(pid, 0) != 0 }
});
assert!(
!run.join("admin.sock").exists(),
"the books closed as at any close: the socket is removed"
);
}
let _ = server_pid;
// The books are whole: a new server opens them without a word.
let again = start(&home, &[BOOK.to_string()]);
again.wait_ready(Duration::from_secs(60)).unwrap();
assert!(open_in_server(&home, BOOK));
assert_eq!(again.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// A "server" that takes five seconds to close once its input ends.
#[cfg(unix)]
fn slow_closer(dir: &Path) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join("slow-server");
std::fs::write(
&path,
"#!/bin/sh\necho ready\ncat >/dev/null\nsleep 5\nexit 0\n",
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
#[cfg(unix)]
#[test]
fn a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so() {
let home = Home::new("app-slow");
let slow = slow_closer(home.dir.path());
let server = AppServer::start_in(&slow, Some(&home.root()), &[], |_| {}).unwrap();
server.wait_ready(Duration::from_secs(60)).unwrap();
let pid = server.pid() as i32;
let started = Instant::now();
assert_eq!(
server.stop(Duration::from_millis(300)),
Stopped::StillClosing
);
assert!(
started.elapsed() < Duration::from_secs(4),
"the window is not held for the server's whole close"
);
// Left alone: still running, nothing signalled.
assert_eq!(server.exited(), None);
// SAFETY: signal 0 only asks whether the process exists; it is the
// child this test started.
assert_eq!(unsafe { libc::kill(pid, 0) }, 0, "it was not killed");
// It finishes by itself.
assert_eq!(server.stop(Duration::from_secs(30)), Stopped::Closed);
}
/// An agent's bridge, spoken to as a client over stdio.
struct Bridge {
child: Child,
stdin: std::process::ChildStdin,
lines: mpsc::Receiver<Value>,
next: u64,
}
impl Bridge {
fn start(home: &Home) -> Self {
let mut c = Command::new(exe());
c.args(["mcp", "--book", BOOK, "--root"]).arg(home.root());
clean_env(&mut c, home.dir.path());
let mut child = c
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
let stdout = child.stdout.take().unwrap();
let (tx, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if let Ok(v) = serde_json::from_str::<Value>(&line) {
let _ = tx.send(v);
}
}
});
Self {
child,
stdin,
lines,
next: 1,
}
}
/// Send a request and return the answer to it.
fn ask(&mut self, method: &str, params: Value) -> Value {
let id = self.next;
self.next += 1;
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
writeln!(self.stdin, "{line}").unwrap();
self.stdin.flush().unwrap();
let end = Instant::now() + Duration::from_secs(60);
loop {
let left = end.saturating_duration_since(Instant::now());
let said = self
.lines
.recv_timeout(left)
.unwrap_or_else(|_| panic!("no answer to {method}"));
if said["id"] == json!(id) {
return said;
}
}
}
fn initialize(&mut self) -> Value {
self.ask(
"initialize",
json!({"protocolVersion": common::PROTOCOL, "capabilities": {},
"clientInfo": {"name": "test", "version": "0"}}),
)
}
fn start_call(&mut self) -> Value {
self.ask(
"tools/call",
json!({"name": "books.start", "arguments": {}}),
)
}
}
impl Drop for Bridge {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn error_of(answer: &Value) -> String {
answer["error"]["message"]
.as_str()
.unwrap_or_else(|| panic!("an error was expected: {answer}"))
.to_string()
}
#[test]
fn the_bridge_says_the_app_isnt_running_then_works_once_it_is() {
let home = Home::new("app-bridge");
let run = home.run();
// The app has served this root (it wrote its mark), and isn't running.
std::fs::write(run.join(APP_MARKER), b"").unwrap();
let mut bridge = Bridge::start(&home);
let not_running = format!("Wanderbooks isn't running: start Wanderbooks and open {BOOK}.");
assert_eq!(error_of(&bridge.initialize()), not_running);
assert_eq!(error_of(&bridge.start_call()), not_running);
// No host was started for it.
assert!(!host_lock_held(&run));
assert!(!run.join("lease.sock").exists());
// The app starts, with the company closed.
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
home.create(BOOK, "USD");
let token = home.token_with(BOOK, "agent", &["read", "write", "post", "admin"]);
ledger_host::tokens::keeper(&run)
.set(
&ledger_host::tokens::Account::new(&home.root(), BOOK, "agent"),
&token,
)
.unwrap();
assert_eq!(server.close_book(BOOK), Ok(None));
let not_open = format!("Company {BOOK} isn't open: open it in Wanderbooks.");
assert_eq!(error_of(&bridge.start_call()), not_open);
// Its tab opens: the same session goes through.
assert_eq!(server.open_book(BOOK), Ok(None));
let answered = bridge.start_call();
assert!(
answered.get("error").is_none() && answered.get("result").is_some(),
"{answered}"
);
assert!(!host_lock_held(&run), "still no host");
// The company's tab closes under the running session: said again.
assert_eq!(server.close_book(BOOK), Ok(None));
assert_eq!(error_of(&bridge.start_call()), not_open);
// The window closes: said again, in the same session.
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
assert_eq!(error_of(&bridge.start_call()), not_running);
}
+492
View File
@@ -0,0 +1,492 @@
//! The window and the books server it runs (serving.rs, app.rs;
//! plan/p15-app-and-relay.md 3.1; WB-app-2, WB-app-4): a tab is a company
//! open in the server, and closing the window closes the server in view.
//!
//! ```text
//! GOAL: the server is started with the companies the window restored;
//! a tab opened or closed opens or closes that company in it; what
//! fails is said in words; closing the window closes the server and
//! says so while it waits, and the wait is the owner's bounded one.
//! SOURCE: plan/p15-app-and-relay.md 3.1 (a tab is a company open in the
//! server; the app closes it by closing its input; the close
//! dialog shows the wait), D-77, D-78, WB-app-2, WB-app-4.
//! INVARIANTS:
//! 1. The server starts once, with the restored companies, and none of
//! them is asked to open again.
//! 2. A tab opened is `serve_open`, a tab closed is `serve_close`, for
//! that company, in the order the tabs were opened and closed.
//! 3. A start that failed is a notice, and nothing is asked of the
//! server after it.
//! 4. A close that wasn't whole, a company that wouldn't open, and a
//! server that exited on its own are notices, in words.
//! 5. Asked to close, the window stays up saying it is closing the books
//! until the owner's close has returned; the owner is asked to close
//! once, however many times it is asked.
//! 6. A window with no owner that hosts a server asks nothing of any.
//! ```
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use ledger_core::Currency;
use ledger_gui::data::Source;
use ledger_gui::owner::{Agent, Owner, RestorePlan};
use ledger_gui::serving::Serving;
use ledger_gui::{App, Start};
use ledger_store::root::{BookId, Root};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// A data root of its own, with companies made in it.
struct World {
_dir: tempfile::TempDir,
root: PathBuf,
}
impl World {
fn new(ids: &[&str]) -> World {
let dir = tempfile::Builder::new()
.prefix("wb-gui-serving-")
.tempdir()
.unwrap();
let home = dir.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let root = dir.path().join("root");
Root::setup(&home, Some(&root), None).unwrap();
let found = Root::find(Some(&root)).unwrap();
for id in ids {
drop(
found
.create_book(&BookId::parse(id).unwrap(), Currency::USD)
.unwrap(),
);
}
World { _dir: dir, root }
}
fn source(&self, id: &str) -> Source {
Source {
data_dir: self.root.join("books").join(id),
today: None,
}
}
/// The kept preferences that restore these companies as tabs.
fn kept(&self, open: &[&str]) -> HashMap<String, String> {
HashMap::from([(ledger_gui::app::open_key(&self.root), open.join(","))])
}
fn start(&self, open: &[&str], owner: &Arc<Fake>) -> App {
let kept = self.kept(open);
let owner: Arc<dyn Owner> = owner.clone();
App::start_with_owner(
&egui::Context::default(),
&|k| kept.get(k).cloned(),
Start::Restore {
root: self.root.clone(),
fallback: self.source(open.first().copied().unwrap_or("alpha")),
},
Some(owner),
)
}
}
/// An owner that hosts a server of its own, recording what it is asked.
#[derive(Default)]
struct Fake {
/// What was asked, in order: "start alpha,beta", "open gamma", "close
/// beta", "stop".
log: Mutex<Vec<String>>,
/// What starting says, if not well.
start_says: Mutex<Option<String>>,
/// What closing each company says, if not plainly well.
close_says: Mutex<HashMap<String, Result<Option<String>, String>>>,
/// What opening each company says, if not well.
open_says: Mutex<HashMap<String, String>>,
/// How long the close of the server takes, and what it says after.
stop_takes: Mutex<Duration>,
stop_says: Mutex<Option<String>>,
/// Why the server is gone, once it is.
exited: Mutex<Option<String>>,
}
impl Fake {
fn new() -> Arc<Fake> {
Arc::new(Fake::default())
}
fn said(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
}
fn note(&self, what: String) {
self.log.lock().unwrap().push(what);
}
}
impl Owner for Fake {
fn serves(&self) -> bool {
true
}
fn serve_start(&self, open: &[String]) -> Result<(), String> {
self.note(format!("start {}", open.join(",")));
match self.start_says.lock().unwrap().clone() {
Some(why) => Err(why),
None => Ok(()),
}
}
fn serve_open(&self, book: &str) -> Result<Option<String>, String> {
self.note(format!("open {book}"));
match self.open_says.lock().unwrap().remove(book) {
Some(why) => Err(why),
None => Ok(None),
}
}
fn serve_close(&self, book: &str) -> Result<Option<String>, String> {
self.note(format!("close {book}"));
self.close_says
.lock()
.unwrap()
.remove(book)
.unwrap_or(Ok(None))
}
fn serve_stop(&self) -> Result<Option<String>, String> {
self.note("stop".into());
std::thread::sleep(*self.stop_takes.lock().unwrap());
Ok(self.stop_says.lock().unwrap().clone())
}
fn serve_exited(&self) -> Option<String> {
self.exited.lock().unwrap().clone()
}
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
Err("not here".into())
}
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn connect(&self, _: Agent, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn upgrade_format(&self, _: &str, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
}
/// Wait until `ok` holds (the requests run on threads of their own).
fn until(what: &str, mut ok: impl FnMut() -> bool) {
let end = Instant::now() + Duration::from_secs(30);
while !ok() {
assert!(Instant::now() < end, "never: {what}");
std::thread::sleep(Duration::from_millis(10));
}
}
/// How long to wait for something that must NOT happen.
fn a_while() {
std::thread::sleep(Duration::from_millis(300));
}
fn tab_of(app: &App, id: &str) -> usize {
app.views()
.iter()
.position(|v| v.book_id().as_deref() == Some(id))
.unwrap_or_else(|| panic!("no tab for {id}"))
}
#[test]
fn the_companies_the_window_restores_are_the_servers_to_open() {
let w = World::new(&["alpha", "beta", "gamma"]);
let owner = Fake::new();
let app = w.start(&["alpha", "beta"], &owner);
until("the server started", || !owner.said().is_empty());
a_while();
// Started once, with exactly the restored companies open; neither is
// asked to open again.
assert_eq!(owner.said(), vec!["start alpha,beta".to_string()]);
assert_eq!(app.views().len(), 2);
drop(app);
}
#[test]
fn a_tab_opening_asks_the_server_to_open_that_company() {
let w = World::new(&["alpha", "gamma"]);
let owner = Fake::new();
let ctx = egui::Context::default();
let mut app = w.start(&["alpha"], &owner);
app.open(&ctx, w.source("gamma"));
until("gamma asked", || {
owner.said().contains(&"open gamma".to_string())
});
assert_eq!(owner.said()[0], "start alpha");
assert!(app.serving().wants("gamma"));
// A company already open shows its tab and asks nothing more.
app.open(&ctx, w.source("gamma"));
a_while();
assert_eq!(
owner.said().iter().filter(|s| *s == "open gamma").count(),
1
);
drop(app);
}
#[test]
fn a_tab_closing_asks_the_server_to_close_that_company() {
let w = World::new(&["alpha", "beta"]);
let owner = Fake::new();
let ctx = egui::Context::default();
let mut app = w.start(&["alpha", "beta"], &owner);
let beta = tab_of(&app, "beta");
app.close(beta);
until("beta closed", || {
owner.said().contains(&"close beta".to_string())
});
assert!(!app.serving().wants("beta"));
assert!(app.serving().wants("alpha"), "the other stays open");
// Closed and opened again: a close, then an open, in that order.
app.open(&ctx, w.source("beta"));
until("beta opened again", || {
owner.said().contains(&"open beta".to_string())
});
let said = owner.said();
let close = said.iter().position(|s| s == "close beta").unwrap();
let open = said.iter().position(|s| s == "open beta").unwrap();
assert!(close < open, "{said:?}");
assert!(
!said.contains(&"close alpha".to_string()),
"closing one tab closes no other: {said:?}"
);
drop(app);
}
#[test]
fn a_close_that_was_not_whole_is_said_to_the_person() {
let w = World::new(&["alpha", "beta"]);
let owner = Fake::new();
owner.close_says.lock().unwrap().insert(
"beta".into(),
Ok(Some(
"beta is closed to your assistants, but its last backup wasn't whole: the backup folder is gone."
.into(),
)),
);
owner.close_says.lock().unwrap().insert(
"alpha".into(),
Err("the books server isn't answering".into()),
);
let mut app = w.start(&["alpha", "beta"], &owner);
let (beta, alpha) = (tab_of(&app, "beta"), tab_of(&app, "alpha"));
app.close(beta);
until("a notice about beta", || {
app.notices().iter().any(|n| n.contains("wasn't whole"))
});
// A refused close is said too, naming the company.
let alpha = if alpha > beta { alpha - 1 } else { alpha };
app.close(alpha);
until("a notice about alpha", || {
app.notices()
.iter()
.any(|n| n.contains("alpha could not be closed") && n.contains("isn't answering"))
});
// A company that would not open for assistants is said too, and asked
// for again the next time its tab opens.
owner.open_says.lock().unwrap().insert(
"beta".into(),
"beta couldn't be opened for your assistants: x".into(),
);
let ctx = egui::Context::default();
app.open(&ctx, w.source("beta"));
until("a notice about the open", || {
app.notices()
.iter()
.any(|n| n.contains("couldn't be opened"))
});
until("beta no longer wanted", || !app.serving().wants("beta"));
drop(app);
}
#[test]
fn a_refused_start_is_said_and_nothing_is_asked_of_the_server() {
let w = World::new(&["alpha", "gamma"]);
let owner = Fake::new();
*owner.start_says.lock().unwrap() = Some("Another program has these books open".into());
let ctx = egui::Context::default();
let mut app = w.start(&["alpha"], &owner);
until("the refusal is said", || {
app.notices()
.iter()
.any(|n| n.contains("Another program has these books open"))
});
app.open(&ctx, w.source("gamma"));
app.close(tab_of(&app, "alpha"));
a_while();
assert_eq!(owner.said(), vec!["start alpha".to_string()]);
drop(app);
}
#[test]
fn a_server_that_exits_on_its_own_is_said_once() {
let w = World::new(&["alpha"]);
let owner = Fake::new();
let mut app = w.start(&["alpha"], &owner);
until("started", || !owner.said().is_empty());
assert!(app.notices().is_empty());
*owner.exited.lock().unwrap() = Some("the books server stopped (exit status: 1)".into());
let said: Vec<String> = app.notices().to_vec();
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].contains("exit status: 1") && said[0].contains("can't reach your companies"),
"{said:?}"
);
assert_eq!(app.notices().len(), 1, "said once, not every frame");
drop(app);
}
#[test]
fn closing_the_window_stops_the_server_and_waits_for_it() {
let w = World::new(&["alpha"]);
let owner = Fake::new();
*owner.stop_takes.lock().unwrap() = Duration::from_millis(600);
let kept = w.kept(&["alpha"]);
let (root, fallback) = (w.root.clone(), w.source("alpha"));
let for_app: Arc<dyn Owner> = owner.clone();
let mut h = Harness::builder()
.with_size(egui::vec2(1000.0, 700.0))
.build_eframe(move |cc| {
App::start_with_owner(
&cc.egui_ctx,
&|k| kept.get(k).cloned(),
Start::Restore { root, fallback },
Some(for_app),
)
});
h.run_steps(3);
// The window is asked to close.
h.input_mut()
.viewports
.entry(egui::ViewportId::ROOT)
.or_default()
.events
.push(egui::ViewportEvent::Close);
h.run_steps(2);
until("the close began", || h.state().serving().is_closing());
h.run_steps(2);
assert!(
h.query_by_label_contains("Closing your books").is_some(),
"the window says it is closing the books while it waits"
);
assert!(!h.state().serving().is_closed(), "the wait is not over");
// Asked again meanwhile: the owner is still asked once.
h.input_mut()
.viewports
.entry(egui::ViewportId::ROOT)
.or_default()
.events
.push(egui::ViewportEvent::Close);
h.run_steps(2);
until("the close is done", || h.state().serving().is_closed());
h.run_steps(3);
assert!(
h.query_by_label_contains("Closing your books").is_none(),
"the message goes when the wait does"
);
assert_eq!(
owner.said().iter().filter(|s| *s == "stop").count(),
1,
"{:?}",
owner.said()
);
drop(h);
assert_eq!(
owner.said().iter().filter(|s| *s == "stop").count(),
1,
"dropping the window asks no second time: {:?}",
owner.said()
);
}
#[test]
fn a_server_that_will_not_exit_is_left_closing_and_the_window_closes() {
let w = World::new(&["alpha"]);
let owner = Fake::new();
*owner.stop_says.lock().unwrap() = Some("The books are still closing in the background".into());
let serving = Serving::start(Some(owner.clone() as Arc<dyn Owner>), vec!["alpha".into()]);
until("started", || !owner.said().is_empty());
serving.begin_stop();
until("the close returned", || serving.is_closed());
// The wait ended with the owner's word; the window can close, and the
// person is told what is left.
let notices = serving.take_notices();
assert!(
notices.iter().any(|n| n.contains("still closing")),
"{notices:?}"
);
drop(serving);
drop(w);
}
#[test]
fn a_window_with_no_server_asks_nothing_of_any() {
let w = World::new(&["alpha", "gamma"]);
let ctx = egui::Context::default();
// An owner that does not host a server: the default.
struct Plain;
impl Owner for Plain {
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
Err("not here".into())
}
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn connect(&self, _: Agent, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn upgrade_format(&self, _: &str, _: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
}
let kept = w.kept(&["alpha"]);
let mut app = App::start_with_owner(
&ctx,
&|k| kept.get(k).cloned(),
Start::Restore {
root: w.root.clone(),
fallback: w.source("alpha"),
},
Some(Arc::new(Plain)),
);
assert!(!app.serving().is_on());
app.open(&ctx, w.source("gamma"));
app.close(0);
assert!(app.notices().is_empty());
assert!(app.serving().is_closed(), "nothing to close");
// And no owner at all.
let app = App::start_with_owner(
&ctx,
&|k| kept.get(k).cloned(),
Start::Restore {
root: w.root.clone(),
fallback: w.source("alpha"),
},
None,
);
assert!(!app.serving().is_on());
}
+57 -17
View File
@@ -295,15 +295,7 @@ impl AppServer {
pub fn open_book(&self, id: &str) -> Result<Option<String>, 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::OpenBook { outcome, .. } => open_words(id, outcome),
Response::Refused(why) => Err(why),
other => Err(format!("the books server answered oddly: {other:?}")),
}
@@ -317,14 +309,7 @@ impl AppServer {
pub fn close_book(&self, id: &str) -> Result<Option<String>, 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::CloseBook { outcome, .. } => Ok(close_words(id, outcome)),
Response::Refused(why) => Err(why),
other => Err(format!("the books server answered oddly: {other:?}")),
}
@@ -368,6 +353,31 @@ impl AppServer {
}
}
/// What opening the company `id` came to, for the person: `Ok(None)` when
/// it is open, else why not (INVARIANT 6).
fn open_words(id: &str, outcome: OpenOutcome) -> Result<Option<String>, String> {
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."
)),
}
}
/// What closing the company `id` came to: a notice when its last backup
/// wasn't whole, never a plain success then (INVARIANT 6).
fn close_words(id: &str, outcome: CloseOutcome) -> Option<String> {
match outcome {
CloseOutcome::Closed | CloseOutcome::WasNotOpen | CloseOutcome::NoSuchBook => None,
CloseOutcome::ClosedBackupIncomplete(why) => 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."
)),
}
}
/// `--open`'s value for these companies.
fn open_argument(open: &[String]) -> String {
if open.is_empty() {
@@ -388,6 +398,36 @@ mod tests {
assert_eq!(open_argument(&["acme".into(), "beta".into()]), "acme,beta");
}
#[test]
fn a_close_with_an_incomplete_backup_is_a_notice_never_a_plain_success() {
assert_eq!(close_words("acme", CloseOutcome::Closed), None);
assert_eq!(close_words("acme", CloseOutcome::WasNotOpen), None);
let said = close_words(
"acme",
CloseOutcome::ClosedBackupIncomplete("the backup folder is gone".into()),
)
.expect("a notice");
assert!(
said.contains("acme")
&& said.contains("last backup wasn't whole")
&& said.contains("the backup folder is gone"),
"{said}"
);
}
#[test]
fn an_open_that_did_not_happen_says_why() {
assert_eq!(open_words("acme", OpenOutcome::Opened), Ok(None));
assert_eq!(open_words("acme", OpenOutcome::AlreadyOpen), Ok(None));
let refused = open_words("acme", OpenOutcome::CouldNotOpen("a damaged line".into()))
.expect_err("not opened");
assert!(
refused.contains("acme") && refused.contains("a damaged line"),
"{refused}"
);
assert!(open_words("acme", OpenOutcome::NoSuchBook).is_err());
}
#[test]
fn a_server_that_has_exited_stays_exited() {
let shared = Shared {
+9 -4
View File
@@ -49,7 +49,9 @@ or never started. A request for one company never waits for another's.
`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`).
`ledger-cli` `app_server.rs` (`opening_and_closing_a_company_drives_the_servers_book`);
`ledger-host` `app_server.rs` tests (`a_close_with_an_incomplete_backup_is_a_notice_never_a_plain_success`,
`an_open_that_did_not_happen_says_why`).
**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
@@ -67,8 +69,9 @@ did: the bridge holds a lease and starts a host.
*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`).
`ledger-cli` `app_server.rs` (`the_bridge_says_the_app_isnt_running_then_works_once_it_is`: not
running, then running with the company closed, then open, then closed
again, then the window closed, in one session, with no host started).
**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
@@ -82,4 +85,6 @@ 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`).
`a_server_that_will_not_exit_is_left_closing_and_the_window_closes`,
`a_server_that_exits_on_its_own_is_said_once`); `ledger-cli` `app_server.rs`
(`a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`).