From 022c0c642f6adc517e57003375dc2e9ed3d9d805 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:03:35 -0700 Subject: [PATCH] feat(gui): each company's assistants: three states, Ask your assistant, the Connect page, a warning before closing P15 unit A4, plan 3.3 and D-79. The window only reads the books, so it now says so by what it offers. Each company is in one of three states (no assistant, connected, working) read from the books server's own sessions answer, never waited for, drawn as a shape on its tab and said in words with the last thing done at the right of the top bar; the sidebar gives up no height, because the links must all fit at 1479x519. Where a button that edits would be there is "Ask your assistant", which copies a ready sentence. The Connect page has a row per local tool with exact commands, the keys with who is on each, and Revoke through the existing command path. Closing the window or a tab with an assistant connected warns first, before and never beside the server's own close. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/app.rs | 292 ++++- crates/ledger-gui/src/company.rs | 101 +- crates/ledger-gui/src/connect.rs | 911 +++++++++++++++ crates/ledger-gui/src/connections.rs | 573 +++++++++ crates/ledger-gui/src/lib.rs | 2 + crates/ledger-gui/src/nav.rs | 5 +- crates/ledger-gui/src/pages/accounts.rs | 3 +- crates/ledger-gui/src/pages/assets.rs | 3 +- crates/ledger-gui/src/pages/company.rs | 3 +- crates/ledger-gui/src/pages/documents.rs | 3 +- crates/ledger-gui/src/pages/invoices.rs | 7 +- crates/ledger-gui/src/pages/mod.rs | 3 + crates/ledger-gui/src/pages/parties.rs | 3 +- crates/ledger-gui/src/pages/projects.rs | 2 +- crates/ledger-gui/src/pages/transactions.rs | 3 +- crates/ledger-gui/src/palette.rs | 1 + crates/ledger-gui/src/serving.rs | 20 + crates/ledger-gui/src/tabs.rs | 18 +- crates/ledger-gui/src/widgets.rs | 41 + crates/ledger-gui/tests/assistants.rs | 1020 +++++++++++++++++ .../tests/snapshots/assist_ask_dark.shapes | 1 + .../tests/snapshots/assist_ask_light.shapes | 1 + .../snapshots/assist_connect_page_dark.shapes | 1 + .../assist_connect_page_light.shapes | 1 + .../snapshots/assist_connected_dark.shapes | 1 + .../snapshots/assist_connected_light.shapes | 1 + .../tests/snapshots/assist_none_dark.shapes | 1 + .../tests/snapshots/assist_none_light.shapes | 1 + .../snapshots/assist_working_dark.shapes | 1 + .../snapshots/assist_working_light.shapes | 1 + docs/parity.md | 1 + docs/spec/claims/assistants.md | 98 ++ 32 files changed, 3083 insertions(+), 40 deletions(-) create mode 100644 crates/ledger-gui/src/connect.rs create mode 100644 crates/ledger-gui/src/connections.rs create mode 100644 crates/ledger-gui/tests/assistants.rs create mode 100644 crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_ask_light.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_connected_light.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_none_dark.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_none_light.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_working_dark.shapes create mode 100644 crates/ledger-gui/tests/snapshots/assist_working_light.shapes create mode 100644 docs/spec/claims/assistants.md diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 51b3acf3..30b61cd1 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -58,9 +58,10 @@ //! companies restored at the start are opened with the server, a //! company opened later when its tab opens, and closed when its tab //! closes. What fails, and a server that stops on its own, is a -//! notice under the tab bar, in words, until dismissed. Where the -//! session list and the connection states will go (A4) is -//! `Self::connection_slot`. +//! notice under the tab bar, in words, until dismissed. Who is +//! connected to each company is asked of the server off the UI thread +//! and fed to each view every frame (`Self::status_of`, connections.rs; +//! WB-assist-1). //! 9. Asked to close, a window with a server stays up, saying it is //! closing the books, until the server has exited or its bounded //! close has run out (and then says what is left); a close is never @@ -70,9 +71,20 @@ //! it, with a "Close anyway" button; closing again is not that. //! A server still starting is said under the tab bar, and one whose //! start failed has a "Try again" button there (WB-app-2). +//! 10. Closing the window, or a tab, while an assistant is connected to +//! what would close warns first, in words, and closes only when the +//! person says so (WB-assist-2, D-79). One dialog is up at a time: +//! a job that holds the window (7) has its own dialog first and no +//! warning is raised meanwhile; the warning comes before the server's +//! close (9) and goes before it begins, so "Closing your books" and +//! the close report are never up with it; a close the person +//! confirmed goes straight to (9) and is not warned again. Who is +//! connected is read off the UI thread and never waited for; a server +//! that does not answer is not a reason to hold a close. //! ``` use crate::company::CompanyView; +use crate::connections::{Connections, Link, Status}; use crate::data::Source; use crate::nav::Route; use crate::scheme_menu::SchemeMenu; @@ -165,8 +177,35 @@ pub struct App { serving: Serving, /// What the server work has said that the person has not dismissed. notices: Vec, + /// Who is connected to each company, asked of the server off the UI + /// thread (connections.rs). + connections: Connections, + /// The warning about assistants that is up, if any: one at a time + /// (INVARIANT 10). + warn: Warn, + /// The person confirmed a close of the window that assistants were + /// told of: the next close request goes through to the server's close. + assistants_ok: bool, + /// "Now" for "10 seconds ago", fixed (tests, screenshots) or not. + fixed_now: Option>, } +/// The warning about assistants that is up (INVARIANT 10). +#[derive(Clone, Debug, PartialEq, Eq)] +enum Warn { + /// None. + Off, + /// Closing the tab of the company with this key was asked. + Tab(String), + /// Closing the window was asked. + Window, +} + +/// How long an answer of the server about who is connected is believed for +/// the warning before a close: longer than for the state, so a server slow +/// 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); + /// What a window is called when no company is in front. const TITLE: &str = "wanderbooks"; @@ -338,6 +377,10 @@ impl App { closing_window: false, serving: Serving::off(), notices: Vec::new(), + connections: Connections::new(), + warn: Warn::Off, + assistants_ok: false, + fixed_now: None, } } @@ -555,9 +598,215 @@ impl App { &self.serving } - /// Where the connection states and the list of who is connected will - /// be shown (plan 3.3, unit A4); nothing is drawn yet. - fn connection_slot(&mut self, _ui: &mut Ui) {} + /// "Now", for "10 seconds ago". + fn now(&self) -> chrono::DateTime { + self.fixed_now.unwrap_or_else(chrono::Utc::now) + } + + /// Fix "now" (tests and screenshots). + pub fn set_now(&mut self, now: chrono::DateTime) { + self.fixed_now = Some(now); + } + + /// Who is connected, as the window asks the server (tests). + pub fn connections(&self) -> &Connections { + &self.connections + } + + /// What is known of the assistants of the company in `v`, believing an + /// answer no older than `age`. + fn status_within(&self, age: std::time::Duration, v: &CompanyView) -> Status { + self.connections.status_within( + age, + self.serving.is_on(), + self.serving.is_down() || self.serving.has_exited(), + v.book_id().as_deref(), + &self.title_of(v), + self.now(), + ) + } + + /// What is known of the assistants of the company in `v` (WB-assist-1). + fn status_of(&self, v: &CompanyView) -> Status { + self.status_within(crate::connections::STALE, v) + } + + /// Ask the server who is connected, now and then, while it is up; the + /// answer is read next frame (never waited for). + fn drive_connections(&mut self, ctx: &egui::Context) { + let mut refresh = false; + for v in &mut self.views { + refresh |= v.take_roster_refresh(); + } + if refresh { + self.connections.forget(); + } + if !self.serving.is_up() { + return; + } + if let Some(owner) = self.serving.owner() { + self.connections.poll(ctx, &owner, refresh); + } + } + + /// The assistants connected to the company in `v` that the window may + /// warn of: the server's last answer within [`WARN_AGE`]. Only while a + /// server is up. + fn connected_to(&self, v: &CompanyView) -> Status { + let mut s = self.status_within(WARN_AGE, v); + if !self.serving.is_up() { + s.assistants.clear(); + s.link = Link::Unknown; + } + s + } + + /// Whether an assistant is connected to a company. + fn has_assistant(s: &Status) -> bool { + matches!(s.link, Link::Connected | Link::Working) + } + + /// Whether a warning about assistants is up (tests). + pub fn assistant_warning_is_up(&self) -> bool { + self.warn != Warn::Off + } + + /// Whether the warning up is about closing the window, not a tab + /// (tests). + pub fn window_warning_is_up(&self) -> bool { + self.warn == Warn::Window + } + + /// Closing the tab `i` was asked (the tab's control, a middle click): + /// warned first when an assistant is connected to it (INVARIANT 10), + /// else closed. A tab with a job that changes the books is not closed + /// (INVARIANT 7). + pub fn ask_close(&mut self, i: usize) { + let Some(v) = self.views.get(i) else { return }; + if v.closing_is_held().is_some() { + return; + } + if Self::has_assistant(&self.connected_to(v)) { + self.warn = Warn::Tab(v.key().to_string()); + return; + } + self.close(i); + } + + /// The warnings about assistants (INVARIANT 10): true while the + /// window's own close is being held by one, so the server's close does + /// not begin. + fn guard_assistants(&mut self, ctx: &egui::Context) -> bool { + let asked = ctx.input(|i| i.viewport().close_requested()); + // A job that holds the window has its dialog (INVARIANT 7), and a + // close that has begun is the server's (9): nothing is raised + // then. + if asked && self.holding().is_empty() && !self.serving.is_closing() { + if self.assistants_ok { + // Confirmed: it goes through, to the close of the books. + self.assistants_ok = false; + } else if self + .views + .iter() + .any(|v| Self::has_assistant(&self.connected_to(v))) + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.warn = Warn::Window; + } + } + match self.warn.clone() { + Warn::Off => false, + Warn::Tab(key) => { + let Some(i) = self.views.iter().position(|v| v.key() == key) else { + self.warn = Warn::Off; + return false; + }; + let status = self.connected_to(&self.views[i]); + if !Self::has_assistant(&status) { + // They are gone: nothing is left to warn of. + self.warn = Warn::Off; + self.close(i); + return false; + } + let (mut close, mut keep) = (false, false); + let response = egui::Modal::new(egui::Id::new("wanderbooks-close-tab-assistants")) + .show(ctx, |ui| { + ui.set_max_width(460.0); + ui.heading(format!("Close {}?", status.company)); + ui.add_space(4.0); + ui.label(format!("{}.", status.word())); + ui.label( + "Closing the company ends the connection: the assistant can no longer reach these books until you open the company again. What it is in the middle of finishes first.", + ); + ui.add_space(6.0); + ui.horizontal(|ui| { + if ui.button("Close the company").clicked() { + close = true; + } + if ui.button("Keep it open").clicked() { + keep = true; + } + }); + }); + if close { + self.warn = Warn::Off; + self.close(i); + } else if keep || response.should_close() { + self.warn = Warn::Off; + } + false + } + Warn::Window => { + let connected: Vec = self + .views + .iter() + .map(|v| self.connected_to(v)) + .filter(Self::has_assistant) + .collect(); + if connected.is_empty() { + // They are gone: the person asked to close, so it does. + self.warn = Warn::Off; + self.assistants_ok = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + return false; + } + let (mut close, mut keep) = (false, false); + let response = egui::Modal::new(egui::Id::new("wanderbooks-close-assistants")) + .show(ctx, |ui| { + ui.set_max_width(480.0); + ui.heading("Assistants are connected"); + ui.add_space(4.0); + for s in &connected { + ui.label(format!("{}: {}", s.company, s.word())); + } + ui.add_space(4.0); + ui.label( + "Closing Wanderbooks ends their connection. What an assistant is in the middle of finishes first, and nothing is cut off half way. They can carry on once Wanderbooks is open again.", + ); + ui.add_space(6.0); + ui.horizontal(|ui| { + if ui.button("Close Wanderbooks").clicked() { + close = true; + } + if ui.button("Keep it open").clicked() { + keep = true; + } + }); + }); + if close { + self.warn = Warn::Off; + self.assistants_ok = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + false + } else { + if keep || response.should_close() { + self.warn = Warn::Off; + } + self.warn == Warn::Window + } + } + } + } /// The window's title now. pub fn window_title(&self) -> String { @@ -782,7 +1031,7 @@ impl App { fn act(&mut self, ctx: &egui::Context, action: TabAction) { match action { TabAction::Show(i) => self.activate(i), - TabAction::Close(i) => self.close(i), + TabAction::Close(i) => self.ask_close(i), TabAction::Open(id) => { let Some(root) = self.root.clone() else { return; @@ -958,22 +1207,38 @@ impl eframe::App for App { v.pump(&ctx, i == self.active); } self.guard_close(&ctx); - self.guard_server_close(&ctx); + if !self.guard_assistants(&ctx) { + self.guard_server_close(&ctx); + } self.check_identities(); self.learn_names(); + // Who is connected to each company: asked of the server off this + // thread, read here (WB-assist-1), and given to each view. + self.drive_connections(&ctx); + let statuses: Vec = self.views.iter().map(|v| self.status_of(v)).collect(); + for (v, s) in self.views.iter_mut().zip(&statuses) { + v.set_assist(s.clone()); + } let tabs: Vec = self .views .iter() - .map(|v| { + .zip(&statuses) + .map(|(v, status)| { let title = self.title_of(v); + let mut detail = match v.book_id() { + Some(id) if id != title => format!("{title}\n{id}"), + _ => title.clone(), + }; + if status.serves && status.link != Link::Unknown { + detail.push('\n'); + detail.push_str(&status.hover()); + } Tab { held: v.closing_is_held(), - detail: match v.book_id() { - Some(id) if id != title => format!("{title}\n{id}"), - _ => title.clone(), - }, + detail, title, hue_key: v.hue_key(), + link: status.link, } }) .collect(); @@ -983,7 +1248,6 @@ impl eframe::App for App { // company in front: a tab is the top level (D-78). let action = self.tabs.show(ui, &tabs, shown, &others); self.show_notices(ui); - self.connection_slot(ui); let active = self.active; match self.views.get_mut(active) { Some(v) => v.ui(ui, &mut self.schemes), diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 798efdf4..6d69b85e 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -129,6 +129,11 @@ pub struct CompanyView { /// The identity of the books as last loaded (None while there is no /// journal line to take it from). loaded_identity: Option, + /// What the window knows of this company's assistants, given by the app + /// each frame (connections.rs): the state, who is connected, the keys. + assist: crate::connections::Status, + /// The Connect page's own state (connect.rs). + connect: crate::connect::State, } impl Drop for CompanyView { @@ -175,6 +180,8 @@ impl CompanyView { jobs, identity: None, loaded_identity: None, + assist: crate::connections::Status::off(""), + connect: Default::default(), } } @@ -215,6 +222,28 @@ impl CompanyView { self } + /// What the window knows of this company's assistants, as of this + /// frame (the app gives it before it draws the view). + pub fn set_assist(&mut self, status: crate::connections::Status) { + self.assist = status; + } + + /// What this view was last given of its assistants (tests). + pub fn assist(&self) -> &crate::connections::Status { + &self.assist + } + + /// The Connect page's state (tests). + pub fn connect_state(&self) -> &crate::connect::State { + &self.connect + } + + /// A revoke on the Connect page just ended: who is connected must be + /// read again (taken once). + pub fn take_roster_refresh(&mut self) -> bool { + self.connect.take_refresh() + } + /// What tells this company's view apart from another's. pub fn key(&self) -> &str { &self.key @@ -505,16 +534,45 @@ impl CompanyView { // Books waiting for a format upgrade: said above every page // until it is done (owner.rs INVARIANT 5). self.owner_menu.notice(ui, self.owner.clone(), &books); - let mut shell = Shell { - receipts: &mut self.receipts, - state: &mut self.state, - go: None, - since_update, - }; let route = self.nav.current.clone(); - pages::show(ui, &books, &route, &mut shell); - if let Some(to) = shell.go.take() { - self.nav.go(to); + // What "Ask your assistant" on a page is about. + crate::connect::set_context( + ui.ctx(), + crate::connect::AskContext { + company: self.assist.company.clone(), + serves: self.assist.serves, + link: self.assist.link, + }, + ); + if route == Route::Connect { + // The Connect page keeps its own state (connect.rs). + match self.book_id() { + Some(book) => { + let spawner = self.jobs.spawner(); + self.connect.show( + ui, + &self.assist, + &book, + self.owner.clone(), + &spawner, + ); + } + None => self.nav.go(Route::Company), + } + } else { + let mut shell = Shell { + receipts: &mut self.receipts, + state: &mut self.state, + go: None, + since_update, + }; + pages::show(ui, &books, &route, &mut shell); + if let Some(to) = shell.go.take() { + self.nav.go(to); + } + } + if crate::connect::take_go(ui.ctx()) { + self.nav.go(Route::Connect); } if let Some(to) = self.palette.show(ui.ctx(), &books) { self.nav.go(to); @@ -1027,6 +1085,22 @@ impl CompanyView { .color(p.muted), ); } + // The assistants: its shape and words, then what it + // last did while there is room (connect.rs). + let room = if width >= 1100.0 { + Some(crate::connect::Room::Full) + } else if width >= 780.0 { + Some(crate::connect::Room::Word) + } else if width >= 520.0 { + Some(crate::connect::Room::Icon) + } else { + None + }; + if let Some(room) = room + && crate::connect::chip(ui, &self.assist, room) + { + self.nav.go(Route::Connect); + } ui.add_space(8.0); ui.with_layout(Layout::left_to_right(Align::Center), |ui| { let crumbs = @@ -1681,11 +1755,10 @@ fn footer_layout( } } -/// The top of the sidebar (and of the rail): where the assistant's -/// connection state goes, in a later unit. It draws nothing today, so the -/// links begin at the panel's top margin, under the tab bar. A block put -/// here adds its own height and gap below it ([`HEAD_GAP`], -/// [`HEAD_GAP_TIGHT`] are what the fit leaves under it). +/// The top of the sidebar (and of the rail). It stays empty, on purpose: the +/// links must all fit at 1479x519 (`tests/sidenav.rs`), so nothing is added +/// above them. The assistant state is in the top bar instead, where it costs +/// no height (`topbar`, `connect::chip`). fn top_slot(_ui: &mut Ui) {} /// What the status card says of its company: the heading row's badge diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs new file mode 100644 index 00000000..c61a670e --- /dev/null +++ b/crates/ledger-gui/src/connect.rs @@ -0,0 +1,911 @@ +//! What the window says about assistants: the state mark, the top bar's +//! assistant state, "Ask your assistant", and the Connect page (plan P15 +//! 3.3). The window only reads the books; to change anything a person asks +//! an assistant, and these are where it says so. The word is "assistant". +//! +//! ```text +//! GOAL: a person who has never heard of any of this can see that they may +//! read everything here, that to change anything they ask an +//! assistant, whether one is connected, and how to connect one; and +//! they can end an assistant's access. +//! SOURCE: plan/p15-app-and-relay.md 3.3 (the word is "assistant"; every +//! tab carries one of three states as a shape and a word; "Ask your +//! assistant" where a button that edits would be, copying a ready +//! 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. +//! 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 +//! arc), with the words in its hover; the front company's state is +//! said in words once, at the right of its top bar, with what it last +//! did; the Connect page lists the keys and who is on each. None of +//! them repeats the company's name or the status card's "Live". The +//! state takes no height: the sidebar's links must all fit at +//! 1479x519 (`tests/sidenav.rs`), so nothing is added above them. +//! 2. The state is never colour alone: each has its own shape and its +//! own word; colour only adds. +//! 3. "Ask your assistant" copies one ready sentence naming the company +//! and what the page is for ("In my Wanderbooks books for Acme, +//! please create a new invoice."); with no assistant connected it +//! says so and where to connect one. It writes nothing: it only puts +//! the sentence on the clipboard. +//! 4. The Connect page shows exact instructions, and only ones this +//! build can stand behind: Claude Code and Codex have a button that +//! does what `wanderbooks connect` does and the command it runs; for +//! any other tool the page gives the program and arguments an +//! assistant must run, and says the tool is untested. No config format +//! is shown that the repository does not document. +//! 5. Revoke asks once, then calls what `wanderbooks token revoke` calls +//! (the owner's `serve_revoke`); the window writes no books. Its job +//! holds the window open until it ends (owner.rs INVARIANT 6). +//! 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: `State::web_section` is its +//! place, and it draws nothing until then. +//! ``` + +use crate::connections::{Connection, Link, Status, describe, program_name}; +use crate::owner::Owner; +use crate::theme::{self, pal}; +use egui::{Align, CornerRadius, Frame, Layout, Margin, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as icon; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, channel}; + +// ---- the shape of a state --------------------------------------------------- + +/// Paint the mark of `link` centred on `at`, `size` points across: plugs +/// apart (no assistant), plugs together (connected), a turning arc +/// (working). Nothing for `Link::Unknown`. +pub fn paint_mark(ui: &Ui, at: egui::Pos2, size: f32, link: Link) { + let p = pal(ui.ctx()); + match link { + Link::Unknown => {} + Link::None => { + ui.painter().text( + at, + egui::Align2::CENTER_CENTER, + icon::PLUGS, + egui::FontId::proportional(size), + p.faint, + ); + } + Link::Connected => { + ui.painter().text( + at, + egui::Align2::CENTER_CENTER, + icon::PLUGS_CONNECTED, + egui::FontId::proportional(size), + p.positive, + ); + } + Link::Working => { + // A three-quarter arc, turning. + let r = size * 0.36; + let turn = (ui.input(|i| i.time) * 1.6).fract() as f32 * std::f32::consts::TAU; + let points: Vec = (0..=18) + .map(|k| { + let a = turn + k as f32 / 18.0 * std::f32::consts::TAU * 0.75; + at + vec2(a.cos(), a.sin()) * r + }) + .collect(); + ui.painter() + .add(egui::Shape::line(points, Stroke::new(2.0, p.accent))); + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(50)); + } + } +} + +// ---- the state in the top bar ------------------------------------------------- + +/// How much of the state the top bar has room for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Room { + /// The shape, the words and what was last done (two lines). + Full, + /// The shape and the words. + Word, + /// The shape alone (the words are its hover). + Icon, +} + +impl Room { + /// How wide the state takes, in points. + pub fn width(self) -> f32 { + match self { + Room::Full => 272.0, + Room::Word => 196.0, + Room::Icon => 30.0, + } + } +} + +/// The state of the front company in the top bar, at the right, where a +/// status is looked for: its shape, the state in words and what was last +/// done, or how to connect one. True when it was clicked (the Connect page +/// is wanted). Nothing for a window that runs no server. It costs no height: +/// the sidebar's links must fit at 1479x519 (`tests/sidenav.rs`), so nothing +/// is added above them. +pub fn chip(ui: &mut Ui, status: &Status, room: Room) -> bool { + if !status.serves { + return false; + } + let p = pal(ui.ctx()); + let (rect, resp) = ui.allocate_exact_size(vec2(room.width(), 32.0), Sense::click()); + if resp.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(8), p.hover); + } + let known = status.link != Link::Unknown; + paint_mark( + ui, + egui::pos2(rect.left() + 16.0, rect.center().y), + 18.0, + status.link, + ); + let text_x = rect.left() + 34.0; + let room_w = (rect.right() - 6.0 - text_x).max(10.0); + let line = |ui: &Ui, text: String, font: egui::FontId, color: egui::Color32, y: f32| { + let mut job = + egui::text::LayoutJob::single_section(text, egui::TextFormat::simple(font, color)); + job.wrap.max_width = room_w; + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.overflow_character = Some('…'); + let g = ui.painter().layout_job(job); + ui.painter() + .galley(egui::pos2(text_x, y - g.size().y / 2.0), g, color); + }; + if room != Room::Icon { + let two = room == Room::Full && known; + let y = rect.center().y; + if known { + line( + ui, + status.word(), + theme::semibold(13.0), + p.text, + if two { y - 8.0 } else { y }, + ); + if two { + let color = if status.link == Link::None { + p.accent + } else { + p.muted + }; + line(ui, status.detail(), theme::regular(11.5), color, y + 8.0); + } + } else { + let (text, color) = if status.down { + (status.word(), p.warning) + } else { + (format!("{}…", status.word()), p.faint) + }; + line(ui, text, theme::regular(12.5), color, y); + } + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, status.word())); + let tip = if known { + format!("{}\nClick to connect or manage", status.hover()) + } else if status.down { + "Assistants can't connect now: see the notice at the top of the window".to_string() + } else { + "Asking the books server who is connected".to_string() + }; + resp.on_hover_text(tip).clicked() +} + +// ---- "Ask your assistant" --------------------------------------------------- + +/// What the pages need to know to offer "Ask your assistant", put where +/// they can read it for the company in front. +#[derive(Clone, Debug)] +pub struct AskContext { + /// The company's name. + pub company: String, + /// Whether the window runs a server (without one, nothing is offered). + pub serves: bool, + /// The state. + pub link: Link, +} + +fn ask_key() -> egui::Id { + egui::Id::new("wanderbooks-ask-context") +} + +fn go_key() -> egui::Id { + egui::Id::new("wanderbooks-ask-go") +} + +/// Say, for this frame, what "Ask your assistant" is about. +pub fn set_context(ctx: &egui::Context, c: AskContext) { + ctx.data_mut(|d| d.insert_temp(ask_key(), c)); +} + +/// Whether "Ask your assistant" is offered on the page now: only in a window +/// that runs a books server. +pub fn asking_is_offered(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(ask_key())) + .is_some_and(|c| c.serves) +} + +/// Whether "Connect an assistant" was clicked on a page this frame. +pub fn take_go(ctx: &egui::Context) -> bool { + ctx.data_mut(|d| d.remove_temp::(go_key())) + .unwrap_or(false) +} + +/// The sentence "Ask your assistant" copies (INVARIANT 3). +pub fn sentence(company: &str, what: &str) -> String { + format!("In my Wanderbooks books for {company}, please {what}.") +} + +/// The "Ask your assistant" button, where a button that edits the books +/// would be: it copies a ready sentence for `what` ("create a new +/// invoice") to paste into the assistant, and says so. Nothing is offered +/// in a window that runs no server. `id` tells apart two on one page. +pub fn ask_button(ui: &mut Ui, what: &str) { + let Some(c) = ui.ctx().data(|d| d.get_temp::(ask_key())) else { + return; + }; + if !c.serves { + return; + } + let p = pal(ui.ctx()); + let id = ui.id().with("ask-your-assistant"); + let button = egui::Button::new( + RichText::new(format!("{} Ask your assistant", icon::CHAT_CENTERED_TEXT)) + .font(theme::semibold(13.0)) + .color(p.accent), + ) + .fill(p.accent_soft) + .stroke(Stroke::new(1.0, p.accent)) + .corner_radius(CornerRadius::same(8)) + .min_size(vec2(0.0, 30.0)); + let resp = ui.add(button).on_hover_text( + "Copies a sentence to paste into your assistant: this window only reads the books", + ); + if resp.clicked() { + ui.ctx().copy_text(sentence(&c.company, what)); + let now = ui.input(|i| i.time); + ui.ctx().data_mut(|d| d.insert_temp(id, now)); + } + resp.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Ask your assistant") + }); + let said_at: Option = ui.ctx().data(|d| d.get_temp(id)); + let now = ui.input(|i| i.time); + if let Some(at) = said_at + && now - at < 8.0 + { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + ui.ctx() + .data_mut(|d| d.insert_temp(ask_said_key(), (what.to_string(), at))); + } +} + +fn ask_said_key() -> egui::Id { + egui::Id::new("wanderbooks-ask-said") +} + +/// The line under a page's title that follows a click on "Ask your +/// assistant": what was copied, and, with no assistant connected, where to +/// connect one. Drawn by the page header; nothing while it has not been +/// clicked. +pub fn ask_feedback(ui: &mut Ui) { + let Some(c) = ui.ctx().data(|d| d.get_temp::(ask_key())) else { + return; + }; + let said: Option<(String, f64)> = ui.ctx().data(|d| d.get_temp(ask_said_key())); + let now = ui.input(|i| i.time); + let Some((what, at)) = said else { return }; + if now - at >= 8.0 { + ui.ctx() + .data_mut(|d| d.remove_temp::<(String, f64)>(ask_said_key())); + return; + } + let p = pal(ui.ctx()); + ui.add_space(6.0); + ui.label( + RichText::new(format!( + "{} Copied: “{}” Paste it into your assistant.", + icon::CHECK, + sentence(&c.company, &what) + )) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if c.link == Link::None { + ui.horizontal(|ui| { + ui.label( + RichText::new("No assistant is connected yet.") + .font(theme::regular(13.0)) + .color(p.warning), + ); + if ui.link("Connect an assistant").clicked() { + ui.ctx().data_mut(|d| d.insert_temp(go_key(), true)); + } + }); + } +} + +// ---- the Connect page ------------------------------------------------------- + +/// A tool the page has a row for. +struct Tool { + /// Its name. + name: &'static str, + /// The agent the owner can connect with one button, if it can. + agent: Option, + /// The words that add it to the tool by hand (before the command), if + /// the repository documents them; None says: give the program and its + /// arguments (INVARIANT 4). + add_by_hand: Option<&'static str>, +} + +/// The tools of "On this computer", in the order of plan 3.3. +const TOOLS: [Tool; 6] = [ + Tool { + name: "Claude Code", + agent: Some(crate::owner::Agent::Claude), + add_by_hand: Some("claude mcp add --scope user"), + }, + Tool { + name: "Codex", + agent: Some(crate::owner::Agent::Codex), + add_by_hand: Some("codex mcp add"), + }, + Tool { + name: "Gemini CLI", + agent: None, + add_by_hand: None, + }, + Tool { + name: "Grok Build", + agent: None, + add_by_hand: None, + }, + Tool { + name: "Muse Code", + agent: None, + add_by_hand: None, + }, + Tool { + name: "Cursor", + agent: None, + add_by_hand: None, + }, +]; + +type Outcome = Result; + +/// The Connect page's memory: the command lines (found once), the job under +/// way and its result, and a revoke asked once. +#[derive(Default)] +pub struct State { + /// The command lines for this company, found once: `Err` says why + /// there are none. + commands: Option<(String, Result)>, + /// A job under way: what it is, and its answer. + job: Option<(String, Receiver)>, + /// What the last job said. + done: Option<(String, Outcome)>, + /// The key whose Revoke was clicked once: the second click does it. + confirm: Option, + /// A revoke ended: the state is read again. + refresh: bool, +} + +/// The two lines an assistant set up by hand needs. +#[derive(Clone)] +struct Commands { + /// What the assistant runs: this program with `mcp --book ID`. + bridge: String, +} + +impl State { + /// Whether a revoke just ended, so who is connected must be read again + /// (taken once). + pub fn take_refresh(&mut self) -> bool { + std::mem::take(&mut self.refresh) + } + + /// Whether a job of this page is running (the page is not left to + /// start another). + pub fn busy(&self) -> bool { + self.job.is_some() + } + + /// What the last job said, `(what, result)` (tests). + pub fn said(&self) -> Option<&(String, Outcome)> { + self.done.as_ref() + } + + /// Ask for the Revoke of `key` (the first click), or do it (the + /// second): used by the page, and by tests. + pub fn confirm(&self) -> Option<&str> { + self.confirm.as_deref() + } + + /// The web half of the page: "Allow web assistants", the address with + /// Copy, and the steps for Claude and ChatGPT. Unit B3 draws it here; + /// nothing until then (INVARIANT 7). + fn web_section(&mut self, _ui: &mut Ui, _status: &Status) {} + + fn collect(&mut self) { + if let Some((what, rx)) = &self.job + && let Ok(result) = rx.try_recv() + { + if what.starts_with("Revoke") && result.is_ok() { + self.refresh = true; + } + self.done = Some((what.clone(), result)); + self.job = None; + } + } + + fn start( + &mut self, + ui: &Ui, + jobs: &crate::jobs::Spawner, + what: String, + keep: &str, + work: Box Outcome + Send>, + ) { + let (tx, rx) = channel(); + let ctx = ui.ctx().clone(); + let started = jobs.spawn( + &what.clone(), + crate::jobs::Hold::Keep(format!("{keep}: wait for it to finish")), + move |_| { + let _ = tx.send(work()); + ctx.request_repaint(); + }, + ); + if started { + self.job = Some((what, rx)); + self.done = None; + } else { + self.done = Some((what, Err("the system gave no thread for it".into()))); + } + } + + /// The page. `book` is the company's id; `owner` does what is asked. + pub fn show( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + owner: Option>, + jobs: &crate::jobs::Spawner, + ) { + self.collect(); + if self.job.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(250)); + } + // The command lines, found once for this company. + if self.commands.as_ref().is_none_or(|(b, _)| b != book) { + let found = match &owner { + Some(o) => o + .command_line(&["mcp", "--book", book]) + .map(|bridge| Commands { bridge }), + None => Err("this window has no books server to connect to".to_string()), + }; + self.commands = Some((book.to_string(), found)); + } + let commands = self.commands.as_ref().map(|(_, c)| c.clone()); + let p = pal(ui.ctx()); + crate::pages::page(ui, "connect", |ui| { + crate::widgets::page_header( + ui, + "Assistants", + &format!( + "You can read all of {}'s books in this window. To add or change anything, you ask an assistant (an AI program such as Claude Code or Codex) and this window shows what it did.", + status.company + ), + ); + section(ui, "On this computer"); + ui.label( + RichText::new( + "Pick the assistant you use. It gets a key to these books, kept on this computer.", + ) + .font(theme::regular(13.5)) + .color(p.muted), + ); + ui.add_space(8.0); + let busy = self.busy(); + let mut want: Want = None; + for tool in &TOOLS { + if let Some(w) = tool_row(ui, tool, status, book, &owner, &commands, busy) { + want = Some(w); + } + } + if TOOLS.iter().any(|t| t.agent.is_none()) { + key_row(ui, status, book, &owner, busy, &mut want); + } + if let Some((what, keep, work)) = want { + self.start(ui, jobs, what, &keep, work); + } + if self.job.is_some() { + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.spinner(); + ui.label( + RichText::new("Working…") + .font(theme::regular(13.0)) + .color(p.muted), + ); + }); + } else if let Some((what, result)) = &self.done { + ui.add_space(6.0); + match result { + Ok(said) => ui.label( + RichText::new(format!("{what}: {said}")) + .font(theme::regular(13.0)) + .color(p.muted), + ), + Err(why) => ui.label( + RichText::new(format!("{what}: {why}")) + .font(theme::regular(13.0)) + .color(p.warning), + ), + }; + } + self.web_section(ui, status); + ui.add_space(24.0); + self.connections(ui, status, book, &owner, jobs); + }); + } + + /// "Connections": every key to these books, who is connected on it, + /// what it may do, when it last did anything, and Revoke. + fn connections( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + owner: &Option>, + jobs: &crate::jobs::Spawner, + ) { + let p = pal(ui.ctx()); + section(ui, "Who can reach these books"); + let rows = status.connections(); + if rows.is_empty() { + ui.label( + RichText::new(if status.link == Link::Unknown { + "Checking…" + } else { + "No assistant has a key to these books yet. Connect one above." + }) + .font(theme::regular(13.5)) + .color(p.muted), + ); + return; + } + let mut revoke: Option = None; + for row in &rows { + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + connection_row( + ui, + row, + status, + &mut self.confirm, + &mut revoke, + self.job.is_some(), + owner.is_some(), + ); + }); + ui.add_space(6.0); + } + if let (Some(name), Some(owner)) = (revoke, owner.clone()) { + self.confirm = None; + let b = book.to_string(); + self.start( + ui, + jobs, + format!("Revoke {name}"), + "Ending an assistant's access", + Box::new(move || owner.serve_revoke(&b, &name)), + ); + } + } +} + +fn section(ui: &mut Ui, title: &str) { + ui.label(RichText::new(title).font(theme::semibold(17.0))); + ui.add_space(4.0); +} + +type Want = Option<(String, String, Box Outcome + Send>)>; + +/// One tool's row: its name, its button when it has one, and the exact +/// instructions. +fn tool_row( + ui: &mut Ui, + tool: &Tool, + status: &Status, + book: &str, + owner: &Option>, + commands: &Option>, + busy: bool, +) -> Want { + let p = pal(ui.ctx()); + let mut want: Want = None; + let connected = status + .assistants + .iter() + .any(|a| program_name(a) == tool.name); + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new(tool.name).font(theme::semibold(14.5))); + if connected { + ui.label( + RichText::new(format!("{} connected now", icon::PLUGS_CONNECTED)) + .font(theme::regular(12.5)) + .color(p.positive), + ); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if let (Some(agent), Some(owner)) = (tool.agent, owner) + && ui + .add_enabled(!busy, egui::Button::new(format!("Connect {}", tool.name))) + .on_hover_text(format!( + "Makes a key for these books and adds them to {}", + tool.name + )) + .clicked() + { + let (o, b) = (owner.clone(), book.to_string()); + let keep = match agent { + crate::owner::Agent::Claude => "Connecting Claude Code to these books", + crate::owner::Agent::Codex => "Connecting Codex to these books", + }; + want = Some(( + format!("Connect {}", tool.name), + keep.to_string(), + Box::new(move || o.connect(agent, &b).map(|lines| lines.join(" "))), + )); + } + }); + }); + ui.add_space(4.0); + match commands { + Some(Ok(c)) => by_hand(ui, tool, book, &c.bridge), + Some(Err(why)) => { + ui.label( + RichText::new(format!("The command could not be worked out: {why}")) + .font(theme::regular(12.5)) + .color(p.warning), + ); + } + None => {} + } + }); + ui.add_space(6.0); + want +} + +/// The exact text for a tool, copyable. +fn by_hand(ui: &mut Ui, tool: &Tool, book: &str, bridge: &str) { + let p = pal(ui.ctx()); + let name = format!("wanderbooks-{book}"); + match tool.add_by_hand { + Some(add) => { + let line = format!("{add} {name} -- {bridge}"); + egui::CollapsingHeader::new( + RichText::new("Or do it yourself, in a terminal") + .font(theme::regular(12.5)) + .color(p.muted), + ) + .id_salt(("by-hand", tool.name)) + .show(ui, |ui| { + ui.label( + RichText::new("Run this once:") + .font(theme::regular(12.5)) + .color(p.muted), + ); + command_box(ui, &line); + ui.label( + RichText::new(format!( + "Then restart {}. It reaches the books as “{name}”.", + tool.name + )) + .font(theme::regular(12.5)) + .color(p.muted), + ); + }); + } + None => { + ui.label( + RichText::new(format!( + "In {}, add a local tool (a program it runs on this computer) named “{name}”, with this command:", + tool.name + )) + .font(theme::regular(13.0)) + .color(p.text), + ); + command_box(ui, bridge); + ui.label( + RichText::new(format!( + "Then restart {}. If it asks for the program and its arguments separately, the program is the first word and the rest are its arguments. We haven't tested {} yet.", + tool.name, tool.name + )) + .font(theme::regular(12.5)) + .color(p.muted), + ); + } + } +} + +/// The step the tools without a button share: the key they read, made once. +fn key_row( + ui: &mut Ui, + status: &Status, + book: &str, + owner: &Option>, + busy: bool, + want: &mut Want, +) { + let p = pal(ui.ctx()); + ui.add_space(2.0); + ui.label( + RichText::new(format!( + "For the others, make {}'s key first (once):", + status.company + )) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if let Some(owner) = owner + && ui + .add_enabled(!busy, egui::Button::new("Make the key")) + .on_hover_text( + "Makes the key these books give an assistant, and keeps it on this computer", + ) + .clicked() + { + let (o, b) = (owner.clone(), book.to_string()); + *want = Some(( + "Make the key".to_string(), + "Making the key".to_string(), + Box::new(move || { + o.make_key(&b).map(|made| { + if made { + "made, and kept on this computer.".to_string() + } else { + "it was already made.".to_string() + } + }) + }), + )); + } +} + +/// Text in a box, with a Copy button. +fn command_box(ui: &mut Ui, text: &str) { + let p = pal(ui.ctx()); + Frame::new() + .fill(p.bg) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(6)) + .inner_margin(Margin::symmetric(10, 8)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.with_layout(Layout::right_to_left(Align::Min), |ui| { + if ui.button(format!("{} Copy", icon::COPY)).clicked() { + ui.ctx().copy_text(text.to_string()); + } + ui.with_layout(Layout::left_to_right(Align::Min), |ui| { + ui.add( + egui::Label::new( + RichText::new(text).font(egui::FontId::monospace(12.0)), + ) + .wrap() + .selectable(true), + ); + }); + }); + }); + }); +} + +/// One key of these books: its name, what is connected on it, what it may +/// do, and Revoke (asked once). +fn connection_row( + ui: &mut Ui, + row: &Connection<'_>, + status: &Status, + confirm: &mut Option, + revoke: &mut Option, + busy: bool, + can_revoke: bool, +) { + let p = pal(ui.ctx()); + let working = row.sessions.iter().any(|a| a.running > 0); + let link = if row.sessions.is_empty() { + Link::None + } else if working { + Link::Working + } else { + Link::Connected + }; + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + paint_mark(ui, rect.center(), 18.0, link); + ui.vertical(|ui| { + ui.label( + RichText::new(format!("Key “{}”", row.name)).font(theme::semibold(13.5)), + ); + let state = match link { + Link::Working => "Working now", + Link::Connected => "Connected", + _ => "Not connected", + }; + ui.label( + RichText::new(format!("{state}. {}", row.may())) + .font(theme::regular(12.5)) + .color(p.muted), + ); + }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let Some(t) = row.token else { return }; + if !can_revoke { + return; + } + if confirm.as_deref() == Some(t.name.as_str()) { + if ui + .add_enabled(!busy, egui::Button::new("Yes, revoke")) + .clicked() + { + *revoke = Some(t.name.clone()); + } + if ui.button("Keep it").clicked() { + *confirm = None; + } + } else if ui + .add_enabled(!busy, egui::Button::new("Revoke")) + .on_hover_text("Ends this key: the assistant using it is cut off and cannot reach these books again") + .clicked() + { + *confirm = Some(t.name.clone()); + } + }); + }); + if confirm.as_deref() == Some(row.name.as_str()) { + ui.label( + RichText::new(format!( + "Revoke the key “{}”? Anything using it is cut off now; {}'s books are not changed.", + row.name, status.company + )) + .font(theme::regular(12.5)) + .color(p.warning), + ); + } + for a in &row.sessions { + ui.label( + RichText::new(describe(a, status.now)) + .font(theme::regular(12.5)) + .color(p.text), + ); + } +} diff --git a/crates/ledger-gui/src/connections.rs b/crates/ledger-gui/src/connections.rs new file mode 100644 index 00000000..17fd455d --- /dev/null +++ b/crates/ledger-gui/src/connections.rs @@ -0,0 +1,573 @@ +//! Who is connected to each company, and how the window says so (plan P15 +//! 3.3). The word in the window is "assistant". +//! +//! ```text +//! GOAL: a person can see, for each company, at a glance and without +//! reading, whether an assistant is connected to it and whether it is +//! working, and read in words who it is and what it last did; and the +//! window never waits on the books server to say so. +//! SOURCE: plan/p15-app-and-relay.md 3.3 (every tab carries one of three +//! states, as a shape and a word, not colour alone: no assistant +//! connected, connected with its name, working; beside it the last +//! thing done) and 3.1 (the sessions request); D-77, D-78; +//! WB-assist-1, WB-assist-2. +//! INVARIANTS: +//! 1. A company is in exactly one state: `Link::None` (no assistant +//! connected), `Link::Connected`, `Link::Working` (a call of an +//! assistant is running), or `Link::Unknown` when the server has not +//! answered lately (starting, gone, slow, or no server at all). The +//! state is read from the server's own answer, never inferred from +//! anything the window did. +//! 2. Nothing here waits for the server: one request is asked at a time, +//! on a thread of its own, at most every [`POLL`]; the window reads +//! the latest answer. An answer older than [`STALE`] is not believed: +//! the state is `Unknown`, and nothing is drawn as though it were +//! known. A request that never returns holds one idle thread and +//! nothing else; the window never notices. +//! 3. What an assistant said of itself (its name, version, model) is +//! shown as said and never trusted for anything: it is the server's +//! masked copy, and no state, permission or revoke depends on it. +//! 4. Words say what happened and when ("posted an entry, 10 seconds +//! ago"), in the person's terms: a tool's name is turned into what it +//! did, and one this file does not know is said plainly ("ran trial +//! balance"). A failed call is said to have failed. +//! 5. Nothing here holds a token's text: the server never sends one. +//! ``` + +use crate::owner::{Assistant, LastCall, Owner, Roster, TokenRow}; +use chrono::{DateTime, Utc}; +use egui_phosphor::regular as icon; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +/// How often the server is asked who is connected, while it is up. +pub const POLL: Duration = Duration::from_secs(2); + +/// How old an answer may be and still be believed (INVARIANT 2): a few +/// polls, and the time a slow request is allowed. +pub const STALE: Duration = Duration::from_secs(15); + +/// Whether an assistant is connected to a company, and whether it is +/// working (INVARIANT 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Link { + /// The server has not said lately, or there is no server. + Unknown, + /// No assistant is connected. + None, + /// At least one is, and none has a call running. + Connected, + /// At least one has a call running. + Working, +} + +impl Link { + /// The shape that stands for the state: a different silhouette for + /// each, so it reads without colour (plugs apart, plugs together, a + /// spinning arc). + pub fn glyph(self) -> Option<&'static str> { + match self { + Link::Unknown => None, + Link::None => Some(icon::PLUGS), + Link::Connected => Some(icon::PLUGS_CONNECTED), + Link::Working => Some(icon::CIRCLE_NOTCH), + } + } +} + +/// Everything the window shows of one company's assistants. Made by the +/// app each frame from the latest answer (`Connections::status_of`). +#[derive(Clone, Debug, PartialEq)] +pub struct Status { + /// The window runs a books server: without one there is nothing to + /// connect to, and none of this is shown. + pub serves: bool, + /// The server is not coming up: its start failed or it has exited + /// (the notice under the tab bar says why). + pub down: bool, + /// The company's name, as the tab says it. + pub company: String, + /// The state. + pub link: Link, + /// The assistants connected to this company, the longest connected + /// first. + pub assistants: Vec, + /// The tokens of this company: who may connect. + pub tokens: Vec, + /// "Now", for "10 seconds ago" (fixed in tests and screenshots). + pub now: DateTime, +} + +impl Status { + /// A company in a window with no server: nothing to show. + pub fn off(company: &str) -> Self { + Self { + serves: false, + down: false, + company: company.to_string(), + link: Link::Unknown, + assistants: Vec::new(), + tokens: Vec::new(), + now: Utc::now(), + } + } + + /// The state in words, for the person: "No assistant connected", + /// "Claude Code connected", "Claude Code is working". + pub fn word(&self) -> String { + match self.link { + Link::Unknown if self.down => "Assistants can't connect now".to_string(), + Link::Unknown => "Checking for assistants".to_string(), + Link::None => "No assistant connected".to_string(), + Link::Connected => format!("{} connected", names(&self.assistants, false)), + Link::Working => { + let (names, many) = (names(&self.assistants, true), self.working_count() > 1); + format!("{names} {} working", if many { "are" } else { "is" }) + } + } + } + + /// Sessions with a call running. + fn working_count(&self) -> usize { + self.assistants.iter().filter(|a| a.running > 0).count() + } + + /// The last thing any connected assistant did, in words, and when: + /// "posted an entry, 10 seconds ago". None when none has done anything. + pub fn last_thing(&self) -> Option { + self.assistants + .iter() + .filter_map(|a| a.last.as_ref()) + .max_by_key(|l| parse_time(&l.at)) + .map(|l| did(l, self.now)) + } + + /// The second line under the state: the last thing done and when, else + /// what to do about there being no assistant. + pub fn detail(&self) -> String { + match self.link { + Link::Unknown => String::new(), + Link::None => "Connect an assistant".to_string(), + Link::Connected => self + .last_thing() + .map(|l| capitalize(&l)) + .unwrap_or_else(|| "Nothing done yet".to_string()), + Link::Working => self + .last_thing() + .map(|l| format!("Last: {l}")) + .unwrap_or_else(|| "On its first call".to_string()), + } + } + + /// The whole of it as one hover text, for the tab and the slot: the + /// state, then what each connected assistant is. + pub fn hover(&self) -> String { + let mut out = self.word(); + for a in &self.assistants { + out.push_str(&format!("\n{}", describe(a, self.now))); + } + out + } + + /// The tokens' state for the Connect page: each token of this company + /// with the sessions open on it. + pub fn connections(&self) -> Vec> { + let mut rows: Vec> = self + .tokens + .iter() + .map(|t| Connection { + token: Some(t), + name: t.name.clone(), + sessions: self + .assistants + .iter() + .filter(|a| a.token == t.name) + .collect(), + }) + .collect(); + // A session whose token is not in the list (listed a moment apart + // from it): shown, with nothing to revoke. + for a in &self.assistants { + if !self.tokens.iter().any(|t| t.name == a.token) { + match rows + .iter_mut() + .find(|r| r.token.is_none() && r.name == a.token) + { + Some(r) => r.sessions.push(a), + None => rows.push(Connection { + token: None, + name: a.token.clone(), + sessions: vec![a], + }), + } + } + } + rows + } +} + +/// One token of a company with the assistants connected on it (the Connect +/// page's "Connections" list). +#[derive(Debug)] +pub struct Connection<'a> { + /// The token, if the list still has it. + pub token: Option<&'a TokenRow>, + /// Its name. + pub name: String, + /// The sessions open on it. + pub sessions: Vec<&'a Assistant>, +} + +impl Connection<'_> { + /// What the token lets an assistant do, in words. + pub fn may(&self) -> String { + let Some(t) = self.token else { + return String::new(); + }; + let has = |s: &str| t.scopes.iter().any(|x| x == s); + let mut can: Vec<&str> = Vec::new(); + if has("books:read") { + can.push("read the books"); + } + if has("books:write") { + can.push("draft entries"); + } + if has("books:post") { + can.push("post them"); + } + if has("books:admin") { + can.push("read the access record"); + } + match can.as_slice() { + [] => "Can do nothing".to_string(), + [one] => format!("Can {one}"), + [init @ .., last] => format!("Can {} and {last}", init.join(", ")), + } + } +} + +/// An assistant's program, by the name it gave: a friendly name for the +/// ones this window knows, else what it said, else "An assistant" +/// (INVARIANT 3). +pub fn program_name(a: &Assistant) -> String { + let said = a.client_name.as_deref().unwrap_or("").trim(); + let low = said.to_lowercase(); + let known = [ + ("claude-code", "Claude Code"), + ("claude code", "Claude Code"), + ("codex", "Codex"), + ("gemini", "Gemini CLI"), + ("grok", "Grok Build"), + ("muse", "Muse Code"), + ("cursor", "Cursor"), + ("chatgpt", "ChatGPT"), + ("openai", "ChatGPT"), + ("claude", "Claude"), + ]; + if let Some((_, name)) = known.iter().find(|(k, _)| low.contains(k)) { + return (*name).to_string(); + } + if said.is_empty() { + "An assistant".to_string() + } else { + said.to_string() + } +} + +/// The names of the assistants (those working only, if `working`), each +/// once, with a count where one program has several sessions: "Claude +/// Code", "Claude Code and Codex", "Claude Code ×2", "3 assistants". +fn names(list: &[Assistant], working: bool) -> String { + let mut seen: Vec<(String, usize)> = Vec::new(); + for a in list.iter().filter(|a| !working || a.running > 0) { + let n = program_name(a); + match seen.iter_mut().find(|(s, _)| *s == n) { + Some((_, c)) => *c += 1, + None => seen.push((n, 1)), + } + } + match seen.as_slice() { + [] => "An assistant".to_string(), + [(n, 1)] => n.clone(), + [(n, c)] => format!("{n} ×{c}"), + [(a, 1), (b, 1)] => format!("{a} and {b}"), + many => { + let total = many.iter().fold(0usize, |t, (_, c)| t.saturating_add(*c)); + format!("{total} assistants") + } + } +} + +/// One assistant in a line: "Claude Code 2.1 (token "agent"), connected 3 +/// minutes ago, working". +pub fn describe(a: &Assistant, now: DateTime) -> String { + let mut out = program_name(a); + if let Some(v) = a.client_version.as_deref().filter(|v| !v.is_empty()) { + out.push(' '); + out.push_str(v); + } + if let Some(m) = a.model.as_deref().filter(|m| !m.is_empty()) { + out.push_str(&format!(" ({m})")); + } + out.push_str(&format!( + ", connected {}", + ago(parse_time(&a.connected_at), now) + )); + if a.running > 0 { + out.push_str(", working"); + } + if let Some(l) = &a.last { + out.push_str(&format!(", last {}", did(l, now))); + } + out +} + +/// A finished call as a person would say it, and when: "posted an entry, +/// 10 seconds ago" (INVARIANT 4). +pub fn did(l: &LastCall, now: DateTime) -> String { + let t = l.tool.strip_prefix("books.").unwrap_or(&l.tool); + let what = match t { + "post_entry" => "posted an entry".to_string(), + "draft_entry" => "drafted an entry".to_string(), + "add_line" => "added a line to a draft".to_string(), + "reverse_entry" => "reversed an entry".to_string(), + "start" => "began a session".to_string(), + "handbook" => "read the handbook".to_string(), + "digest" => "read the digest".to_string(), + other if other.contains("://") || other.starts_with('/') => format!("read {other}"), + other => format!("ran {}", other.replace(['_', '.'], " ")), + }; + let how = match l.outcome.as_str() { + "ok" => String::new(), + "error" => ", and it failed".to_string(), + refused => format!( + ", and it was refused ({})", + refused.strip_prefix("refused: ").unwrap_or(refused) + ), + }; + format!("{what}{how}, {}", ago(parse_time(&l.at), now)) +} + +fn parse_time(at: &str) -> Option> { + DateTime::parse_from_rfc3339(at) + .ok() + .map(|t| t.with_timezone(&Utc)) +} + +/// "just now", "10 seconds ago", "3 minutes ago", "2 hours ago", "5 days +/// ago"; "a while ago" for a time that could not be read. +pub fn ago(then: Option>, now: DateTime) -> String { + let Some(then) = then else { + return "a while ago".to_string(); + }; + let s = (now - then).num_seconds().max(0); + let unit = |n: i64, one: &str| { + if n == 1 { + format!("1 {one} ago") + } else { + format!("{n} {one}s ago") + } + }; + match s { + 0..=4 => "just now".to_string(), + 5..=59 => unit(s, "second"), + 60..=3599 => unit(s / 60, "minute"), + 3600..=86399 => unit(s / 3600, "hour"), + _ => unit(s / 86400, "day"), + } +} + +fn capitalize(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + +// ---- asking the server ---------------------------------------------------- + +struct Shared { + /// A request is out. + in_flight: bool, + /// When the last one was begun. + last_begun: Option, + /// The latest answer and when it came. + answer: Option<(Instant, Result)>, +} + +/// The latest answer of the server's sessions request (INVARIANT 2). +pub struct Connections { + shared: Arc>, +} + +impl Default for Connections { + fn default() -> Self { + Self::new() + } +} + +fn lock(m: &Mutex) -> MutexGuard<'_, Shared> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Clears "a request is out" however the request ends, a panic included. +struct Done(Arc>); + +impl Drop for Done { + fn drop(&mut self) { + lock(&self.0).in_flight = false; + } +} + +impl Connections { + /// Nothing asked yet. + pub fn new() -> Self { + Self { + shared: Arc::new(Mutex::new(Shared { + in_flight: false, + last_begun: None, + answer: None, + })), + } + } + + /// Ask the server who is connected, if it is time and no request is + /// out (INVARIANT 2); `force` asks as soon as none is out. Returns at + /// once; the answer is read with [`Connections::roster`]. + pub fn poll(&self, ctx: &egui::Context, owner: &Arc, force: bool) { + { + let mut s = lock(&self.shared); + let due = s.last_begun.is_none_or(|t| t.elapsed() >= POLL); + if s.in_flight || !(due || force) { + ctx.request_repaint_after(POLL); + return; + } + s.in_flight = true; + s.last_begun = Some(Instant::now()); + } + let (shared, owner, ctx2) = (self.shared.clone(), owner.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("connections".into()) + .spawn(move || { + let _done = Done(shared.clone()); + let answer = owner.serve_roster(); + lock(&shared).answer = Some((Instant::now(), answer)); + ctx2.request_repaint(); + }); + if spawned.is_err() { + lock(&self.shared).in_flight = false; + } + ctx.request_repaint_after(POLL); + } + + /// The latest answer, if it is one the server gave and is not stale + /// (INVARIANT 2). + pub fn roster(&self) -> Option { + self.roster_within(STALE) + } + + /// The latest answer the server gave, if it is no older than `age`: the + /// close warning goes by a longer memory than the state does, so a + /// server that is slow for a moment does not make an assistant that was + /// connected seem gone. + pub fn roster_within(&self, age: Duration) -> Option { + match &lock(&self.shared).answer { + Some((at, Ok(roster))) if at.elapsed() <= age => Some(roster.clone()), + _ => None, + } + } + + /// Why the last request failed, if it did and no later one has + /// succeeded (for a notice; not for the state). + pub fn trouble(&self) -> Option { + match &lock(&self.shared).answer { + Some((_, Err(why))) => Some(why.clone()), + _ => None, + } + } + + /// Whether a request is out now. + pub fn is_asking(&self) -> bool { + lock(&self.shared).in_flight + } + + /// Forget the answer: the next frame asks again (after a token is + /// ended, the state is not the one that was read before). + pub fn forget(&self) { + let mut s = lock(&self.shared); + s.answer = None; + s.last_begun = None; + } + + /// Wait until no request is out, for at most `within`: true when none + /// is (tests). + pub fn wait_idle(&self, within: Duration) -> bool { + let until = Instant::now() + within; + while Instant::now() < until { + if !self.is_asking() { + return true; + } + std::thread::sleep(Duration::from_millis(5)); + } + !self.is_asking() + } + + /// What is shown of the company with books `book`, named `company`, + /// from the latest answer; `serves` is whether the window runs a + /// server at all. + pub fn status_of( + &self, + serves: bool, + down: bool, + book: Option<&str>, + company: &str, + now: DateTime, + ) -> Status { + self.status_within(STALE, serves, down, book, company, now) + } + + /// [`Connections::status_of`], believing an answer no older than `age`. + pub fn status_within( + &self, + age: Duration, + serves: bool, + down: bool, + book: Option<&str>, + company: &str, + now: DateTime, + ) -> Status { + let mut status = Status::off(company); + status.now = now; + status.serves = serves && book.is_some(); + status.down = down; + let (true, Some(book)) = (status.serves, book) else { + return status; + }; + let Some(roster) = (if down { None } else { self.roster_within(age) }) else { + return status; + }; + status.assistants = roster + .assistants + .into_iter() + .filter(|a| a.book == book) + .collect(); + // The longest connected first (RFC 3339 times order as text). + status + .assistants + .sort_by(|a, b| a.connected_at.cmp(&b.connected_at)); + status.tokens = roster + .tokens + .into_iter() + .filter(|t| t.book == book) + .collect(); + status.link = if status.assistants.is_empty() { + Link::None + } else if status.assistants.iter().any(|a| a.running > 0) { + Link::Working + } else { + Link::Connected + }; + status + } +} diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 75d17ce0..80290487 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -8,6 +8,8 @@ pub mod attention; pub mod books; pub mod charts; pub mod company; +pub mod connect; +pub mod connections; pub mod data; pub mod demo; pub mod dock; diff --git a/crates/ledger-gui/src/nav.rs b/crates/ledger-gui/src/nav.rs index 60f99a64..d66c99cc 100644 --- a/crates/ledger-gui/src/nav.rs +++ b/crates/ledger-gui/src/nav.rs @@ -85,6 +85,9 @@ pub enum Route { Documents, Document(u64), Company, + /// The company's assistants: who is connected, and how to connect one + /// (connect.rs). Drawn by the company's view, which holds its state. + Connect, Journal, JournalEvent(u64), } @@ -106,7 +109,7 @@ impl Route { Section::Invoices } Route::Documents | Route::Document(_) => Section::Documents, - Route::Company => Section::Company, + Route::Company | Route::Connect => Section::Company, Route::Journal | Route::JournalEvent(_) => Section::Journal, } } diff --git a/crates/ledger-gui/src/pages/accounts.rs b/crates/ledger-gui/src/pages/accounts.rs index 283e45df..fd7eced9 100644 --- a/crates/ledger-gui/src/pages/accounts.rs +++ b/crates/ledger-gui/src/pages/accounts.rs @@ -56,10 +56,11 @@ impl RegisterRange { pub fn show_chart(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "accounts", |ui| { - widgets::page_header( + widgets::page_header_ask( ui, "Accounts", "Every account in the chart with today's balance. Click one for its register.", + "add an account to the chart", ); ui.checkbox( &mut shell.state.accounts.show_empty, diff --git a/crates/ledger-gui/src/pages/assets.rs b/crates/ledger-gui/src/pages/assets.rs index 2b541f1b..a6c9922e 100644 --- a/crates/ledger-gui/src/pages/assets.rs +++ b/crates/ledger-gui/src/pages/assets.rs @@ -499,10 +499,11 @@ fn date_controls(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) -> NaiveDate { pub fn show_register(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "assets", |ui| { - widgets::page_header( + widgets::page_header_ask( ui, "Fixed assets", "Everything the company owns as a fixed asset: its label, what it cost, how much has been depreciated, and what it's worth on the books, reconciled to the general ledger.", + "add a fixed asset", ); if b.ledger.registered_assets().next().is_none() { widgets::card(ui, |ui| { diff --git a/crates/ledger-gui/src/pages/company.rs b/crates/ledger-gui/src/pages/company.rs index 28054e6b..a0ae88ca 100644 --- a/crates/ledger-gui/src/pages/company.rs +++ b/crates/ledger-gui/src/pages/company.rs @@ -158,10 +158,11 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { let mut kept_go: Option = None; page(ui, "company", |ui| { let c = &b.settings.company; - widgets::page_header( + widgets::page_header_ask( ui, &c.name, "The company's profile and the standing parts of its books.", + "change a company setting", ); columns(ui, 980.0, &[1.0, 1.0], |i, ui| match i { 0 => { diff --git a/crates/ledger-gui/src/pages/documents.rs b/crates/ledger-gui/src/pages/documents.rs index 2b2498d9..4ad5558b 100644 --- a/crates/ledger-gui/src/pages/documents.rs +++ b/crates/ledger-gui/src/pages/documents.rs @@ -46,13 +46,14 @@ fn grid(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { .iter() .filter(|a| a.withdrawn_at.is_none()) .count(); - widgets::page_header( + widgets::page_header_ask( ui, "Documents", &format!( "{} on file: receipts that prove entries, and the company's records. Bytes are content-addressed and verified on every read.", fmt::count(current, "document", "documents") ), + "attach a receipt or document", ); let mut cats: Vec = b.attachments.iter().map(|a| a.category.clone()).collect(); cats.sort(); diff --git a/crates/ledger-gui/src/pages/invoices.rs b/crates/ledger-gui/src/pages/invoices.rs index 2ccf9316..e1a29219 100644 --- a/crates/ledger-gui/src/pages/invoices.rs +++ b/crates/ledger-gui/src/pages/invoices.rs @@ -238,10 +238,15 @@ fn status_text(st: &DocState, date: NaiveDate, today: NaiveDate) -> String { pub fn show_list(ui: &mut Ui, b: &Books, bills: bool, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "invoices", |ui| { - widgets::page_header( + widgets::page_header_ask( ui, "Invoices & Bills", "What customers owe the company and what it owes vendors, each figure read from the ledger, tied to its account. The bookkeeper issues, records and voids them.", + if bills { + "enter a new bill" + } else { + "create a new invoice" + }, ); let mut side = bills; if widgets::segmented( diff --git a/crates/ledger-gui/src/pages/mod.rs b/crates/ledger-gui/src/pages/mod.rs index 52905e25..18aa81aa 100644 --- a/crates/ledger-gui/src/pages/mod.rs +++ b/crates/ledger-gui/src/pages/mod.rs @@ -72,6 +72,9 @@ pub fn show(ui: &mut Ui, b: &Books, route: &Route, shell: &mut Shell<'_>) { Route::Documents => documents::show(ui, b, None, shell), Route::Document(id) => documents::show(ui, b, Some(*id), shell), Route::Company => company::show(ui, b, shell), + // Drawn by the company's view, which holds the page's state + // (connect.rs). + Route::Connect => {} Route::Journal => journal::show(ui, b, None, shell), Route::JournalEvent(seq) => journal::show(ui, b, Some(*seq), shell), } diff --git a/crates/ledger-gui/src/pages/parties.rs b/crates/ledger-gui/src/pages/parties.rs index 7b012c11..4dde7cb8 100644 --- a/crates/ledger-gui/src/pages/parties.rs +++ b/crates/ledger-gui/src/pages/parties.rs @@ -330,10 +330,11 @@ pub(crate) fn chip(ui: &mut Ui, text: &str, on: bool) -> bool { pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "parties", |ui| { - widgets::page_header( + widgets::page_header_ask( ui, "Parties", "Everyone the company deals with — vendors, contractors, customers, platforms, agencies — and what the company paid each and received from each. Click one for everything the books hold about them.", + "add a customer or vendor", ); if b.ledger.parties().next().is_none() { widgets::card(ui, |ui| { diff --git a/crates/ledger-gui/src/pages/projects.rs b/crates/ledger-gui/src/pages/projects.rs index 84dad086..0978017d 100644 --- a/crates/ledger-gui/src/pages/projects.rs +++ b/crates/ledger-gui/src/pages/projects.rs @@ -122,7 +122,7 @@ pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "projects", |ui| { let all = listed(b); - widgets::page_header(ui, "Projects", &summary(&all)); + widgets::page_header_ask(ui, "Projects", &summary(&all), "add a project"); if all.is_empty() { widgets::card(ui, |ui| { widgets::empty( diff --git a/crates/ledger-gui/src/pages/transactions.rs b/crates/ledger-gui/src/pages/transactions.rs index 5108b7f6..2c495159 100644 --- a/crates/ledger-gui/src/pages/transactions.rs +++ b/crates/ledger-gui/src/pages/transactions.rs @@ -64,13 +64,14 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { let p = pal(ui.ctx()); page(ui, "transactions", |ui| { let total = b.entries.len(); - widgets::page_header( + widgets::page_header_ask( ui, "Transactions", &format!( "{} recorded, newest first. Click one to see its lines, its receipt, and its history.", fmt::count(total, "entry", "entries") ), + "record a new transaction", ); let st = &mut shell.state.transactions; let narrow = ui.available_width() < 720.0; diff --git a/crates/ledger-gui/src/palette.rs b/crates/ledger-gui/src/palette.rs index e6ee07f3..c5e74601 100644 --- a/crates/ledger-gui/src/palette.rs +++ b/crates/ledger-gui/src/palette.rs @@ -557,6 +557,7 @@ pub fn describe(b: &Books, r: &Route) -> String { Route::Project(id) => b.project_label(*id), Route::Reconciliation(id) => b.subject_label(ledger_store::Subject::Reconciliation(*id)), Route::JournalEvent(seq) => format!("Event {seq}"), + Route::Connect => "Assistants".to_string(), _ => String::new(), } } diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs index c3ae7350..bdac225f 100644 --- a/crates/ledger-gui/src/serving.rs +++ b/crates/ledger-gui/src/serving.rs @@ -256,6 +256,26 @@ impl Serving { .is_some_and(|i| *lock(&i.gate) == Gate::Starting) } + /// Whether the server has exited on its own (cheap: asked every frame). + pub fn has_exited(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| i.owner.serve_exited().is_some()) + } + + /// The owner that hosts the server, to ask it who is connected (A4). + pub fn owner(&self) -> Option> { + self.inner.as_ref().map(|i| i.owner.clone()) + } + + /// Whether the server is up and not closing: it can be asked who is + /// connected (A4). + pub fn is_up(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| *lock(&i.gate) == Gate::Up && *lock(&i.closing) == Closing::Not) + } + /// Whether the start failed and a `retry` would try again. pub fn is_down(&self) -> bool { self.inner diff --git a/crates/ledger-gui/src/tabs.rs b/crates/ledger-gui/src/tabs.rs index 1f56dbae..c4b25e3a 100644 --- a/crates/ledger-gui/src/tabs.rs +++ b/crates/ledger-gui/src/tabs.rs @@ -43,7 +43,9 @@ //! cut, whole in its hover text), then the strip scrolls, with a //! step control at each end; the tab shown is scrolled into view //! when it changes. Each tab leaves room left of its close control -//! for a state mark (drawn by a later unit, nothing now). +//! for the assistant state mark (`Tab::link`, connect.rs: plugs +//! apart, plugs together, a turning arc, so it reads without colour; +//! its words are in the tab's hover). //! 6. This only says what was asked (show, close, open); the app does //! it. //! 7. A tab whose company has a job under way that changes its books @@ -70,8 +72,8 @@ const CLOSE: f32 = 20.0; /// The badge's size, and its gap to the name. const BADGE: f32 = 18.0; const GAP: f32 = 8.0; -/// Room left of the close control for the connection state, which a later -/// unit draws there. +/// Room left of the close control for the connection state mark +/// (`Tab::link`). const STATE_W: f32 = 14.0; /// The room round a tab's content: left and right. const PAD_L: f32 = 10.0; @@ -100,6 +102,10 @@ pub struct Tab { /// running ("Restoring these books: wait for it to finish"). Its close /// control is off, and says so on hover. pub held: Option, + /// Whether an assistant is connected to the company, and whether it + /// is working: drawn as a shape left of the close control, with its + /// words in the tab's hover (nothing for `Link::Unknown`). + pub link: crate::connections::Link, } /// The badge hue of the company whose books have id `book_id`, light or @@ -517,6 +523,12 @@ fn one_tab( galley, p.text, ); + crate::connect::paint_mark( + ui, + egui::pos2(close_rect.left() - STATE_W / 2.0 - 2.0, rect.center().y), + 14.0, + tab.link, + ); if close.hovered() && tab.held.is_none() { painter.rect_filled(close_rect, CornerRadius::same(5), p.selected); } diff --git a/crates/ledger-gui/src/widgets.rs b/crates/ledger-gui/src/widgets.rs index 21bd1804..b2833537 100644 --- a/crates/ledger-gui/src/widgets.rs +++ b/crates/ledger-gui/src/widgets.rs @@ -61,6 +61,47 @@ pub fn page_header(ui: &mut Ui, title: &str, subtitle: &str) { ui.add_space(16.0); } +/// [`page_header`] with "Ask your assistant" at the right of the title, +/// where a button that changes the books would be: it copies a sentence +/// about `what` (a phrase that finishes "please ...": "create a new +/// invoice") to paste into the assistant (connect.rs INVARIANT 3). In a +/// window that runs no books server it is [`page_header`]. +pub fn page_header_ask(ui: &mut Ui, title: &str, subtitle: &str, what: &str) { + if !crate::connect::asking_is_offered(ui.ctx()) { + return page_header(ui, title, subtitle); + } + let narrow = ui.available_width() < 560.0; + if narrow { + ui.label(RichText::new(title).font(theme::bold(26.0))); + ui.add_space(4.0); + crate::connect::ask_button(ui, what); + crate::connect::ask_feedback(ui); + ui.add_space(4.0); + } else { + ui.horizontal(|ui| { + ui.label(RichText::new(title).font(theme::bold(26.0))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + crate::connect::ask_button(ui, what); + }); + }); + crate::connect::ask_feedback(ui); + } + let p = pal(ui.ctx()); + if !subtitle.is_empty() { + ui.add_space(2.0); + let w = ui.available_width().min(860.0); + ui.allocate_ui(vec2(w, 0.0), |ui| { + ui.set_max_width(w); + ui.label( + RichText::new(subtitle) + .font(theme::regular(15.0)) + .color(p.muted), + ); + }); + } + ui.add_space(16.0); +} + /// A page that opens with a sentence instead of a title (the Overview: /// the company's name is the tab's, and the status card's, not the /// page's): the sentence at the theme's heading size and weight, the diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs new file mode 100644 index 00000000..402da3a7 --- /dev/null +++ b/crates/ledger-gui/tests/assistants.rs @@ -0,0 +1,1020 @@ +//! The window and the assistants connected to its companies (connections.rs, +//! connect.rs, app.rs; plan/p15-app-and-relay.md 3.3; WB-assist-1 to +//! WB-assist-4): the three states, "Ask your assistant", the Connect page, +//! and the warning before a close. +//! +//! ```text +//! GOAL: a person sees, for each company, whether an assistant is connected +//! and whether it is working, can connect or end one from a page, +//! asks for changes through an assistant, and is warned before +//! closing what an assistant is using; and none of it ever waits on +//! the books server. +//! SOURCE: plan/p15-app-and-relay.md 3.3 (three states, "Ask your +//! assistant", the Connect page), D-79 (closing with assistants +//! connected warns, then closes), 3.1 (the sessions request); +//! WB-assist-1, WB-assist-2, WB-assist-3, WB-assist-4. +//! INVARIANTS: +//! 1. Each state, from the server's own answer: none, connected (with the +//! program's name), working (a call running); the last thing done in +//! words; a company's state is its own. +//! 2. A server that is slow, gone or silent is "not known", never +//! guessed, and no frame waits for it: one request is out at a time. +//! 3. "Ask your assistant" copies one ready sentence naming the company, +//! says where to connect one when none is, and is not there when the +//! window runs no server. +//! 4. The Connect page lists the keys with who is on each, what each may +//! do, shows the exact command for a tool, and revokes a key only +//! after asking once, through the owner. +//! 5. Closing the window or a tab warns when an assistant is connected +//! and only then; it closes when the person says so, composing with +//! "Closing your books"; one dialog at a time; a server that does not +//! answer does not hold a close. +//! 6. The state mark of a tab, the top bar's state and the pages look as +//! they were blessed (`tests/snapshots/assist_*.shapes`, +//! `TABS_BLESS=1`). +//! ``` + +use chrono::{DateTime, Utc}; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use ledger_core::{AccountType, Currency}; +use ledger_gui::connections::Link; +use ledger_gui::data::Source; +use ledger_gui::nav::Route; +use ledger_gui::owner::{Agent, Assistant, LastCall, Owner, RestorePlan, Roster, TokenRow}; +use ledger_gui::{App, Start}; +use ledger_store::root::{BookId, Root}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +fn now() -> DateTime { + "2026-11-21T10:30:00Z".parse().unwrap() +} + +/// A data root of its own, with companies made in it. +struct World { + _dir: tempfile::TempDir, + root: PathBuf, +} + +impl World { + fn new(companies: &[(&str, &str)]) -> World { + let dir = tempfile::Builder::new() + .prefix("wb-gui-assist-") + .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 hosts a server and answers who is connected as it is told. +#[derive(Default)] +struct Fake { + log: Mutex>, + roster: Mutex>>, + /// While closed, the roster request does not return. + gate: Mutex, + gate_changed: Condvar, + asked: Mutex, + exited: Mutex>, + stop_takes: Mutex, +} + +impl Fake { + fn new() -> Arc { + let f = Fake::default(); + *f.gate.lock().unwrap() = true; + Arc::new(f) + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } + + fn note(&self, s: String) { + self.log.lock().unwrap().push(s); + } + + fn answer(&self, r: Result) { + *self.roster.lock().unwrap() = Some(r); + } + + fn close_gate(&self) { + *self.gate.lock().unwrap() = false; + } + + fn open_gate(&self) { + *self.gate.lock().unwrap() = true; + self.gate_changed.notify_all(); + } +} + +impl Owner for Fake { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, open: &[String]) -> Result<(), String> { + self.note(format!("start {}", open.join(","))); + Ok(()) + } + fn serve_open(&self, book: &str) -> Result, String> { + self.note(format!("open {book}")); + Ok(None) + } + fn serve_close(&self, book: &str) -> Result, String> { + self.note(format!("close {book}")); + Ok(None) + } + fn serve_stop(&self) -> Result, String> { + self.note("stop".into()); + std::thread::sleep(*self.stop_takes.lock().unwrap()); + Ok(None) + } + fn serve_exited(&self) -> Option { + self.exited.lock().unwrap().clone() + } + fn serve_roster(&self) -> Result { + *self.asked.lock().unwrap() += 1; + let mut open = self.gate.lock().unwrap(); + let end = Instant::now() + Duration::from_secs(60); + while !*open { + let left = end.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("the books server isn't answering".into()); + } + open = self.gate_changed.wait_timeout(open, left).unwrap().0; + } + drop(open); + self.roster + .lock() + .unwrap() + .clone() + .unwrap_or_else(|| Ok(Roster::default())) + } + fn serve_revoke(&self, book: &str, name: &str) -> Result { + self.note(format!("revoke {book} {name}")); + if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() { + r.tokens.retain(|t| !(t.book == book && t.name == name)); + r.assistants + .retain(|a| !(a.book == book && a.token == name)); + } + Ok(format!("Ended {name:?}'s access to {book}.")) + } + fn command_line(&self, words: &[&str]) -> Result { + Ok(format!("/opt/wanderbooks {}", words.join(" "))) + } + fn make_key(&self, book: &str) -> Result { + self.note(format!("key {book}")); + Ok(true) + } + fn connect(&self, agent: Agent, book: &str) -> Result, String> { + self.note(format!("connect {} {book}", agent.key())); + Ok(vec![format!("{} reaches the books.", agent.label())]) + } + fn close_books(&self) -> Result { + Err("not here".into()) + } + fn new_books(&self, _: &str, _: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + Err("not here".into()) + } + fn restore(&self, _: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _: &str, _: &str) -> Result, String> { + Err("not here".into()) + } +} + +fn session(book: &str, token: &str, program: &str, running: u32, last: Option<&str>) -> Assistant { + Assistant { + book: book.into(), + token: token.into(), + client_name: Some(program.into()), + client_version: Some("2.1".into()), + model: None, + connected_at: "2026-11-21T10:00:00Z".into(), + running, + last: last.map(|tool| LastCall { + tool: tool.into(), + outcome: "ok".into(), + at: "2026-11-21T10:29:50Z".into(), + }), + } +} + +fn token(book: &str, name: &str) -> TokenRow { + TokenRow { + book: book.into(), + name: name.into(), + scopes: ["books:read", "books:write", "books:post"] + .map(String::from) + .to_vec(), + created: "2026-11-01T09:00:00Z".into(), + } +} + +fn roster(assistants: Vec, tokens: Vec) -> Result { + Ok(Roster { assistants, tokens }) +} + +/// The app over `ids` as tabs (the first in front), served by `owner`. +fn start(w: &World, ids: &[&str], owner: &Arc) -> Harness<'static, App> { + let kept: HashMap = + HashMap::from([(ledger_gui::app::open_key(&w.root), ids.join(","))]); + let (root, fallback) = (w.root.clone(), w.source(ids[0])); + let for_app: Arc = owner.clone(); + // Tall, so the whole Connect page is on screen to be clicked. + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 1700.0)) + .build_eframe(move |cc| { + let mut app = App::start_with_owner( + &cc.egui_ctx, + &|k| kept.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ); + app.set_now(now()); + app + }); + let o: Arc = owner.clone(); + for i in 0..ids.len() { + h.state_mut().view_mut(i).unwrap().set_owner(o.clone()); + } + 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)); + } +} + +/// Read the server's answer again: forget the last, ask, wait, draw. +fn refresh(h: &mut Harness<'static, App>) { + h.state().connections().forget(); + h.run_steps(2); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(3); +} + +fn links(h: &Harness<'_, App>) -> Vec { + h.state().views().iter().map(|v| v.assist().link).collect() +} + +fn ask_to_close(h: &mut Harness<'static, App>) { + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(3); +} + +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() +} + +fn wait_for(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)); + } +} + +// ---- 1: the three states ---------------------------------------------------- + +#[test] +fn each_state_is_read_from_the_servers_answer_and_is_the_companys_own() { + let w = World::new(&[("alpha", "Wanderland Labs"), ("beta", "Fernhill Studio")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![])); + let mut h = start(&w, &["alpha", "beta"], &owner); + refresh(&mut h); + // No assistant: said in words, and what to do. + assert_eq!(links(&h), [Link::None, Link::None]); + let a = h.state().views()[0].assist().clone(); + assert_eq!(a.word(), "No assistant connected"); + assert_eq!(a.detail(), "Connect an assistant"); + assert!(h.query_by_label("No assistant connected").is_some()); + + // One connected to alpha, idle: its name, and the last thing done. + owner.answer(roster( + vec![session( + "alpha", + "agent", + "claude-code", + 0, + Some("books.post_entry"), + )], + vec![token("alpha", "agent")], + )); + refresh(&mut h); + assert_eq!(links(&h), [Link::Connected, Link::None], "beta is its own"); + let a = h.state().views()[0].assist().clone(); + assert_eq!(a.word(), "Claude Code connected"); + assert_eq!(a.detail(), "Posted an entry, 10 seconds ago"); + assert!(h.query_by_label("Claude Code connected").is_some()); + + // A call running: working. + owner.answer(roster( + vec![session( + "alpha", + "agent", + "claude-code", + 1, + Some("books.post_entry"), + )], + vec![token("alpha", "agent")], + )); + refresh(&mut h); + assert_eq!(links(&h)[0], Link::Working); + let a = h.state().views()[0].assist().clone(); + assert_eq!(a.word(), "Claude Code is working"); + assert_eq!(a.detail(), "Last: posted an entry, 10 seconds ago"); + + // Two programs on one company. + owner.answer(roster( + vec![ + session("alpha", "agent", "claude-code", 0, None), + session("alpha", "codex", "codex-mcp-client", 0, None), + ], + vec![], + )); + refresh(&mut h); + assert_eq!( + h.state().views()[0].assist().word(), + "Claude Code and Codex connected" + ); + drop(h); +} + +// ---- 2: slow, gone, silent ------------------------------------------------- + +#[test] +fn a_slow_server_is_never_waited_for_and_one_request_is_out_at_a_time() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.close_gate(); + owner.answer(roster( + vec![session("alpha", "agent", "claude-code", 0, None)], + vec![], + )); + let began = Instant::now(); + let mut h = start(&w, &["alpha"], &owner); + let frames = Instant::now(); + h.run_steps(30); + assert!( + frames.elapsed() < Duration::from_secs(10), + "frames did not wait for the server: {:?}", + frames.elapsed() + ); + let _ = began; + // Not known, said so and not guessed; one request, still out. + assert_eq!(links(&h), [Link::Unknown]); + assert!(h.state().connections().is_asking()); + wait_for("the request began", || *owner.asked.lock().unwrap() >= 1); + assert_eq!( + *owner.asked.lock().unwrap(), + 1, + "never a second one beside it" + ); + // Answered at last: known. + owner.open_gate(); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(3); + assert_eq!(links(&h), [Link::Connected]); + drop(h); +} + +#[test] +fn a_server_that_is_gone_or_refuses_is_not_known_and_the_window_goes_on() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(Err("the books server didn't answer (BrokenPipe)".into())); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + assert_eq!(links(&h), [Link::Unknown]); + assert!(h.state().connections().trouble().is_some()); + // The server exits on its own: said as down, still drawing. + *owner.exited.lock().unwrap() = Some("The books server stopped".into()); + h.run_steps(4); + assert!(h.state().views()[0].assist().down); + assert!( + h.query_by_label_contains("Assistants can't connect now") + .is_some() + ); + // The company's own pages still draw. + h.state_mut().goto(Route::Transactions); + h.run_steps(3); + assert_eq!(h.state().route(), &Route::Transactions); + assert!( + h.query_all_by_label_contains("Transactions") + .next() + .is_some() + ); + drop(h); +} + +// ---- 3: Ask your assistant --------------------------------------------------- + +#[test] +fn ask_your_assistant_copies_one_ready_sentence() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![])); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + h.state_mut().goto(Route::Transactions); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Ask your assistant") + .click(); + h.step(); + assert_eq!( + copied(&h), + ["In my Wanderbooks books for Wanderland Labs, please record a new transaction."] + ); + h.run_steps(2); + // With none connected it says so, and where to connect one. + assert!( + h.query_by_label_contains("No assistant is connected yet.") + .is_some() + ); + h.get_by_label("Connect an assistant").click(); + h.run_steps(3); + assert_eq!(h.state().route(), &Route::Connect); + + // With one connected, only what was copied. + owner.answer(roster( + vec![session("alpha", "agent", "claude-code", 0, None)], + vec![], + )); + refresh(&mut h); + h.state_mut().goto(Route::Receivables); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Ask your assistant") + .click(); + h.step(); + assert_eq!( + copied(&h), + ["In my Wanderbooks books for Wanderland Labs, please create a new invoice."] + ); + h.run_steps(2); + assert!( + h.query_by_label_contains("No assistant is connected yet.") + .is_none() + ); + drop(h); +} + +#[test] +fn a_window_with_no_server_offers_no_assistant() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let source = w.source("alpha"); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .build_eframe(move |cc| { + App::with_books( + &cc.egui_ctx, + ledger_gui::data::load_once(&source).unwrap(), + false, + Route::Transactions, + ) + }); + h.run_steps(4); + assert!(h.query_by_label("Ask your assistant").is_none()); + assert!(h.query_by_label("No assistant connected").is_none()); +} + +// ---- 4: the Connect page --------------------------------------------------- + +#[test] +fn the_top_bar_state_opens_the_connect_page_which_lists_and_revokes() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster( + vec![session( + "alpha", + "agent", + "claude-code", + 0, + Some("books.draft_entry"), + )], + vec![token("alpha", "agent"), token("alpha", "web")], + )); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + h.get_by_label("Claude Code connected").click(); + h.run_steps(3); + assert_eq!(h.state().route(), &Route::Connect); + // A row per tool, and the keys with who is on each. + for tool in [ + "Claude Code", + "Codex", + "Gemini CLI", + "Grok Build", + "Muse Code", + "Cursor", + ] { + assert!( + h.query_all_by_label(tool).next().is_some(), + "a row for {tool}" + ); + } + assert!(h.query_by_label_contains("Key “agent”").is_some()); + assert!(h.query_by_label_contains("Key “web”").is_some()); + assert!( + h.query_by_label_contains("Claude Code 2.1, connected 30 minutes ago") + .is_some(), + "the assistant's name and version, and when it connected" + ); + assert!( + h.query_by_label_contains("Not connected. Can read the books, draft entries and post them") + .is_some() + ); + // The exact command for a tool with no button of its own, and for + // Claude Code once its by-hand part is opened. + assert_eq!( + h.query_all_by_label("/opt/wanderbooks mcp --book alpha") + .count(), + 4, + "the program and its arguments, for each tool that has no button" + ); + h.get_all_by_label("Or do it yourself, in a terminal") + .next() + .unwrap() + .click(); + h.run_steps(3); + assert!( + h.query_by_label( + "claude mcp add --scope user wanderbooks-alpha -- /opt/wanderbooks mcp --book alpha" + ) + .is_some() + ); + + // Revoke asks once, and does nothing until it is said again. + h.get_all_by_role_and_label(Role::Button, "Revoke") + .next() + .unwrap() + .click(); + h.run_steps(3); + assert!(!owner.said().iter().any(|s| s.starts_with("revoke"))); + h.get_by_role_and_label(Role::Button, "Keep it").click(); + h.run_steps(2); + assert!(!owner.said().iter().any(|s| s.starts_with("revoke"))); + h.get_all_by_role_and_label(Role::Button, "Revoke") + .next() + .unwrap() + .click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Yes, revoke").click(); + h.run_steps(2); + wait_for("the revoke ran", || { + owner.said().contains(&"revoke alpha agent".to_string()) + }); + until(&mut h, "the page says it", |a| { + a.views()[0].connect_state().said().is_some() + }); + // Who is connected is read again: the key and its session are gone. + until(&mut h, "the key is gone", |a| { + a.views()[0] + .assist() + .tokens + .iter() + .all(|t| t.name != "agent") + }); + assert!(h.query_by_label_contains("Key “agent”").is_none()); + assert!(h.query_by_label_contains("Key “web”").is_some()); + drop(h); +} + +#[test] +fn the_connect_buttons_do_what_connect_does() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![])); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + h.state_mut().goto(Route::Connect); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Connect Codex") + .click(); + h.run_steps(2); + wait_for("connect ran", || { + owner.said().contains(&"connect codex alpha".to_string()) + }); + until(&mut h, "it said what came of it", |a| { + a.views()[0].connect_state().said().is_some() + }); + h.run_steps(2); + assert!( + h.query_by_label_contains("Codex reaches the books.") + .is_some() + ); + h.get_by_role_and_label(Role::Button, "Make the key") + .click(); + h.run_steps(2); + wait_for("the key was made", || { + owner.said().contains(&"key alpha".to_string()) + }); + drop(h); +} + +// ---- 5: the warning before a close --------------------------------------------- + +fn connected_alpha(owner: &Fake) { + owner.answer(roster( + vec![session("alpha", "agent", "claude-code", 1, None)], + vec![token("alpha", "agent")], + )); +} + +#[test] +fn closing_the_window_with_an_assistant_connected_warns_and_then_closes_if_confirmed() { + let w = World::new(&[("alpha", "Wanderland Labs"), ("beta", "Fernhill Studio")]); + let owner = Fake::new(); + *owner.stop_takes.lock().unwrap() = Duration::from_millis(400); + connected_alpha(&owner); + let mut h = start(&w, &["alpha", "beta"], &owner); + refresh(&mut h); + ask_to_close(&mut h); + assert!(h.state().window_warning_is_up()); + assert!(h.query_by_label("Assistants are connected").is_some()); + assert!( + h.query_by_label_contains("Wanderland Labs: Claude Code is working") + .is_some() + ); + // Only the company that has one is named; the books are not closing. + assert!(h.query_by_label_contains("Fernhill Studio:").is_none()); + assert!(h.query_by_label_contains("Closing your books").is_none()); + assert!(!owner.said().contains(&"stop".to_string())); + // Keep it open: nothing closes, and nothing is up. + h.get_by_role_and_label(Role::Button, "Keep it open") + .click(); + h.run_steps(3); + assert!(!h.state().assistant_warning_is_up()); + assert!(!owner.said().contains(&"stop".to_string())); + // Asked again, and confirmed: the books close, in view, with no second + // dialog beside it. + ask_to_close(&mut h); + assert!(h.state().window_warning_is_up()); + h.get_by_role_and_label(Role::Button, "Close Wanderbooks") + .click(); + h.run_steps(2); + assert!(!h.state().assistant_warning_is_up()); + // The window's close command comes back as a close request (egui-winit + // does that; the harness does not). + ask_to_close(&mut h); + until(&mut h, "the close began", |a| a.serving().is_closing()); + assert!(!h.state().assistant_warning_is_up(), "not warned twice"); + assert!( + h.query_by_label_contains("Closing your books").is_some() + || h.state().serving().is_closed() + ); + assert!(h.query_by_label("Assistants are connected").is_none()); + until(&mut h, "the close is done", |a| a.serving().is_closed()); + assert_eq!( + owner.said().iter().filter(|s| *s == "stop").count(), + 1, + "{:?}", + owner.said() + ); + drop(h); +} + +#[test] +fn closing_the_window_with_no_assistant_connected_does_not_warn() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![token("alpha", "agent")])); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + ask_to_close(&mut h); + assert!(!h.state().assistant_warning_is_up()); + until(&mut h, "the close began", |a| a.serving().is_closing()); + assert!(h.query_by_label("Assistants are connected").is_none()); + drop(h); +} + +#[test] +fn a_server_that_does_not_answer_does_not_hold_a_close() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.close_gate(); + let mut h = start(&w, &["alpha"], &owner); + h.run_steps(5); + assert_eq!(links(&h), [Link::Unknown]); + ask_to_close(&mut h); + assert!(!h.state().assistant_warning_is_up(), "it cannot be told"); + until(&mut h, "the close began", |a| a.serving().is_closing()); + owner.open_gate(); + drop(h); +} + +#[test] +fn closing_a_tab_with_an_assistant_connected_warns_and_only_then() { + let w = World::new(&[("alpha", "Wanderland Labs"), ("beta", "Fernhill Studio")]); + let owner = Fake::new(); + connected_alpha(&owner); + let mut h = start(&w, &["alpha", "beta"], &owner); + refresh(&mut h); + // Beta has none: its tab closes at once. + h.get_by_label("Close Fernhill Studio").click(); + h.run_steps(3); + assert_eq!(h.state().views().len(), 1); + assert!(!h.state().assistant_warning_is_up()); + // Alpha has one: asked first. + h.get_by_label("Close Wanderland Labs").click(); + h.run_steps(3); + assert!(h.state().assistant_warning_is_up()); + assert!(!h.state().window_warning_is_up()); + assert!(h.query_by_label("Close Wanderland Labs?").is_some()); + assert_eq!(h.state().views().len(), 1); + h.get_by_role_and_label(Role::Button, "Keep it open") + .click(); + h.run_steps(3); + assert_eq!(h.state().views().len(), 1); + assert!(!h.state().assistant_warning_is_up()); + h.get_by_label("Close Wanderland Labs").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Close the company") + .click(); + h.run_steps(3); + assert_eq!(h.state().views().len(), 0); + wait_for("the company closed in the server", || { + owner.said().contains(&"close alpha".to_string()) + }); + drop(h); +} + +// ---- 6: how it looks ---------------------------------------------------------- + +fn describe(shape: &egui::epaint::Shape) -> String { + use egui::epaint::Shape; + match shape { + Shape::Text(t) => { + let mut out = format!( + "Text pos={:?} fallback={:?} angle={:?} text={:?}", + t.pos, t.fallback_color, t.angle, t.galley.job.text, + ); + for placed in &t.galley.rows { + out.push_str(&format!(" row@{:?} size={:?}", placed.pos, placed.row.size)); + for g in &placed.row.glyphs { + out.push_str(&format!(" {}@{:?}+{:?}", g.chr, g.pos, g.advance_width)); + } + } + out + } + Shape::Vec(v) => v.iter().map(describe).collect::>().join(" | "), + Shape::Mesh(m) => { + let mut out = String::from("Mesh"); + for v in &m.vertices { + out.push_str(&format!(" v{:?}{:?}", v.pos, v.color)); + } + out + } + other => format!("{other:?}"), + } +} + +/// A hash of every shape the window paints where it can be seen. +fn shapes_of(h: &Harness<'_, App>) -> u64 { + let screen = h.ctx.content_rect(); + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for s in h + .output() + .shapes + .iter() + .filter(|s| s.clip_rect.intersects(screen)) + { + let line = format!("{:?} {}", s.clip_rect, describe(&s.shape)); + for b in line.bytes() { + hash ^= b as u64; + hash = hash.wrapping_mul(0x100_0000_01b3); + } + } + hash +} + +/// The shapes painted are the check (`tests/snapshots/.shapes`; +/// `TABS_BLESS=1` writes them): never pixels. +fn picture(h: &Harness<'_, App>, name: &str) { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots"); + let file = dir.join(format!("{name}.shapes")); + let shapes = format!("{:016x}", shapes_of(h)); + if std::env::var("TABS_BLESS").is_ok() { + std::fs::write(&file, format!("{shapes}\n")).unwrap(); + } else { + let want = std::fs::read_to_string(&file) + .unwrap_or_else(|e| panic!("{}: {e} (TABS_BLESS=1 writes it)", file.display())); + assert_eq!(shapes, want.trim(), "the shapes of {name} changed"); + } +} + +/// A window of two companies in the three states (alpha: working, beta: +/// none, gamma: connected), the front one `front`. +fn three_states(dark: bool, front: usize, size: egui::Vec2) -> (World, Harness<'static, App>) { + let w = World::new(&[ + ("alpha", "Wanderland Labs LLC"), + ("beta", "Fernhill Studio"), + ("gamma", "Oak & Ash Carpentry"), + ]); + let owner = Fake::new(); + owner.answer(roster( + vec![ + session("alpha", "agent", "claude-code", 1, Some("books.post_entry")), + session( + "gamma", + "agent", + "codex-mcp-client", + 0, + Some("books.draft_entry"), + ), + ], + vec![token("alpha", "agent"), token("gamma", "agent")], + )); + let kept: HashMap = HashMap::from([ + ( + ledger_gui::app::open_key(&w.root), + "alpha,beta,gamma".to_string(), + ), + ("dark".to_string(), 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(size).build_eframe(move |cc| { + let mut app = App::start_with_owner( + &cc.egui_ctx, + &|k| kept.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ); + app.set_now(now()); + app + }); + let o: Arc = owner; + for i in 0..3 { + h.state_mut().view_mut(i).unwrap().set_owner(o.clone()); + } + until(&mut h, "the books load", |a| { + a.views().iter().all(|v| v.books().is_some()) + }); + refresh(&mut h); + h.state_mut().activate(front); + h.run_steps(4); + (w, h) +} + +#[test] +fn the_state_marks_the_top_bar_and_the_pages_look_as_blessed() { + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + let size = egui::vec2(1280.0, 800.0); + // alpha in front: working; the tabs show all three marks. + let (_w, mut h) = three_states(dark, 0, size); + picture(&h, &format!("assist_working_{mode}")); + h.state_mut().activate(1); + h.run_steps(4); + picture(&h, &format!("assist_none_{mode}")); + h.state_mut().activate(2); + h.run_steps(4); + picture(&h, &format!("assist_connected_{mode}")); + h.state_mut().goto(Route::Connect); + h.run_steps(4); + picture(&h, &format!("assist_connect_page_{mode}")); + h.state_mut().activate(1); + h.state_mut().goto(Route::Receivables); + h.run_steps(4); + picture(&h, &format!("assist_ask_{mode}")); + } +} + +/// The three states are three different shapes, whatever the colour (plugs +/// apart, plugs together, and an arc that is drawn, not a glyph). +#[test] +fn the_three_states_are_three_different_shapes() { + let (_w, h) = three_states(false, 0, egui::vec2(1280.0, 800.0)); + assert_eq!(links(&h), [Link::Working, Link::None, Link::Connected]); + let (none, connected, working) = ( + Link::None.glyph(), + Link::Connected.glyph(), + Link::Working.glyph(), + ); + assert!(none.is_some() && connected.is_some()); + assert_ne!(none, connected, "apart and together are two glyphs"); + assert_eq!(working, None, "working is an arc, drawn, and no glyph"); + assert_eq!( + Link::Unknown.glyph(), + None, + "nothing is drawn when not known" + ); +} + +/// Pictures of the main states for a person to look at +/// (`SHOT_DIR=… cargo test -p ledger-gui --test assistants -- --ignored pictures`). +#[test] +#[ignore] +fn pictures() { + let out = PathBuf::from(std::env::var("SHOT_DIR").expect("SHOT_DIR")); + std::fs::create_dir_all(&out).unwrap(); + let save = |h: &mut Harness<'_, App>, name: &str| { + h.render() + .unwrap() + .save(out.join(format!("{name}.png"))) + .unwrap(); + }; + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + let size = egui::vec2(1440.0, 920.0); + let (_w, mut h) = three_states(dark, 0, size); + h.state_mut().goto(Route::Transactions); + h.run_steps(4); + save(&mut h, &format!("1-working-{mode}")); + h.state_mut().activate(1); + h.run_steps(4); + save(&mut h, &format!("2-none-{mode}")); + h.state_mut().activate(2); + h.run_steps(4); + save(&mut h, &format!("3-connected-{mode}")); + h.state_mut().activate(1); + h.state_mut().goto(Route::Receivables); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Ask your assistant") + .click(); + h.run_steps(3); + save(&mut h, &format!("4-ask-your-assistant-{mode}")); + h.state_mut().goto(Route::Connect); + h.run_steps(4); + save(&mut h, &format!("5-connect-none-{mode}")); + h.state_mut().activate(0); + h.state_mut().goto(Route::Connect); + h.run_steps(4); + save(&mut h, &format!("6-connect-working-{mode}")); + // The window asked to close with an assistant connected. + ask_to_close(&mut h); + save(&mut h, &format!("7-close-warning-{mode}")); + // A short window, as the owner's laptop has. + let (_w2, mut small) = three_states(dark, 0, egui::vec2(1479.0, 519.0)); + save(&mut small, &format!("8-short-window-{mode}")); + } +} diff --git a/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes new file mode 100644 index 00000000..4dad9afc --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes @@ -0,0 +1 @@ +554a45de5050b79d diff --git a/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes b/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes new file mode 100644 index 00000000..8f6ab98b --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes @@ -0,0 +1 @@ +fffc3e5adaa00db0 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes new file mode 100644 index 00000000..b596b6df --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes @@ -0,0 +1 @@ +e8b3ce383a13c776 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes new file mode 100644 index 00000000..7c77cfb2 --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes @@ -0,0 +1 @@ +3271d551e50db504 diff --git a/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes new file mode 100644 index 00000000..c01b28ef --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes @@ -0,0 +1 @@ +9530691dfcdedf6b diff --git a/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes new file mode 100644 index 00000000..fd637ecd --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes @@ -0,0 +1 @@ +5f60b24231b7a370 diff --git a/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes new file mode 100644 index 00000000..54873482 --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes @@ -0,0 +1 @@ +9bc7803073cd0434 diff --git a/crates/ledger-gui/tests/snapshots/assist_none_light.shapes b/crates/ledger-gui/tests/snapshots/assist_none_light.shapes new file mode 100644 index 00000000..68a78c2f --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_none_light.shapes @@ -0,0 +1 @@ +fea19947b5c1a09e diff --git a/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes new file mode 100644 index 00000000..1ab2b0bb --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes @@ -0,0 +1 @@ +334251b6f2666663 diff --git a/crates/ledger-gui/tests/snapshots/assist_working_light.shapes b/crates/ledger-gui/tests/snapshots/assist_working_light.shapes new file mode 100644 index 00000000..a32351a4 --- /dev/null +++ b/crates/ledger-gui/tests/snapshots/assist_working_light.shapes @@ -0,0 +1 @@ +31ed42032e1844c9 diff --git a/docs/parity.md b/docs/parity.md index 93440f2e..57633476 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -255,4 +255,5 @@ Three new rows, none above changed status, and the floor stands. |---|---|---|---| | Books home: a visible folder per book, `/Wanderbooks/`, holding `AGENTS.md`, `CLAUDE.md`, `.mcp.json` and `.claude/settings.json` and nothing of the books | A QBO/Xero company has no counterpart; the point is the agent's workplace (D-27) | partial | `books_home_holds_no_books_data`, `a_books_home_made_again_keeps_what_a_person_kept` (`crates/ledger-host/tests/books_home.rs`); `partial` until the macOS home is tried | | Agent dock: Claude Code or Codex in a terminal along the bottom of the viewer, started in the books home; never required | QBO's assistant panel is a cross-check only | partial | `dock_runs_the_chosen_agent`, `agent_missing_offers_the_installer` (`crates/ledger-gui/tests/dock.rs`); Linux checked; macOS by the CI run; Windows not offered (ConPTY unchecked) | +| Assistants in the window: each company's state (none, connected, working) as a shape and a word, "Ask your assistant" where a button that edits would be, the Connect page (a row per local tool, the keys with who is on each, Revoke), and a warning before closing the window or a tab with an assistant connected (plan P15 3.3, D-79) | QBO's "Accountant" invitations and Xero's "Advisor" access are a cross-check only | partial | WB-assist-1 to WB-assist-4; `crates/ledger-gui/tests/assistants.rs`; local assistants only: the web half is plan units B1 and B3, the Claude desktop extension C1 | | First run with no terminal: the viewer sets up the private folder, the owner passphrase, the first books and an agent | QBO's "set up your company" flow | partial | `first_run_onboards_with_no_terminal` (`crates/ledger-gui/tests/welcome.rs`); the AppImage's whole path is the EM's to try on a clean machine | diff --git a/docs/spec/claims/assistants.md b/docs/spec/claims/assistants.md new file mode 100644 index 00000000..60d0ca26 --- /dev/null +++ b/docs/spec/claims/assistants.md @@ -0,0 +1,98 @@ +# Claims: assistants + +Wanderbooks' own product rules for how the window deals with the assistants +that do the bookkeeping (plan P15, `plan/p15-app-and-relay.md` 3.3). No +authority outside this product states them. They are `WB-assist-`. The +word in the window is "assistant", never "MCP", "agent", "server" or "token". + +Rules: none from bookspec's list; these are product rules only. + +--- + +### Product rules + +**WB-assist-1 Every company carries one of three states, as a shape and a word, +read from the server's own answer.** A company in the window is in exactly one +state: no assistant connected, connected (with the program's name: "Claude +Code"), or working (a call of an assistant is running); or not known, when the +books server has not answered lately (starting, gone, slow, or none). The +state comes from the server's sessions request, never from anything the +window did. A tab carries the shape (plugs apart, plugs together, a turning +arc: three silhouettes, so it reads without colour) with the words in its +hover; the front company's state is said in words once, at the right of the +top bar, with the last thing done in words ("Posted an entry, 10 seconds +ago"). The sidebar's links are not given up for it: they all fit at 1479x519 +(`tests/sidenav.rs`). Asking is off the UI thread, one request at a time, at +most every 2 seconds; an answer older than 15 seconds is not believed; a +server that is slow or gone is "not known" and no frame waits for it. What an +assistant says of itself is shown as said and trusted for nothing. +*Enforced:* `ledger_gui::connections` (`Connections::poll`, `status_within`, +`Status::word`, `Status::detail`), `ledger_gui::connect::paint_mark` and +`chip`, `ledger_gui::tabs::Tab::link`, `ledger_host::app_server::AppServer::roster`. +*Checked:* `ledger-gui` `tests/assistants.rs` +(`each_state_is_read_from_the_servers_answer_and_is_the_companys_own`, +`a_slow_server_is_never_waited_for_and_one_request_is_out_at_a_time`, +`a_server_that_is_gone_or_refuses_is_not_known_and_the_window_goes_on`, +`the_three_states_are_three_different_shapes`, +`the_state_marks_the_top_bar_and_the_pages_look_as_blessed`); `tests/sidenav.rs`. + +**WB-assist-2 Closing the window, or a tab, with an assistant connected warns +first, then closes if confirmed (D-79).** Asked to close the window, or a +company's tab, while an assistant is connected to what would close, the window +says so in plain words, names the companies and who is connected, says that +what an assistant is in the middle of finishes first and that nothing is cut +off half way, and closes only when the person says so; "Keep it open" leaves +everything as it was. With no assistant connected it does not warn. One +dialog is up at a time: a job that holds the window has its own dialog and no +warning is raised meanwhile; the warning comes before, and never beside, the +server's close ("Closing your books" and the close report of WB-app-4); a +close the person confirmed goes straight to that close and is not warned +again. A server that does not answer is not a reason to hold a close. +*Enforced:* `ledger_gui::app::App` (`guard_assistants`, `ask_close`), +`ledger_gui::connections::Connections::roster_within`. +*Checked:* `ledger-gui` `tests/assistants.rs` +(`closing_the_window_with_an_assistant_connected_warns_and_then_closes_if_confirmed`, +`closing_the_window_with_no_assistant_connected_does_not_warn`, +`a_server_that_does_not_answer_does_not_hold_a_close`, +`closing_a_tab_with_an_assistant_connected_warns_and_only_then`). + +**WB-assist-3 "Ask your assistant" is where a button that edits would be.** The +window only reads the books; to change anything a person asks an assistant. +On each page where a person might look for a button that edits (transactions, +invoices and bills, parties, accounts, fixed assets, projects, documents, the +company's settings) there is "Ask your assistant", which copies one ready +sentence naming the company and what the page is for ("In my Wanderbooks books +for Acme, please create a new invoice.") and says it did. With no assistant +connected it says so and links to the Connect page. It writes nothing, and it +is not offered in a window that runs no books server. A banner saying +"read-only" is not the design. +*Enforced:* `ledger_gui::widgets::page_header_ask`, +`ledger_gui::connect::ask_button`, `ask_feedback`, `sentence`. +*Checked:* `ledger-gui` `tests/assistants.rs` +(`ask_your_assistant_copies_one_ready_sentence`, +`a_window_with_no_server_offers_no_assistant`). + +**WB-assist-4 The Connect page connects an assistant on this computer and ends +a key.** The page ("Assistants", under the company) says in its first sentence +that everything here is for reading and that changes go through an assistant. +It has a row for each of Claude Code, Codex, Gemini CLI, Grok Build, Muse Code +and Cursor. Claude Code and Codex have a button that does what `wanderbooks +connect` does (a key made and kept on this computer, the bridge added to the +assistant's own list) and, folded, the exact command it runs. For the other +four the page gives the program and arguments an assistant must run +(` mcp --book ID`, with `--root` when a root was named), the +one-time "Make the key" step, and says the tool is untested: the repository +documents no configuration format for them, and none is invented. The page +lists every key to the company with who is connected on it, what it may do and +when it connected and last acted, and "Revoke", asked once, which calls what +`wanderbooks token revoke` calls (the server ends the key and the sessions on +it; its copy in the token file is removed). The window writes no books. The +web half of the page (the switch, the address, the steps for Claude and +ChatGPT) is plan unit B3's; `connect::State::web_section` is its place, and +the "Claude desktop app" row (a one-click extension) is unit C1's. +*Enforced:* `ledger_gui::connect::State::show`, `ledger_host::commands` +(`bridge_serve_args`, `command_line`, `ensure_key`, `forget_token_file`), +`ledger_host::app_server::AppServer::revoke_token`. +*Checked:* `ledger-gui` `tests/assistants.rs` +(`the_top_bar_state_opens_the_connect_page_which_lists_and_revokes`, +`the_connect_buttons_do_what_connect_does`).