Merge branch 't3/wanderbooks-app-hosted-bridge': nothing on the desktop starts a detached host (P15 A5)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 12:32:59 -07:00
commit 610e41d1d1
34 files changed
+2967 -527

No files matched your search

+14
View File
@@ -535,12 +535,20 @@ impl App {
self.notices.extend(self.serving.take_notices());
let starting = self.serving.is_starting();
let down = self.serving.is_down();
// The refusal by a host is over once the start is on its way again
// (the host was closed): its words go, whether or not they were
// dismissed.
if !down {
self.notices.retain(|n| n != crate::serving::HOST_HOLDS);
}
if self.notices.is_empty() && !starting && !down {
return;
}
let p = pal(ui.ctx());
let mut dismiss = None;
let mut retry = false;
let mut close_host = false;
let host_blocks = self.serving.host_blocks();
egui::Panel::top("server_notices")
.resizable(false)
.frame(
@@ -563,6 +571,9 @@ impl App {
for (i, words) in self.notices.iter().enumerate() {
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(words).color(p.text));
if host_blocks && ui.button("Close it").clicked() {
close_host = true;
}
if down && ui.button("Try again").clicked() {
retry = true;
}
@@ -578,6 +589,9 @@ impl App {
if retry {
self.serving.retry();
}
if close_host {
self.serving.close_host();
}
if let Some(i) = dismiss {
self.notices.remove(i);
}
+19 -36
View File
@@ -1,14 +1,16 @@
//! The viewer's Books menu (plan P2 "Viewer menu", D-19, D-32): the
//! owner's own actions on the books, handed to the books server (back up
//! now, restore, new books, close the books, the format upgrade) or to the
//! now, restore, new books, the format upgrade) or to the
//! owner's agent (connect). The viewer itself still never writes the
//! books.
//!
//! ```text
//! GOAL: the owner backs up, restores, starts new books, closes the books
//! and connects an agent from the viewer, without a terminal.
//! GOAL: the owner backs up, restores, starts new books and connects an
//! agent from the viewer, without a terminal. (There is no "Close the
//! books": the app is the host, and a company's tab, or the window,
//! closes it: WB-app-2, WB-app-4.)
//! SOURCE: plan P2 ("Viewer menu (D-19)": "Back up now", "Restore…",
//! "New books…", "Close the books" and "Connect an assistant…"; the
//! "New books…" and "Connect an assistant…"; the
//! page it opens carries the two connect buttons; "Nothing in the viewer writes a book"); D-32
//! (no confinement: the viewer asks the server itself, as the
//! command line does); plan 3.9 and D-39 (the format upgrade: the
@@ -279,6 +281,19 @@ pub trait Owner: Send + Sync {
fn serve_start(&self, _open: &[String]) -> Result<(), String> {
Ok(())
}
/// Whether another program's host holds the books now (an earlier
/// build's, or `wanderbooks serve`'s): asked when the start was
/// refused, to offer the person a button that closes it
/// (`serve_close_host`) beside the line that says what to type.
fn serve_host_holds(&self) -> bool {
false
}
/// Ask that host to close the books and wait until it has (what
/// `wanderbooks close` does, for a person with no command line on
/// their path): `Ok` says what came of it, `Err` why not. Blocks.
fn serve_close_host(&self) -> Result<String, String> {
Err("not here".into())
}
/// Open the company `book` in the server (a tab opened): `Ok(None)`
/// when it is open now. Blocks.
fn serve_open(&self, _book: &str) -> Result<Option<String>, String> {
@@ -348,8 +363,6 @@ pub trait Owner: Send + Sync {
fn make_key(&self, _book: &str) -> Result<bool, String> {
Err("not here".into())
}
/// Close the books: everything holding them lets go.
fn close_books(&self) -> Result<String, String>;
/// New, empty books `id` in `currency`.
fn new_books(&self, id: &str, currency: &str) -> Result<String, String>;
/// Back the books `book` up now.
@@ -472,8 +485,6 @@ enum Dialog {
NewBooks { id: String, currency: String },
/// "Restore…": the backup, then its preview.
Restore(Box<RestoreForm>),
/// "Close the books": asked first.
Close,
/// The format upgrade: the go-ahead, with the owner passphrase.
Upgrade(Box<UpgradeForm>),
}
@@ -822,14 +833,6 @@ impl OwnerMenu {
Box::new(move || o.apply_update()),
));
}
ui.separator();
if ui
.button(format!("{} Close the books", icon::POWER))
.on_hover_text("Close the books now: assistants' sessions and every other holder let go")
.clicked()
{
self.dialog = Dialog::Close;
}
})
})
.inner;
@@ -916,26 +919,6 @@ impl OwnerMenu {
);
}
}
Dialog::Close => {
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-close")).show(ctx, |ui| {
ui.heading("Close the books?");
ui.label("Assistants' sessions and everything else holding them let go. They open again when something holds them.");
ui.horizontal(|ui| {
if ui.button("Close the books").clicked() {
let o = owner.clone();
run = Some((
"Close the books".into(),
Effect::Changes("Closing the books"),
Box::new(move || o.close_books().map(|l| vec![l])),
));
close = true;
}
if ui.button("Cancel").clicked() {
close = true;
}
});
});
}
Dialog::NewBooks { id, currency } => {
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-new-books"))
.show(ctx, |ui| {
+75 -1
View File
@@ -24,6 +24,11 @@
//! next tab opens or the person asks (`retry`); the owner has
//! stopped the server that failed, so no second one runs beside it.
//! A server still starting is waited for, in view (`is_starting`).
//! A start refused because a host holds the books (an earlier
//! build's, or `wanderbooks serve`'s) says what the button will do
//! and what to type instead, and offers the button (`host_blocks`,
//! `close_host`): it asks the host to close the books and starts
//! the server when it has; a close that fails says why.
//! 4. A company the window opened at the start is not opened again; a
//! company whose open failed, at the start (the server's list says
//! it isn't open: `serve_not_open`) or later, is a notice, and is
@@ -47,6 +52,11 @@ use std::collections::{BTreeSet, HashMap};
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
/// What the person is told when the start was refused because a host
/// holds the books, and what to do: the button closes it for them, and the
/// command is there for a person who prefers a terminal.
pub const HOST_HOLDS: &str = "Assistants can't reach your companies: another program has these books open (an earlier Wanderbooks, or `wanderbooks serve`). \"Close it\" makes it let go of them and starts the books here; or, in a terminal, `wanderbooks close` does the same.";
/// Where the server's start stands (INVARIANT 3).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Gate {
@@ -82,6 +92,12 @@ struct State {
report: Vec<String>,
/// The person has seen the report and chose to close anyway.
report_seen: bool,
/// The start was refused because a host holds the books (an earlier
/// build's, or `wanderbooks serve`'s): the notice has a button that
/// closes it (INVARIANT 3).
host_blocks: bool,
/// That button was pressed and the host is being asked to close.
host_closing: bool,
}
struct Inner {
@@ -207,7 +223,14 @@ impl Serving {
// A window asked to close meanwhile has no use for
// the word.
if *lock(&starting.closing) == Closing::Not {
starting.note(format!("Assistants can't reach your companies: {why}"));
let host = starting.owner.serve_host_holds();
lock(&starting.state).host_blocks = host;
if host {
starting.note(HOST_HOLDS.into());
} else {
starting
.note(format!("Assistants can't reach your companies: {why}"));
}
}
Gate::Down
}
@@ -276,6 +299,57 @@ impl Serving {
.is_some_and(|i| *lock(&i.gate) == Gate::Up && *lock(&i.closing) == Closing::Not)
}
/// Whether the start was refused because a host holds the books, so
/// the notice offers to close it (INVARIANT 3): not while that is
/// being done.
pub fn host_blocks(&self) -> bool {
self.inner.as_ref().is_some_and(|i| {
let state = lock(&i.state);
*lock(&i.gate) == Gate::Down && state.host_blocks && !state.host_closing
})
}
/// Ask the host that holds the books to close them, and start the
/// server when it has (INVARIANT 3): on a thread of its own, the
/// answer a notice. False when nothing was started.
pub fn close_host(&self) -> bool {
let Some(inner) = self.inner.clone() else {
return false;
};
if !self.host_blocks() {
return false;
}
lock(&inner.state).host_closing = true;
let asking = inner.clone();
let started = std::thread::Builder::new()
.name("serving-close-host".into())
.spawn(move || {
let said = asking.owner.serve_close_host();
{
let mut state = lock(&asking.state);
state.host_closing = false;
if said.is_ok() {
state.host_blocks = false;
// The old words are of a refusal that is over.
state.notices.retain(|n| n != HOST_HOLDS);
}
}
match said {
Ok(_) => {
Self::restart(&asking);
}
Err(why) => asking.note(format!(
"Couldn't close it: {why}. In a terminal, `wanderbooks close` closes it."
)),
}
})
.is_ok();
if !started {
lock(&inner.state).host_closing = false;
}
started
}
/// Whether the start failed and a `retry` would try again.
pub fn is_down(&self) -> bool {
self.inner
-3
View File
@@ -247,9 +247,6 @@ impl Owner for Fake {
self.note(format!("connect {} {book}", agent.key()));
Ok(vec![format!("{} reaches the books.", agent.label())])
}
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
-3
View File
@@ -28,9 +28,6 @@ struct Fake {
}
impl Owner for Fake {
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
@@ -80,9 +80,6 @@ struct Fake {
}
impl Owner for Fake {
fn close_books(&self) -> Result<String, String> {
Err("not in these tests".into())
}
fn new_books(&self, _id: &str, _currency: &str) -> Result<String, String> {
Err("not in these tests".into())
}
+235
View File
@@ -0,0 +1,235 @@
//! A start the app's server was refused because a host holds the books (an
//! earlier build's detached host, or `wanderbooks serve`'s): the notice
//! carries a button that closes it, and the line to type is its fallback
//! (serving.rs INVARIANT 3; WB-app-2).
//!
//! ```text
//! GOAL: a person with no command line on their path can let go of a
//! host that holds the books, from the notice, and the app then
//! starts its own server.
//! SOURCE: plan/p15-app-and-relay.md 3.1; WB-app-1 (a start is refused,
//! in words, when another program has the books), WB-app-2.
//! INVARIANTS:
//! 1. A start refused while a host holds the books is a notice that
//! says what will happen and what to type instead; the button is
//! offered (`host_blocks`).
//! 2. The button asks the host to close (`serve_close_host`) and, once
//! it has, starts the server and takes the notice away.
//! 3. A close that fails says why and offers the button again.
//! 4. A start refused for any other reason offers no such button.
//! ```
use ledger_core::Currency;
use ledger_gui::owner::{Agent, Owner, RestorePlan};
use ledger_gui::serving::{HOST_HOLDS, Serving};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
/// An owner whose start is refused while `host` holds the books.
struct Held {
host: AtomicBool,
/// Whether a host is what refused the start (else something else did).
host_is_why: bool,
close_says: Mutex<Result<String, String>>,
log: Mutex<Vec<String>>,
}
impl Held {
fn new(host_is_why: bool) -> Arc<Held> {
Arc::new(Held {
host: AtomicBool::new(true),
host_is_why,
close_says: Mutex::new(Ok("The other program let go of the books.".into())),
log: Mutex::new(Vec::new()),
})
}
fn said(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
}
}
impl Owner for Held {
fn serves(&self) -> bool {
true
}
fn serve_start(&self, _open: &[String]) -> Result<(), String> {
self.log.lock().unwrap().push("start".into());
if self.host.load(Ordering::SeqCst) {
Err("Another program has these books open: close it".into())
} else {
Ok(())
}
}
fn serve_host_holds(&self) -> bool {
self.host_is_why && self.host.load(Ordering::SeqCst)
}
fn serve_close_host(&self) -> Result<String, String> {
self.log.lock().unwrap().push("close host".into());
let said = self.close_says.lock().unwrap().clone();
if said.is_ok() {
self.host.store(false, Ordering::SeqCst);
}
said
}
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())
}
}
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));
}
}
fn started(owner: &Arc<Held>) -> Serving {
let _ = Currency::USD;
let serving = Serving::start(Some(owner.clone() as Arc<dyn Owner>), vec![]);
until("the first start came out", || !serving.is_starting());
serving
}
#[test]
fn a_start_refused_by_a_host_says_what_the_button_does_and_the_command_to_type() {
let owner = Held::new(true);
let serving = started(&owner);
assert!(serving.host_blocks());
let notices = serving.take_notices();
assert_eq!(notices, vec![HOST_HOLDS.to_string()]);
assert!(
HOST_HOLDS.contains("Close it") && HOST_HOLDS.contains("`wanderbooks close`"),
"{HOST_HOLDS}"
);
}
#[test]
fn the_button_closes_the_host_and_starts_the_server() {
let owner = Held::new(true);
let serving = started(&owner);
// Notices the window shows are kept by it: what it has not shown yet
// is read here, as it does.
let mut shown = serving.take_notices();
assert!(serving.close_host());
until("the server started after the host closed", || {
serving.is_up()
});
assert_eq!(owner.said(), ["start", "close host", "start"]);
assert!(!serving.host_blocks());
shown.extend(serving.take_notices());
// The refusal is over, and the notice of it goes (a window that
// already shows it drops it as it learns the start came out).
assert!(!serving.is_down());
}
#[test]
fn a_close_that_fails_says_why_and_the_button_stays() {
let owner = Held::new(true);
*owner.close_says.lock().unwrap() = Err("the other program is still closing".into());
let serving = started(&owner);
let _ = serving.take_notices();
assert!(serving.close_host());
until("the failure is said", || {
serving
.take_notices()
.iter()
.any(|n| n.contains("Couldn't close it: the other program is still closing"))
});
until("the button is back", || serving.host_blocks());
assert!(serving.is_down());
assert_eq!(owner.said(), ["start", "close host"]);
}
#[test]
fn a_start_refused_for_another_reason_offers_no_button() {
let owner = Held::new(false);
let serving = started(&owner);
assert!(!serving.host_blocks());
assert!(!serving.close_host());
let notices = serving.take_notices();
assert_eq!(notices.len(), 1, "{notices:?}");
assert!(notices[0].starts_with("Assistants can't reach your companies:"));
assert_eq!(owner.said(), ["start"]);
}
/// The window itself: the notice shows the button, pressing it asks the
/// host to close, and the notice goes once the server has started.
#[test]
fn the_notice_in_the_window_has_the_button_and_it_goes_when_the_server_starts() {
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use ledger_gui::{App, Start};
use ledger_store::root::{BookId, Root};
let dir = tempfile::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();
drop(
found
.create_book(&BookId::parse("alpha").unwrap(), Currency::USD)
.unwrap(),
);
let fallback = ledger_gui::data::Source {
data_dir: root.join("books").join("alpha"),
today: None,
};
let owner = Held::new(true);
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,
&|_| None,
Start::Restore { root, fallback },
Some(for_app),
)
});
until("the start was refused", || {
h.run_steps(2);
h.query_all_by_label_contains("`wanderbooks close`")
.next()
.is_some()
});
h.query_all_by_label("Close it")
.next()
.expect("the button")
.click();
until("the host was asked to close and the server started", || {
h.run_steps(2);
{
// (A tab opening after the refused start tried it again once.)
let said = owner.said();
said.iter().filter(|s| *s == "close host").count() == 1
&& said.last().is_some_and(|s| s == "start")
}
});
until("the notice goes", || {
h.run_steps(2);
h.query_all_by_label_contains("`wanderbooks close`")
.next()
.is_none()
&& h.query_all_by_label("Close it").next().is_none()
});
}
+4 -19
View File
@@ -33,10 +33,6 @@ impl Fake {
}
impl Owner for Fake {
fn close_books(&self) -> Result<String, String> {
self.said("close".into());
Ok("The books are closing.".into())
}
fn new_books(&self, id: &str, currency: &str) -> Result<String, String> {
self.said(format!("new {id} {currency}"));
Ok(format!("Made new books \"{id}\" ({currency})."))
@@ -247,19 +243,11 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() {
"restore /media/disk/acme.git acme 7"
);
// Close the books: asked first; cancelled, nothing; then done.
// There is no "Close the books": a company's tab, or the window, closes
// the books (WB-app-2, WB-app-4).
open_menu(&mut h);
h.get_by_label_contains("Close the books").click();
h.run_steps(3);
h.get_by_label("Cancel").click();
h.run_steps(3);
assert_eq!(f.asked.lock().unwrap().len(), start + 4);
open_menu(&mut h);
h.get_by_label_contains("Close the books").click();
h.run_steps(3);
h.get_by_label("Close the books").click();
settle(&mut h, &f, start + 5);
assert_eq!(f.asked.lock().unwrap()[start + 4], "close");
assert!(h.query_by_label_contains("Close the books").is_none());
h.run_steps(2);
// The viewer wrote nothing of the books.
drop(h);
@@ -409,7 +397,4 @@ fn screenshots() {
settle(&mut h, &f, n + 1);
shot(&mut h, "restore-plan");
h.get_by_label("Cancel").click();
open_menu(&mut h);
h.get_by_label_contains("Close the books").click();
shot(&mut h, "close");
}
-6
View File
@@ -173,9 +173,6 @@ impl Owner for Fake {
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())
}
@@ -461,9 +458,6 @@ fn a_window_with_no_server_asks_nothing_of_any() {
// 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())
}
-3
View File
@@ -36,9 +36,6 @@ use std::sync::{Arc, OnceLock};
struct Quiet;
impl Owner for Quiet {
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
-7
View File
@@ -578,9 +578,6 @@ struct Agentic {
}
impl Owner for Agentic {
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
@@ -2095,10 +2092,6 @@ impl Gated {
}
impl Owner for Gated {
fn close_books(&self) -> Result<String, String> {
self.block();
Ok("The books are closing.".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
-3
View File
@@ -33,9 +33,6 @@ impl Fake {
}
impl Owner for Fake {
fn close_books(&self) -> Result<String, String> {
Err("not in these tests".into())
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not in these tests".into())
}
-3
View File
@@ -35,9 +35,6 @@ impl Fake {
}
impl Owner for Fake {
fn close_books(&self) -> Result<String, String> {
Err("not here".into())
}
fn new_books(&self, id: &str, currency: &str) -> Result<String, String> {
self.said(format!("new {id} {currency}"));
let (_, root) = self.root_path();