From 13a3f1b51953ad95b7232ffb7b5197e37a408975 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 13:40:00 -0700 Subject: [PATCH] feat(gui): the web half of the Connect page and the first run (P15 B3) The Connect page gets "On the web": a switch "Allow web assistants" per company, off by default; three lines of progress in plain words (getting an address, getting a certificate, connected) with a spinner on the one under way; once it works, the address for the company with Copy; the three steps for Claude on the web that the plan stands behind (Settings, Connectors, Add custom connector, paste, sign in and match the code); and, for ChatGPT and any other assistant, "we haven't tested this yet" rather than steps nobody tried. What goes wrong is in words and says whether the window and the assistants on this computer are affected. A new address is asked for twice. The first time a company is open and the server says no assistant was ever connected, the Connect page opens by itself, once, remembered per installation. The owner trait gains web_state, web_turn_on, web_turn_off and web_new_address; an owner that does not offer them shows no switch. The tabs tests start with the first run already done, since they are about tabs. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/Cargo.toml | 1 + crates/ledger-gui/src/app.rs | 53 +++ crates/ledger-gui/src/company.rs | 5 + crates/ledger-gui/src/connect.rs | 332 +++++++++++++- crates/ledger-gui/src/owner.rs | 57 +++ crates/ledger-gui/tests/tabs.rs | 13 +- crates/ledger-gui/tests/web_connect.rs | 577 +++++++++++++++++++++++++ 7 files changed, 1026 insertions(+), 12 deletions(-) create mode 100644 crates/ledger-gui/tests/web_connect.rs diff --git a/crates/ledger-gui/Cargo.toml b/crates/ledger-gui/Cargo.toml index 3040b7a9..1b95eec0 100644 --- a/crates/ledger-gui/Cargo.toml +++ b/crates/ledger-gui/Cargo.toml @@ -50,6 +50,7 @@ chrono = "0.4" egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] } proptest = "1" tempfile = "3" +ledger-link = { path = "../ledger-link" } zip = "9.0.1" [lints] diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 2c92c98f..211c5fb5 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -188,6 +188,10 @@ pub struct App { assistants_ok: bool, /// "Now" for "10 seconds ago", fixed (tests, screenshots) or not. fixed_now: Option>, + /// The Connect page has been opened by itself once, or an assistant has + /// been connected: kept per installation, and never again after that + /// (WB-app-6). + first_connect_done: bool, } /// The warning about assistants that is up (INVARIANT 10). @@ -206,6 +210,9 @@ enum Warn { /// for a moment does not make an assistant that was connected seem gone. const WARN_AGE: std::time::Duration = std::time::Duration::from_secs(60); +/// The kept preference that says the Connect page has opened by itself. +const FIRST_CONNECT_KEY: &str = "first_connect_done"; + /// What a window is called when no company is in front. const TITLE: &str = "wanderbooks"; @@ -334,9 +341,50 @@ impl App { let schemes = SchemeMenu::restored(get, ctx.global_style().visuals.dark_mode); let mut app = Self::bare(ctx, schemes); app.dock_prefs = (get("dock_open"), get("dock_agent")); + app.first_connect_done = get(FIRST_CONNECT_KEY).is_some(); app } + /// The first time a company is open and no assistant has ever been + /// connected, the Connect page opens by itself, once (WB-app-6): a + /// person who installs, starts the app and makes or opens their first + /// company sees the way to connect an assistant without looking for it. + /// "Never connected" is the server's own answer for the whole + /// installation: no key, no session, no web approval. It is asked after + /// the answer is known (never from a guess), it is remembered per + /// installation, and it is not asked again once an assistant exists. + fn first_connect(&mut self, statuses: &[Status]) { + if self.first_connect_done { + return; + } + let Some(roster) = self.connections.roster() else { + return; // not known yet: not a guess + }; + let any = !roster.tokens.is_empty() + || !roster.assistants.is_empty() + || !roster.web_approvals.is_empty() + || !roster.web_pending.is_empty(); + if any { + self.first_connect_done = true; + return; + } + let ready = statuses + .get(self.active) + .is_some_and(|s| s.serves && !s.down && s.link != Link::Unknown); + if !ready { + return; + } + if let Some(v) = self.views.get_mut(self.active) { + v.open_connect(); + self.first_connect_done = true; + } + } + + /// Whether the Connect page has opened by itself already (tests). + pub fn first_connect_done(&self) -> bool { + self.first_connect_done + } + /// The first-run page, if it is up (tests). pub fn welcome(&self) -> Option<&crate::welcome::Welcome> { self.welcome.as_ref() @@ -381,6 +429,7 @@ impl App { warn: Warn::Off, assistants_ok: false, fixed_now: None, + first_connect_done: false, } } @@ -1233,6 +1282,7 @@ impl eframe::App for App { for (v, s) in self.views.iter_mut().zip(&statuses) { v.set_assist(s.clone()); } + self.first_connect(&statuses); let tabs: Vec = self .views .iter() @@ -1280,6 +1330,9 @@ impl eframe::App for App { fn save(&mut self, storage: &mut dyn eframe::Storage) { self.schemes.keep(&mut |k, v| storage.set_string(k, v)); + if self.first_connect_done { + storage.set_string(FIRST_CONNECT_KEY, "1".to_string()); + } // The dock, as the front tab has it, else as it was kept. match self.active_view() { Some(v) => v.dock_ref().keep(&mut |k, v| storage.set_string(k, v)), diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 0757b15d..e81df1c5 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -228,6 +228,11 @@ impl CompanyView { self.assist = status; } + /// Open the Connect page (the first run does, once: app.rs). + pub fn open_connect(&mut self) { + self.nav.go(Route::Connect); + } + /// What this view was last given of its assistants (tests). pub fn assist(&self) -> &crate::connections::Status { &self.assist diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 00adcbdd..750d687f 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -14,7 +14,8 @@ //! sentence; Connect is a page per company: on this computer, a row //! per tool, and the connections with Revoke); D-77 (bookkeeping is //! through an assistant, the window reads); WB-assist-1, -//! WB-assist-3, WB-assist-4. +//! WB-assist-3, WB-assist-4, WB-assist-6 (the web half), WB-app-6 +//! (the first run). //! INVARIANTS: //! 1. One place per fact: a tab carries the state as a shape (the same //! three shapes everywhere: plugs apart, plugs together, a turning @@ -43,8 +44,9 @@ //! 6. Nothing here blocks the frame: every request of the server runs //! off the UI thread; what is shown while it is not known is "not //! known", never a guess. -//! 7. The web half of the page (the switch, the address, the steps for -//! Claude and ChatGPT) is unit B3's. Unit B1's part of it is here: a +//! 7. The web half of the page (the switch, the progress, the address and +//! the steps) is WB-assist-6's (`State::web_switch`, `web_progress`, +//! `claude_steps`). Unit B1's part of it is here: a //! web assistant that asks to connect is shown to the person, in //! words, as a card that says who is asking, where it is sent back //! to, the address it asked from and what it will be able to do, with @@ -418,6 +420,10 @@ pub struct State { /// The waiting web assistants the person has ticked "let it post /// entries too" for. post_asked: std::collections::BTreeSet, + /// "Get a new address" was clicked once: the second click does it. + new_address_asked: bool, + /// The address was just copied (the time, for the word "Copied"). + copied_at: Option, } /// The two lines an assistant set up by hand needs. @@ -458,16 +464,27 @@ impl State { &mut self, ui: &mut Ui, status: &Status, + book: &str, owner: &Option>, jobs: &crate::jobs::Spawner, ) { - if status.web_pending.is_empty() && status.web_approvals.is_empty() { + let web = owner.as_ref().and_then(|o| o.web_state(book)); + if web.is_none() && status.web_pending.is_empty() && status.web_approvals.is_empty() { return; } let p = pal(ui.ctx()); ui.add_space(24.0); - section(ui, "Assistants on the web"); + section(ui, "On the web"); let mut want: Want = None; + if let Some(web) = &web { + if let Some(w) = self.web_switch(ui, status, book, web, owner) { + want = Some(w); + } + ui.add_space(10.0); + } + if !(status.web_pending.is_empty() && status.web_approvals.is_empty()) { + section(ui, "Assistants on the web"); + } let (shown, more) = newest_waiting(&status.web_pending); for request in shown { if let Some(w) = self.pending_card(ui, status, request, owner) { @@ -819,7 +836,7 @@ impl State { ), }; } - self.web_section(ui, status, &owner, jobs); + self.web_section(ui, status, book, &owner, jobs); ui.add_space(24.0); self.connections(ui, status, book, &owner, jobs); }); @@ -1220,3 +1237,306 @@ fn connection_row( ); } } + +// ---- the web half of the page (plan P15 unit B3) ------------------------------ + +/// The exact steps for Claude on the web, for the address `connector`. +/// Only what the plan can stand behind (plan/served.md 3 and the Connect +/// card there: Settings, Connectors, Add custom connector, paste the +/// address, sign in); the sign-in is this window's (D-83, D-90). +pub fn claude_steps() -> [&'static str; 3] { + [ + "In Claude on the web, open Settings, then Connectors.", + "Choose \u{201c}Add custom connector\u{201d} and paste the address above.", + "Claude opens a sign-in page that shows a code. Come back to this window, check that the code is the same, and choose Allow.", + ] +} + +/// What the page says for ChatGPT: no steps are given, because none were +/// tried (plan 7: "ChatGPT Plus and write tools: OpenAI's two pages +/// disagree"). +pub const CHATGPT_NOTE: &str = "We haven't tested this yet, so there are no steps to give. If you add the address above to ChatGPT as a connector, the sign-in comes to this window the same way."; + +/// What the page says for any other assistant. +pub const OTHER_NOTE: &str = "Other assistants (Gemini, Grok, muse.ai and the like): we haven't tested these yet. The same address may work; the sign-in comes to this window the same way."; + +/// Words for the steps of turning web assistants on: what is done, what is +/// being done, what waits. `current` is the one in progress (none once it +/// is connected). +pub fn web_progress(step: crate::owner::WebStep) -> [(&'static str, Progress); 3] { + use crate::owner::WebStep as S; + let first = match step { + S::Off | S::GettingAddress | S::Connecting => Progress::Now, + _ => Progress::Done, + }; + let second = match step { + S::GettingCertificate => Progress::Now, + S::Connected => Progress::Done, + _ => Progress::Waiting, + }; + let third = match step { + S::Connected => Progress::Done, + _ => Progress::Waiting, + }; + [ + ("Getting an address", first), + ("Getting a certificate", second), + ("Connected", third), + ] +} + +/// Where one of the steps stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Progress { + /// Done. + Done, + /// Being done now. + Now, + /// Not started. + Waiting, +} + +/// A switch: a pill that is on or off, with its label, as one control. +/// The label is its accessible name, so it is found as "Allow web +/// assistants". +fn switch(ui: &mut Ui, on: bool, enabled: bool, label: &str) -> egui::Response { + let p = pal(ui.ctx()); + let size = vec2(40.0, 22.0); + let (rect, resp) = ui.allocate_exact_size( + size, + if enabled { + Sense::click() + } else { + Sense::hover() + }, + ); + if ui.is_rect_visible(rect) { + let t = ui.ctx().animate_bool(resp.id, on); + let fill = if on { p.accent } else { p.border }; + ui.painter().rect_filled( + rect, + CornerRadius::same(11), + fill.gamma_multiply(if enabled { 1.0 } else { 0.5 }), + ); + let r = rect.height() / 2.0 - 3.0; + let x = egui::lerp((rect.left() + r + 3.0)..=(rect.right() - r - 3.0), t); + ui.painter() + .circle_filled(egui::pos2(x, rect.center().y), r, p.surface); + } + let name = label.to_string(); + resp.widget_info(move || { + egui::WidgetInfo::selected(egui::WidgetType::Checkbox, enabled, on, name.clone()) + }); + resp +} + +impl State { + /// The switch, the progress, the address with Copy and the steps + /// (plan 3.3). What the person asks for, if anything. + fn web_switch( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + web: &crate::owner::WebConnect, + owner: &Option>, + ) -> Want { + let p = pal(ui.ctx()); + let mut want: Want = None; + let can = owner.is_some() && self.job.is_none(); + ui.horizontal(|ui| { + let resp = switch(ui, web.on, can, "Allow web assistants"); + ui.label(RichText::new("Allow web assistants").font(theme::semibold(14.0))); + if resp.clicked() + && let Some(o) = owner.clone() + { + let b = book.to_string(); + self.new_address_asked = false; + want = Some(if web.on { + ( + "Turning web assistants off".to_string(), + "Turning web assistants off".to_string(), + Box::new(move || o.web_turn_off(&b)) as Box Outcome + Send>, + ) + } else { + ( + "Turning web assistants on".to_string(), + "Turning web assistants on".to_string(), + Box::new(move || o.web_turn_on(&b)) as Box Outcome + Send>, + ) + }); + } + }); + ui.label( + RichText::new(format!( + "Claude and ChatGPT on the web can only reach {} if you give them an address on the internet. Turn this on to get one. Wanderbooks keeps it private to you, and nobody can read what passes through. An assistant on the web still has to be allowed here, by you, each time it connects.", + status.company + )) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if !web.on { + ui.add_space(4.0); + ui.label( + RichText::new(if web.kept { + "Off. Nothing on this computer can be reached from the internet. Turning it on again gives the same address as before." + } else { + "Off. Nothing on this computer can be reached from the internet." + }) + .font(theme::regular(13.0)) + .color(p.muted), + ); + return want; + } + ui.add_space(8.0); + // Progress, in words. + for (words, progress) in web_progress(web.step) { + ui.horizontal(|ui| match progress { + Progress::Done => { + ui.label(RichText::new(icon::CHECK_CIRCLE).color(p.accent)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now if web.problem.is_some() => { + ui.label(RichText::new(icon::WARNING).color(p.warning)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now => { + ui.spinner(); + ui.label(RichText::new(format!("{words}\u{2026}")).font(theme::regular(13.5))); + } + Progress::Waiting => { + ui.label(RichText::new(icon::CIRCLE).color(p.muted)); + ui.label( + RichText::new(words) + .font(theme::regular(13.5)) + .color(p.muted), + ); + } + }); + } + if web.step != crate::owner::WebStep::Connected || web.problem.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } + if let Some(problem) = &web.problem { + ui.add_space(4.0); + ui.label( + RichText::new(problem) + .font(theme::regular(13.0)) + .color(p.warning), + ); + if !web.needs_person { + ui.label( + RichText::new( + "Your assistants on this computer, and this window, are not affected.", + ) + .font(theme::regular(12.5)) + .color(p.muted), + ); + } + } + // The address is shown once it works (or while the page says why it + // does not): not before, so nobody pastes one that cannot answer yet. + if let Some(connector) = web + .connector + .as_ref() + .filter(|_| web.step == crate::owner::WebStep::Connected || web.problem.is_some()) + { + ui.add_space(10.0); + ui.label(RichText::new("The address to give an assistant").font(theme::semibold(13.5))); + ui.horizontal(|ui| { + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(6)) + .inner_margin(Margin::symmetric(8, 5)) + .show(ui, |ui| { + ui.add( + egui::Label::new( + RichText::new(connector).font(egui::FontId::monospace(12.5)), + ) + .selectable(true), + ); + }); + let copy = ui.button(format!("{} Copy", icon::COPY)); + if copy.clicked() { + ui.ctx().copy_text(connector.clone()); + self.copied_at = Some(ui.input(|i| i.time)); + } + copy.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Copy the address") + }); + if let Some(at) = self.copied_at { + if ui.input(|i| i.time) - at < 3.0 { + ui.label( + RichText::new("Copied") + .font(theme::regular(12.5)) + .color(p.muted), + ); + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } else { + self.copied_at = None; + } + } + }); + ui.label( + RichText::new("Keep this address to yourself: anyone who has it can ask to connect (you would still be asked first).") + .font(theme::regular(12.5)) + .color(p.muted), + ); + ui.add_space(10.0); + ui.label(RichText::new("Claude on the web").font(theme::semibold(13.5))); + for (i, step) in claude_steps().iter().enumerate() { + ui.label(RichText::new(format!("{}. {step}", i + 1)).font(theme::regular(13.0))); + } + ui.add_space(8.0); + ui.label(RichText::new("ChatGPT").font(theme::semibold(13.5))); + ui.label( + RichText::new(CHATGPT_NOTE) + .font(theme::regular(13.0)) + .color(p.muted), + ); + ui.add_space(8.0); + ui.label(RichText::new("Another assistant").font(theme::semibold(13.5))); + ui.label( + RichText::new(OTHER_NOTE) + .font(theme::regular(13.0)) + .color(p.muted), + ); + } + // A new address, behind a confirmation. + ui.add_space(12.0); + if self.new_address_asked { + ui.label( + RichText::new("The old address stops working at once. Every assistant connected through it has to be connected again with the new one.") + .font(theme::regular(13.0)) + .color(p.warning), + ); + ui.horizontal(|ui| { + if ui + .add_enabled(can, egui::Button::new("Get a new address")) + .clicked() + && let Some(o) = owner.clone() + { + let b = book.to_string(); + self.new_address_asked = false; + want = Some(( + "Getting a new address".to_string(), + "Getting a new address".to_string(), + Box::new(move || o.web_new_address(&b)), + )); + } + if ui.button("Keep the old one").clicked() { + self.new_address_asked = false; + } + }); + } else if ui + .add_enabled(can, egui::Button::new("Get a new address\u{2026}")) + .clicked() + { + self.new_address_asked = true; + } + want + } +} diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index ccac21cd..a10aaa4f 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -253,6 +253,44 @@ pub struct WebApproval { pub last_used: Option, } +/// How far web assistants have got for a company (plan P15 B3): the steps +/// the page tells in words. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebStep { + /// Off. + Off, + /// Getting an address. + GettingAddress, + /// Making the line to the relay. + Connecting, + /// The line is up; the certificate is being got. + GettingCertificate, + /// A web assistant can reach the company now. + Connected, +} + +/// What the Connect page shows of one company's web assistants. Read from +/// memory by the owner, every frame, never a wait. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WebConnect { + /// The switch. + pub on: bool, + /// How far it has got. + pub step: WebStep, + /// The address for the whole installation, while on. + pub address: Option, + /// The address an assistant is given for this company. + pub connector: Option, + /// A line of progress, in words. + pub words: String, + /// What is wrong, in words. + pub problem: Option, + /// The problem needs the person (it will not mend itself). + pub needs_person: bool, + /// An address is kept for when web assistants are turned on again. + pub kept: bool, +} + /// Who is connected and who may connect, across the open companies. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Roster { @@ -349,6 +387,25 @@ pub trait Owner: Send + Sync { fn web_set_post(&self, _approval: &str, _post: bool) -> Result { Err("not here".into()) } + /// The company's web assistants as they stand: `None` when this window + /// has no way to offer them (the switch is not drawn). Reads memory; + /// never waits. + fn web_state(&self, _book: &str) -> Option { + None + } + /// Turn web assistants on for the company: `Ok` says what happens next + /// in words. Blocks (a request or two of the server). + fn web_turn_on(&self, _book: &str) -> Result { + Err("not here".into()) + } + /// Turn them off for the company. Blocks. + fn web_turn_off(&self, _book: &str) -> Result { + Err("not here".into()) + } + /// A new address for web assistants: the old one stops working. Blocks. + fn web_new_address(&self, _book: &str) -> Result { + Err("not here".into()) + } /// This program run with `words`, as a line to type in a terminal (the /// program's own path, the words, the data root if one was named): what /// the Connect page shows for an assistant it has no button for. diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index 515176a8..d2e6f193 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -225,12 +225,13 @@ impl eframe::Storage for Prefs { } fn prefs(pairs: &[(&str, &str)]) -> Prefs { - Prefs( - pairs - .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect(), - ) + // The Connect page opens by itself once, in a window whose server says + // no assistant was ever connected (WB-app-6); these tests are about + // tabs, so that has happened already. + let mut kept: std::collections::BTreeMap = + [("first_connect_done".to_string(), "1".to_string())].into(); + kept.extend(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string()))); + Prefs(kept.into_iter().collect()) } /// The app as it starts from `kept`, over `world`'s data root, its first diff --git a/crates/ledger-gui/tests/web_connect.rs b/crates/ledger-gui/tests/web_connect.rs new file mode 100644 index 00000000..fe9c66a0 --- /dev/null +++ b/crates/ledger-gui/tests/web_connect.rs @@ -0,0 +1,577 @@ +//! The web half of the Connect page (plan P15 unit B3; WB-assist-6, +//! WB-app-6): the switch, the progress in plain words, the address with +//! Copy, the steps, every state the page can be in, and the page opening +//! by itself, once, for a person who has never connected an assistant. +//! +//! ```text +//! GOAL: a person with no technical background turns web assistants on, +//! watches it get an address and a certificate in words, copies the +//! address, follows steps that were tried (and is told plainly where +//! none were), sees what is wrong in words with nothing lost +//! locally, turns it off, and can get a new address after being +//! asked; and a first run shows the Connect page once. +//! SOURCE: plan/p15-app-and-relay.md 3.3 ("Allow web assistants" per +//! company, off by default; the address with Copy; the exact steps +//! for Claude and for ChatGPT; the relay unreachable in words, with +//! nothing lost locally; turning off keeps the name; a new address +//! behind a confirmation), 5 (the plan's research: ChatGPT's two +//! pages disagree, so no steps are written); WB-assist-6, +//! WB-app-6. +//! INVARIANTS: +//! 1. Off by default: the switch is shown off, with no address and no +//! steps, and an owner with no web assistants (`web_state` none) +//! shows no switch at all. +//! 2. The switch calls the owner and nothing else; the state is the +//! owner's, read every frame. +//! 3. The steps for Claude are exactly the three in `claude_steps`; +//! ChatGPT and any other assistant are told "we haven't tested this +//! yet", never given steps nobody tried. +//! 4. A problem that mends itself says the window and the local +//! assistants are not affected; one that needs the person does not +//! say that and says what to do. +//! 5. A new address is asked for twice: the first click only asks. +//! 6. The Connect page opens by itself once, when the window's server +//! says no assistant was ever connected, and never again; with any +//! key, session, approval or waiting request it does not open. +//! SCENARIOS: +//! 1. See the tests below; `web_screenshots` (SHOT_DIR) draws each state +//! light and dark. +//! ``` + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use ledger_core::{AccountType, Currency}; +use ledger_gui::connect::{CHATGPT_NOTE, OTHER_NOTE, Progress, claude_steps, web_progress}; +use ledger_gui::data::Source; +use ledger_gui::nav::Route; +use ledger_gui::owner::{Owner, RestorePlan, Roster, TokenRow, WebConnect, WebStep}; +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}; + +const CONNECTOR: &str = + "https://k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.wanderbooks.link/b/alpha/mcp"; + +struct World { + _dir: tempfile::TempDir, + root: PathBuf, +} + +impl World { + fn new(companies: &[(&str, &str)]) -> World { + let dir = tempfile::Builder::new() + .prefix("wb-gui-web-") + .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, name) in companies { + let mut s = found + .create_book(&BookId::parse(id).unwrap(), Currency::USD) + .unwrap(); + s.add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + s.change_settings( + &[ledger_core::settings::Change { + key: "company.name".into(), + value: Some(serde_json::json!(name)), + }], + &ledger_core::settings::Source { + decided_by: "Test".into(), + decided_on: chrono::NaiveDate::from_ymd_opt(2026, 10, 15).unwrap(), + citation: None, + note: None, + }, + ) + .unwrap(); + drop(s); + } + World { _dir: dir, root } + } + + fn source(&self, id: &str) -> Source { + Source { + data_dir: self.root.join("books").join(id), + today: chrono::NaiveDate::from_ymd_opt(2026, 10, 15), + } + } +} + +/// An owner that serves, has web assistants in whatever state a test sets, +/// and says what it was asked. +struct Web { + state: Mutex>, + roster: Mutex, + log: Mutex>, +} + +impl Web { + fn new(state: Option) -> Arc { + Arc::new(Web { + state: Mutex::new(state), + roster: Mutex::new(Roster::default()), + log: Mutex::new(vec![]), + }) + } + + fn set(&self, s: WebConnect) { + *self.state.lock().unwrap() = Some(s); + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } +} + +impl Owner for Web { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + Ok(()) + } + fn serve_open(&self, _book: &str) -> Result, String> { + Ok(None) + } + fn serve_close(&self, _book: &str) -> Result, String> { + Ok(None) + } + fn serve_stop(&self) -> Result, String> { + Ok(None) + } + fn serve_roster(&self) -> Result { + Ok(self.roster.lock().unwrap().clone()) + } + fn command_line(&self, words: &[&str]) -> Result { + Ok(format!("wanderbooks {}", words.join(" "))) + } + fn web_state(&self, _book: &str) -> Option { + self.state.lock().unwrap().clone() + } + fn web_turn_on(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("on {book}")); + Ok("Web assistants are on.".into()) + } + fn web_turn_off(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("off {book}")); + Ok("Web assistants are off.".into()) + } + fn web_new_address(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("new {book}")); + Ok("Your new address is ready.".into()) + } + fn new_books(&self, _id: &str, _currency: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _book: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore( + &self, + _source: &str, + _id: Option, + _replace: bool, + ) -> Result { + Err("not here".into()) + } + fn restore(&self, _plan: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + fn connect( + &self, + _agent: ledger_gui::owner::Agent, + _book: &str, + ) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _book: &str, _passphrase: &str) -> Result, String> { + Err("not here".into()) + } +} + +fn off() -> WebConnect { + WebConnect { + on: false, + step: WebStep::Off, + address: None, + connector: None, + words: "Web assistants are off.".into(), + problem: None, + needs_person: false, + kept: false, + } +} + +fn on(step: WebStep) -> WebConnect { + WebConnect { + on: true, + step, + address: Some(CONNECTOR.trim_end_matches("/b/alpha/mcp").into()), + connector: Some(CONNECTOR.into()), + words: String::new(), + problem: None, + needs_person: false, + kept: true, + } +} + +fn token() -> TokenRow { + TokenRow { + id: "t1".into(), + book: "alpha".into(), + name: "agent".into(), + scopes: vec!["read".into()], + created: "2026-11-01T09:00:00Z".into(), + } +} + +fn start(w: &World, owner: &Arc, kept: &[(&str, &str)], dark: bool) -> Harness<'static, App> { + let mut map: HashMap = kept + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + map.insert(ledger_gui::app::open_key(&w.root), "alpha".into()); + map.insert("dark".into(), dark.to_string()); + let (root, fallback) = (w.root.clone(), w.source("alpha")); + let for_app: Arc = owner.clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 1900.0)) + .build_eframe(move |cc| { + let mut app = App::start_with_owner( + &cc.egui_ctx, + &|k| map.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ); + app.set_now("2026-11-21T10:30:00Z".parse().unwrap()); + app + }); + let o: Arc = owner.clone(); + h.state_mut().view_mut(0).unwrap().set_owner(o); + until(&mut h, "the books load", |a| { + a.views().iter().all(|v| v.books().is_some()) + }); + h +} + +fn until(h: &mut Harness<'static, App>, what: &str, ok: impl Fn(&App) -> bool) { + let end = Instant::now() + Duration::from_secs(30); + loop { + h.run_steps(2); + if ok(h.state()) { + return; + } + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// The Connect page, in front, with the server's answer read. +fn connect_page(w: &World, owner: &Arc, dark: bool) -> Harness<'static, App> { + let mut h = start(w, owner, &[("first_connect_done", "1")], dark); + h.state_mut().view_mut(0).unwrap().open_connect(); + h.state().connections().forget(); + h.run_steps(2); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(4); + h +} + +fn texts(h: &Harness<'_, App>) -> String { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut all = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, &mut all); + } + all.join("\n") +} + +fn has(h: &Harness<'_, App>, text: &str) -> bool { + texts(h).contains(text) +} + +fn copied(h: &Harness<'_, App>) -> Vec { + h.output() + .platform_output + .commands + .iter() + .filter_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) + .collect() +} + +/// WB-assist-6 INVARIANT 1: off by default, nothing but the switch and +/// words; and no switch at all when the window cannot offer them. +#[test] +fn the_switch_is_off_by_default_and_an_owner_without_web_assistants_has_none() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let h = connect_page(&w, &owner, false); + let switch = h.get_by_role_and_label(Role::CheckBox, "Allow web assistants"); + assert_eq!( + switch.accesskit_node().toggled(), + Some(egui::accesskit::Toggled::False) + ); + assert!(has( + &h, + "Off. Nothing on this computer can be reached from the internet." + )); + assert!(!has(&h, "The address to give an assistant")); + assert!(!has(&h, "Claude on the web")); + assert!(owner.said().is_empty(), "looking asks nothing of the owner"); + + let none = Web::new(None); + let h = connect_page(&w, &none, false); + assert!( + h.query_by_role_and_label(Role::CheckBox, "Allow web assistants") + .is_none() + ); +} + +/// WB-assist-6 INVARIANTS 2, 3: turned on, the progress in plain words, +/// then the address with Copy, the three steps for Claude, and for ChatGPT +/// and the rest the plain "we haven't tested this yet". +#[test] +fn turning_it_on_shows_progress_then_the_address_the_steps_and_what_was_not_tried() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let mut h = connect_page(&w, &owner, false); + h.get_by_role_and_label(Role::CheckBox, "Allow web assistants") + .click(); + until(&mut h, "the owner was asked", |_| !owner.said().is_empty()); + assert_eq!(owner.said(), ["on alpha"]); + + owner.set(on(WebStep::GettingAddress)); + h.run_steps(4); + assert!(has(&h, "Getting an address\u{2026}")); + assert!(has(&h, "Getting a certificate")); + assert!( + !has(&h, "Add custom connector"), + "no steps before there is an address that works" + ); + + owner.set(on(WebStep::GettingCertificate)); + h.run_steps(4); + assert!(has(&h, "Getting a certificate\u{2026}")); + + owner.set(on(WebStep::Connected)); + h.run_steps(4); + assert!(has(&h, "Connected")); + assert!(has(&h, CONNECTOR)); + for (i, step) in claude_steps().iter().enumerate() { + assert!(has(&h, &format!("{}. {step}", i + 1)), "{step}"); + } + assert!(has(&h, CHATGPT_NOTE) && CHATGPT_NOTE.contains("We haven't tested this yet")); + assert!(has(&h, OTHER_NOTE) && OTHER_NOTE.contains("we haven't tested these yet")); + // The word MCP is nowhere. + assert!(!texts(&h).contains("MCP")); + // Copy puts the address for this company on the clipboard. + h.get_by_role_and_label(Role::Button, "Copy the address") + .click(); + h.step(); + assert_eq!(copied(&h), [CONNECTOR]); + h.run_steps(2); + assert!(has(&h, "Copied")); +} + +/// The progress words are one function: what is done, what is under way, +/// what waits. +#[test] +fn the_progress_steps_are_in_order() { + use Progress::*; + let p = |s| web_progress(s).map(|(_, p)| p); + assert_eq!(p(WebStep::GettingAddress), [Now, Waiting, Waiting]); + assert_eq!(p(WebStep::Connecting), [Now, Waiting, Waiting]); + assert_eq!(p(WebStep::GettingCertificate), [Done, Now, Waiting]); + assert_eq!(p(WebStep::Connected), [Done, Done, Done]); + let words: Vec<_> = web_progress(WebStep::Connected).map(|(w, _)| w).to_vec(); + assert_eq!( + words, + ["Getting an address", "Getting a certificate", "Connected"] + ); +} + +/// WB-assist-6 INVARIANT 4: the relay cannot be reached (nothing is lost, +/// the window and the local assistants work), the clock is wrong (it needs +/// the person), the certificate is waited for. +#[test] +fn what_goes_wrong_is_in_words_and_says_what_is_not_affected() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(WebConnect { + problem: Some("This computer can't reach the internet. Your assistants on this computer still work. Web assistants will connect again as soon as the internet is back.".into()), + ..on(WebStep::Connecting) + })); + let h = connect_page(&w, &owner, false); + assert!(has(&h, "This computer can't reach the internet.")); + assert!(has( + &h, + "Your assistants on this computer, and this window, are not affected." + )); + // The local rows are there, above, untouched. + assert!(has(&h, "On this computer")); + + owner.set(WebConnect { + problem: Some("This computer's clock looks wrong, so the relay can't be trusted yet. Set the date and time (turn on \"set automatically\"), and Wanderbooks will connect by itself.".into()), + needs_person: true, + ..on(WebStep::Connecting) + }); + let mut h = h; + h.run_steps(4); + assert!(has(&h, "clock looks wrong")); + assert!(!has(&h, "are not affected")); + + owner.set(WebConnect { + problem: Some( + "Wanderbooks could not get a certificate yet: the authority says no. It keeps trying." + .into(), + ), + ..on(WebStep::GettingCertificate) + }); + h.run_steps(4); + assert!(has(&h, "could not get a certificate yet")); +} + +/// WB-assist-6: off calls the owner; a new address is asked for twice. +#[test] +fn off_and_a_new_address_go_through_the_owner_and_a_new_one_is_asked_twice() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(on(WebStep::Connected))); + let mut h = connect_page(&w, &owner, false); + // The first click only asks. + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + assert!(has(&h, "The old address stops working at once.")); + assert!(owner.said().is_empty()); + // Keeping the old one does nothing. + h.get_by_label("Keep the old one").click(); + h.run_steps(3); + assert!(!has(&h, "The old address stops working at once.")); + assert!(owner.said().is_empty()); + // The second click does it. + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + h.get_by_label("Get a new address").click(); + until(&mut h, "the owner was asked", |_| !owner.said().is_empty()); + assert_eq!(owner.said(), ["new alpha"]); + + h.get_by_role_and_label(Role::CheckBox, "Allow web assistants") + .click(); + until(&mut h, "off", |_| owner.said().len() == 2); + assert_eq!(owner.said()[1], "off alpha"); +} + +/// WB-app-6: the first time a company is open and no assistant was ever +/// connected, the Connect page opens by itself, once. +#[test] +fn the_connect_page_opens_by_itself_once_for_a_first_run() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let mut h = start(&w, &owner, &[], false); + until(&mut h, "the page opens", |a| a.first_connect_done()); + h.run_steps(3); + assert_eq!(h.state().route(), &Route::Connect); + // Local rows first, the web below. + assert!(has(&h, "On this computer") && has(&h, "On the web")); + // The person goes elsewhere: it does not open again. + h.state_mut().view_mut(0).unwrap().goto(Route::Company); + h.run_steps(6); + assert_ne!(h.state().route(), &Route::Connect); +} + +/// WB-app-6: it is remembered per installation, and not for a person who +/// has connected an assistant, or has one waiting. +#[test] +fn the_connect_page_does_not_open_when_it_was_shown_or_an_assistant_exists() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + // Shown before (kept preference). + let owner = Web::new(Some(off())); + let mut h = start(&w, &owner, &[("first_connect_done", "1")], false); + h.run_steps(8); + assert_ne!(h.state().route(), &Route::Connect); + // A key exists. + let owner = Web::new(Some(off())); + owner.roster.lock().unwrap().tokens.push(token()); + let mut h = start(&w, &owner, &[], false); + h.state().connections().forget(); + h.run_steps(6); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(6); + assert_ne!(h.state().route(), &Route::Connect); + assert!( + h.state().first_connect_done(), + "an existing assistant ends the first run for good" + ); +} + +/// Pictures for eyes: set `SHOT_DIR`. Each state of the web half, light and +/// dark. +#[test] +fn web_screenshots() { + let Ok(out) = std::env::var("SHOT_DIR") else { + return; + }; + let out = PathBuf::from(out); + std::fs::create_dir_all(&out).unwrap(); + let w = World::new(&[("alpha", "Wanderland Labs")]); + let states: Vec<(&str, WebConnect, bool)> = vec![ + ("1-off", off(), false), + ("2-getting-an-address", on(WebStep::GettingAddress), false), + ( + "3-getting-a-certificate", + on(WebStep::GettingCertificate), + false, + ), + ("4-connected", on(WebStep::Connected), false), + ( + "5-no-internet", + WebConnect { + problem: Some(ledger_link::Trouble::NoInternet.words()), + ..on(WebStep::Connecting) + }, + false, + ), + ( + "6-clock-wrong", + WebConnect { + problem: Some(ledger_link::Trouble::ClockWrong.words()), + needs_person: true, + ..on(WebStep::Connecting) + }, + false, + ), + ("7-new-address", on(WebStep::Connected), true), + ]; + for dark in [false, true] { + for (name, state, ask) in &states { + let owner = Web::new(Some(state.clone())); + let mut h = connect_page(&w, &owner, dark); + if *ask { + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + } + h.run_steps(3); + h.render() + .unwrap() + .save(out.join(format!( + "{name}-{}.png", + if dark { "dark" } else { "light" } + ))) + .unwrap(); + } + } +}