From 016f1b2afca70f3ff59658599e8edb0260d205ce Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 09:28:50 -0700 Subject: [PATCH 1/7] feat(host,gui): the window can ask the books server who is connected, and end a token Unit A4 of plan P15 needs the window to read who is connected to each open company and to end a token. Both go through admin requests the server already answers (Sessions, TokenList, TokenRevoke): the window's server handle gains a quick roster (an Err in words while the server is starting, gone or slow; never a wait) and a revoke that does what `wanderbooks token revoke` does, including removing the token file's copy. The command that reaches a company's books is now made in one place (`bridge_serve_args`) for `connect` and for the Connect page. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 43 +++++++++++++++ crates/ledger-gui/src/owner.rs | 74 +++++++++++++++++++++++++ crates/ledger-host/src/app_server.rs | 81 +++++++++++++++++++++++++++ crates/ledger-host/src/commands.rs | 82 +++++++++++++++++++++------- 4 files changed, 260 insertions(+), 20 deletions(-) diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index ddf6173b..326d5e12 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -116,6 +116,49 @@ impl ledger_gui::owner::Owner for ViewerOwner { self.server.exited() } + fn serve_roster(&self) -> Result { + use ledger_gui::owner::{Assistant, LastCall, Roster, TokenRow}; + let roster = self.server.roster(std::time::Duration::from_secs(3))?; + let mut assistants = Vec::new(); + for book in roster.sessions { + for s in book.sessions { + assistants.push(Assistant { + book: book.book.clone(), + token: s.token, + client_name: s.client_name, + client_version: s.client_version, + model: s.agent.and_then(|a| a.model), + connected_at: s.connected_at, + running: s.running, + last: s.last.map(|l| LastCall { + tool: l.tool, + outcome: l.outcome, + at: l.at, + }), + }); + } + } + let tokens = roster + .tokens + .into_iter() + .map(|t| TokenRow { + book: t.book, + name: t.name, + scopes: t.scopes, + created: t.created, + }) + .collect(); + Ok(Roster { assistants, tokens }) + } + + fn serve_revoke(&self, book: &str, name: &str) -> Result { + self.server.revoke_token(book, name) + } + + fn bridge_command(&self, book: &str) -> Result { + ledger_host::commands::bridge_command_line(&self.common, book) + } + fn close_books(&self) -> Result { ledger_host::commands::close_books(&self.common) } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 5b124fa7..9e2bc318 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -153,6 +153,62 @@ pub struct UpdateWaiting { pub staged_at: String, } +/// A call an assistant made last, as the server says it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LastCall { + /// The tool (or the resource's address). + pub tool: String, + /// "ok", "error", or "refused: CODE". + pub outcome: String, + /// When it finished (UTC, RFC 3339). + pub at: String, +} + +/// One assistant connected to a company, from the server's sessions +/// request (plan P15 3.1): what it said of itself (asserted, never +/// checked) and what it is doing. Never a token's text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Assistant { + /// The company it is connected to (the id of its books). + pub book: String, + /// The NAME of the token it opened its session with. + pub token: String, + /// The program's name, as it said at the start. + pub client_name: Option, + /// Its version. + pub client_version: Option, + /// The model it said it is, if it did. + pub model: Option, + /// When it connected (UTC, RFC 3339). + pub connected_at: String, + /// Calls of it running now. + pub running: u32, + /// The last call it made, if it has made one. + pub last: Option, +} + +/// A token, as listed: who may connect to a company (never its text). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TokenRow { + /// The company it opens. + pub book: String, + /// Its name. + pub name: String, + /// What it may do (books:read, books:write, books:post, books:admin). + pub scopes: Vec, + /// When it was made (UTC). + pub created: String, +} + +/// Who is connected and who may connect, across the open companies. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Roster { + /// Every live session. + pub assistants: Vec, + /// Every live token. + pub tokens: Vec, +} + /// The owner's actions, done by the program the viewer runs in (ledger-cli /// over the books server and the agents' own commands). Each blocks: the /// menu calls it off the UI thread. @@ -199,6 +255,24 @@ pub trait Owner: Send + Sync { fn serve_exited(&self) -> Option { None } + /// Who is connected to the open companies, and which tokens are live: + /// two quick requests to the server, an `Err` (in words) when it is + /// starting, gone or does not answer in a few seconds. Blocks, for that + /// long at most: the window asks off its UI thread. + fn serve_roster(&self) -> Result { + Ok(Roster::default()) + } + /// End the token `name` of the company `book` (what `wanderbooks token + /// revoke` does): `Ok` says what was done, in words. Blocks. + fn serve_revoke(&self, _book: &str, _name: &str) -> Result { + Err("not here".into()) + } + /// The command an assistant runs to reach the company `book`, as text + /// to type (the program and `mcp --book ID`, quoted for a terminal): + /// what the Connect page shows for an assistant it has no button for. + fn bridge_command(&self, _book: &str) -> Result { + Err("not here".into()) + } /// Close the books: everything holding them lets go. fn close_books(&self) -> Result; /// New, empty books `id` in `currency`. diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index c3752800..bd036ea5 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -62,6 +62,14 @@ //! 11. After the server is ready, the companies the window wanted open //! are checked against the server's list: one that is not open is //! returned in words ([`AppHost::not_open`]). +//! 12. Who is connected, and the tokens there are, are read with two +//! quick admin requests (`Sessions`, `TokenList`) that wait for +//! neither the server's start nor an answer for long +//! ([`AppHost::roster`]): a server that is starting, gone or slow +//! is an `Err` in words, never a wait; a token is revoked by the +//! request `wanderbooks token revoke` makes, and its copy in the +//! token file goes with it ([`AppHost::revoke_token`]). Neither ever +//! holds a token's text. //! ``` use crate::host::{SERVER_LOG, children_executable, open_log, private_options}; @@ -136,6 +144,16 @@ pub enum Stopped { StillClosing, } +/// Who is connected and which tokens are live, as the server says +/// (INVARIANT 12). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Roster { + /// For each open company, its live sessions. + pub sessions: Vec, + /// Every live token. + pub tokens: Vec, +} + /// The books server, a child process of this one. pub struct AppServer { run: PathBuf, @@ -377,6 +395,58 @@ impl AppServer { } } + /// Who is connected to each open company, and every live token + /// (INVARIANT 12). It does not wait for the server to be ready: a + /// server still starting is an `Err`, and so is one that does not + /// answer within `wait`. + pub fn roster(&self, wait: Duration) -> Result { + if !self.is_ready() { + return Err(match self.exited() { + Some(why) => why, + None => "the books server is still starting".into(), + }); + } + let sessions = match self.ask(Request::Sessions, Some(wait))? { + Response::Sessions(open) => open, + Response::Refused(why) => return Err(why), + other => return Err(format!("the books server answered oddly: {other:?}")), + }; + let tokens = match self.ask(Request::TokenList, Some(wait))? { + Response::Tokens(tokens) => tokens, + Response::Refused(why) => return Err(why), + other => return Err(format!("the books server answered oddly: {other:?}")), + }; + Ok(Roster { sessions, tokens }) + } + + /// End the token `name` of the company `book`, as `wanderbooks token + /// revoke` does (INVARIANT 12): the server ends the token and the + /// sessions it opened, and the token file's copy is removed. `Ok` says + /// what was done, in words; a token file that could not be cleaned is + /// said, and the token is revoked all the same. + pub fn revoke_token(&self, book: &str, name: &str) -> Result { + self.wait_ready(READY_WAIT)?; + let request = Request::TokenRevoke { + book: book.into(), + name: name.into(), + id: None, + }; + match self.ask_raw(request, Some(Duration::from_secs(30))) { + Ok(Response::TokenRevoked(t)) => { + let said = format!("Ended {:?}'s access to {}.", t.name, t.book); + match crate::commands::forget_token_file(&self.run, book, name) { + Ok(()) => Ok(said), + Err(why) => Ok(format!( + "{said} Its token file still holds its text ({why}); it opens nothing now." + )), + } + } + Ok(Response::Refused(why)) => Err(why), + Ok(other) => Err(format!("the books server answered oddly: {other:?}")), + Err(e) => Err(e.to_string()), + } + } + /// The owner's go-ahead for the format upgrade of the company `id`, /// with the owner passphrase they typed, sent to the server as the /// host sends it (INVARIANT 10): what came of it, a line each; or why @@ -621,6 +691,17 @@ impl AppHost { .collect() } + /// Who is connected, and which tokens are live (INVARIANT 12): quick, + /// for a server that is not running or not ready an `Err`. + pub fn roster(&self, wait: Duration) -> Result { + self.running()?.roster(wait) + } + + /// End a token (INVARIANT 12). + pub fn revoke_token(&self, book: &str, name: &str) -> Result { + self.running()?.revoke_token(book, name) + } + /// The format upgrade of the company `id` (INVARIANT 10). pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result, String> { match self.running() { diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index f4ec92a9..20189011 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1402,6 +1402,66 @@ pub fn connect( } } +/// The command an assistant runs to reach the books `book`: this program's +/// own executable and `mcp --book `, with `--root` when the data root +/// was named and the knobs this run was given. The one place it is made: +/// `connect_agent` registers it, and the window's Connect page shows it to +/// be typed into an assistant that has no `connect` of its own. +pub fn bridge_serve_args(common: &Common, book: &str) -> Result, String> { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + // A translocated macOS app's path (P11a step 6) is not a place to point + // an agent: the copy goes away with the app. + let exe = crate::start::this_executable()?; + if let Some(why) = crate::start::translocation_refusal(&exe) { + return Err(why.to_string()); + } + let mut serve: Vec = vec![ + exe.into_os_string(), + "mcp".into(), + "--book".into(), + book.into(), + ]; + if common.root.is_some() { + let found = + ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; + serve.push("--root".into()); + serve.push(found.path().as_os_str().to_os_string()); + } + serve.extend(common.knobs.args().into_iter().map(Into::into)); + Ok(serve) +} + +/// [`bridge_serve_args`] as text, for an assistant that is set up by hand: +/// a part with a space in it is quoted for a terminal. +pub fn bridge_command_line(common: &Common, book: &str) -> Result { + let args = bridge_serve_args(common, book)?; + Ok(args + .iter() + .map(|a| { + let a = a.to_string_lossy(); + if a.contains(char::is_whitespace) { + format!("\"{a}\"") + } else { + a.into_owned() + } + }) + .collect::>() + .join(" ")) +} + +/// A revoked token's copy in the token file goes with it (what `token +/// revoke` does after the server has ended the token). `run_dir` is the +/// root's `run/` folder. +pub fn forget_token_file(run_dir: &Path, book: &str, name: &str) -> Result<(), String> { + let root = run_dir.parent().unwrap_or(run_dir).to_path_buf(); + let account = crate::tokens::Account::new(&root, book, name); + crate::tokens::keeper(run_dir) + .delete(&account) + .map_err(|e| e.to_string()) +} + /// Let the agent `agent` ("claude" or "codex") reach the books `book`: /// their token kept in its token file (made if none is), and `wanderbooks /// mcp --book ` added to the agent's own list as @@ -1420,12 +1480,7 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result Result = vec![ - exe.into_os_string(), - "mcp".into(), - "--book".into(), - book.clone().into(), - ]; - if common.root.is_some() { - serve.push("--root".into()); - serve.push(found.path().as_os_str().to_os_string()); - } - serve.extend(common.knobs.args().into_iter().map(Into::into)); let scope: &[&str] = if agent == "claude" { &["--scope", "user"] } else { @@ -2809,9 +2853,7 @@ pub fn token( let (answer, run_dir) = with_server_in(&common, request).map_err(fail)?; match answer { Response::TokenRevoked(t) => { - let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); - let account = crate::tokens::Account::new(&root, &book, &name); - let forgot = crate::tokens::keeper(&run_dir).delete(&account); + let forgot = forget_token_file(&run_dir, &book, &name); println!("Revoked the token {:?} for the books {}.", t.name, t.book); if let Err(why) = forgot { eprintln!( From 1d1a2a5a8848c9afeb6dd8555694244d02cff244 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:03:35 -0700 Subject: [PATCH 2/7] feat(host,gui): the command that reaches a company's books is made in one place The Connect page of P15 unit A4 shows an assistant the exact command it must run to reach a company (` mcp --book ID`, with --root when a root was named). `connect` already built that command, so it is now one function (`bridge_serve_args`/`command_line`) used by both, and the step `connect` does first (the company's default key exists and its copy is in the token file) is `ensure_key`, which the page offers by itself for assistants it has no button for. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 8 ++- crates/ledger-gui/src/owner.rs | 14 +++-- crates/ledger-host/src/commands.rs | 82 +++++++++++++++++------------- 3 files changed, 64 insertions(+), 40 deletions(-) diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 326d5e12..ba57781c 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -155,8 +155,12 @@ impl ledger_gui::owner::Owner for ViewerOwner { self.server.revoke_token(book, name) } - fn bridge_command(&self, book: &str) -> Result { - ledger_host::commands::bridge_command_line(&self.common, book) + fn command_line(&self, words: &[&str]) -> Result { + ledger_host::commands::command_line(&self.common, words) + } + + fn make_key(&self, book: &str) -> Result { + ledger_host::commands::ensure_key(&self.common, book) } fn close_books(&self) -> Result { diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 9e2bc318..4c98e612 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -267,10 +267,16 @@ pub trait Owner: Send + Sync { fn serve_revoke(&self, _book: &str, _name: &str) -> Result { Err("not here".into()) } - /// The command an assistant runs to reach the company `book`, as text - /// to type (the program and `mcp --book ID`, quoted for a terminal): - /// what the Connect page shows for an assistant it has no button for. - fn bridge_command(&self, _book: &str) -> Result { + /// This program run with `words`, as a line to type in a terminal (the + /// program's own path, the words, the data root if one was named): what + /// the Connect page shows for an assistant it has no button for. + fn command_line(&self, _words: &[&str]) -> Result { + Err("not here".into()) + } + /// The key an assistant needs to reach the company `book` exists (made + /// now if it did not): `Ok(true)` when it was made now. What `connect` + /// does first, for an assistant set up by hand. Blocks. + fn make_key(&self, _book: &str) -> Result { Err("not here".into()) } /// Close the books: everything holding them lets go. diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 20189011..278055eb 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1402,42 +1402,43 @@ pub fn connect( } } -/// The command an assistant runs to reach the books `book`: this program's -/// own executable and `mcp --book `, with `--root` when the data root -/// was named and the knobs this run was given. The one place it is made: -/// `connect_agent` registers it, and the window's Connect page shows it to -/// be typed into an assistant that has no `connect` of its own. -pub fn bridge_serve_args(common: &Common, book: &str) -> Result, String> { - let book = ledger_store::root::BookId::parse(book) - .map_err(|e| e.to_string())? - .to_string(); +/// This program's own executable followed by `words`, then `--root` when +/// the data root was named and the knobs this run was given: what an +/// assistant, or a person at a terminal, runs to reach these books. The one +/// place it is made. +fn program_args(common: &Common, words: &[&str]) -> Result, String> { // A translocated macOS app's path (P11a step 6) is not a place to point // an agent: the copy goes away with the app. let exe = crate::start::this_executable()?; if let Some(why) = crate::start::translocation_refusal(&exe) { return Err(why.to_string()); } - let mut serve: Vec = vec![ - exe.into_os_string(), - "mcp".into(), - "--book".into(), - book.into(), - ]; + let mut args: Vec = vec![exe.into_os_string()]; + args.extend(words.iter().map(std::ffi::OsString::from)); if common.root.is_some() { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; - serve.push("--root".into()); - serve.push(found.path().as_os_str().to_os_string()); + args.push("--root".into()); + args.push(found.path().as_os_str().to_os_string()); } - serve.extend(common.knobs.args().into_iter().map(Into::into)); - Ok(serve) + args.extend(common.knobs.args().into_iter().map(Into::into)); + Ok(args) } -/// [`bridge_serve_args`] as text, for an assistant that is set up by hand: -/// a part with a space in it is quoted for a terminal. -pub fn bridge_command_line(common: &Common, book: &str) -> Result { - let args = bridge_serve_args(common, book)?; - Ok(args +/// The command an assistant runs to reach the books `book`: this program +/// and `mcp --book `. `connect_agent` registers it, and the window's +/// Connect page shows it for an assistant that has no `connect` of its own. +pub fn bridge_serve_args(common: &Common, book: &str) -> Result, String> { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + program_args(common, &["mcp", "--book", &book]) +} + +/// This program run with `words`, as a line to type in a terminal: a part +/// with a space in it is quoted. +pub fn command_line(common: &Common, words: &[&str]) -> Result { + Ok(program_args(common, words)? .iter() .map(|a| { let a = a.to_string_lossy(); @@ -1451,6 +1452,28 @@ pub fn bridge_command_line(common: &Common, book: &str) -> Result Result { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + let found = + ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + let account = crate::tokens::Account::new(found.path(), &book, crate::tokens::DEFAULT_NAME); + if crate::tokens::keeper(&run).get(&account)?.is_some() { + return Ok(false); + } + let scopes = ledger_store::auth::Scope::ALL + .iter() + .map(|s| s.as_str().to_string()) + .collect(); + make_token(common, &book, crate::tokens::DEFAULT_NAME, scopes, true)?; + Ok(true) +} + /// A revoked token's copy in the token file goes with it (what `token /// revoke` does after the server has ended the token). `run_dir` is the /// root's `run/` folder. @@ -1483,16 +1506,7 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result Date: Sat, 21 Nov 2026 10:03:35 -0700 Subject: [PATCH 3/7] 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`). From f218bf45523c71f6ef78644e5dd7b34203f18199 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:16:26 -0700 Subject: [PATCH 4/7] test(cli): the roster and a key's revoke, through the real books server A bridge session opened with a key is on the roster; revoking the key takes the key and its session off, refuses the session's next call and deletes the token file's copy. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/app_server.rs | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index ab903fdb..a3f0be0d 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -41,6 +41,9 @@ //! company whose closing backup was incomplete and a server that //! exited badly; the format upgrade reaches the server; a company //! that is not open is told. +//! 9. The roster, from the real server, lists a key and the bridge +//! session opened with it; ending the key takes both off the roster, +//! refuses the session's next call and deletes the token file's copy. //! ``` mod common; @@ -714,3 +717,76 @@ fn the_format_upgrade_goes_to_the_windows_own_server() { assert!(refused.starts_with("not upgraded: "), "{refused}"); assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); } + +/// What the window's Connect page reads and does, through the real server +/// (not a fake): a bridge session opened with a key is on the roster, and +/// revoking the key takes it off, refuses its next call and forgets its +/// token file (plan/p15-app-and-relay.md 3.3; app_server.rs INVARIANT 12). +#[test] +fn the_roster_lists_a_connected_key_and_revoking_it_ends_its_use() { + let home = Home::new("app-roster"); + let run = home.run(); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + home.create(BOOK, "USD"); + assert_eq!(server.open_book(BOOK), Ok(None)); + let token = home.token_with(BOOK, "agent", &["read", "write", "post", "admin"]); + let account = ledger_host::tokens::Account::new(&home.root(), BOOK, "agent"); + let keeper = ledger_host::tokens::keeper(&run); + keeper.set(&account, &token).unwrap(); + + // A bridge session opens with the key and makes a call. + let mut bridge = Bridge::start(&home); + let init = bridge.initialize(); + assert!(init.get("error").is_none(), "{init}"); + let answered = bridge.start_call(); + assert!( + answered.get("error").is_none() && answered.get("result").is_some(), + "{answered}" + ); + + // The roster, as the window asks for it, lists the key and its session. + let roster = server.roster(Duration::from_secs(30)).unwrap(); + assert!( + roster + .tokens + .iter() + .any(|t| t.book == BOOK && t.name == "agent"), + "{roster:?}" + ); + let sessions_on_key = |r: &ledger_host::app_server::Roster| { + r.sessions + .iter() + .filter(|b| b.book == BOOK) + .flat_map(|b| &b.sessions) + .filter(|s| s.token == "agent") + .count() + }; + assert_eq!(sessions_on_key(&roster), 1, "{roster:?}"); + assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*token)); + + // Revoked: said in words, and no longer usable. + let said = server.revoke_token(BOOK, "agent").unwrap(); + assert!(said.contains("access"), "{said}"); + // (a) the roster no longer lists the key, nor a session on it, + let after = server.roster(Duration::from_secs(30)).unwrap(); + assert!( + !after + .tokens + .iter() + .any(|t| t.book == BOOK && t.name == "agent"), + "{after:?}" + ); + assert_eq!(sessions_on_key(&after), 0, "{after:?}"); + // (b) the next call with that key is refused, + let refused = bridge.start_call(); + assert!( + refused.get("error").is_some() || refused["result"]["isError"] == json!(true), + "{refused}" + ); + // (c) and the token file's copy is gone. + assert_eq!(keeper.get(&account).unwrap(), None); + // Asking again for a key that is gone says so, and breaks nothing. + assert!(server.revoke_token(BOOK, "agent").is_err()); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} From f58191c9de4fe90d417bb53d5b5371b276492a9f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:16:26 -0700 Subject: [PATCH 5/7] fix(gui): the word a person reads is assistant, with no tool names The bottom panel, the welcome steps, empty states and notices said agent, bookkeeper or a books.* tool name; they now say assistant. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/dock.rs | 14 +++++++------- crates/ledger-gui/src/lib.rs | 2 +- crates/ledger-gui/src/menu.rs | 4 ++-- crates/ledger-gui/src/pages/assets.rs | 25 ++++++++++++------------- crates/ledger-gui/src/pages/cash.rs | 2 +- crates/ledger-gui/src/pages/company.rs | 4 ++-- crates/ledger-gui/src/pages/invoices.rs | 6 +++--- crates/ledger-gui/src/pages/overview.rs | 2 +- crates/ledger-gui/src/pages/parties.rs | 2 +- crates/ledger-gui/src/pages/projects.rs | 2 +- crates/ledger-gui/src/pages/reports.rs | 2 +- crates/ledger-gui/src/welcome.rs | 12 ++++++------ crates/ledger-gui/src/widgets.rs | 4 ++-- crates/ledger-gui/tests/assets.rs | 4 ++-- 14 files changed, 42 insertions(+), 43 deletions(-) diff --git a/crates/ledger-gui/src/dock.rs b/crates/ledger-gui/src/dock.rs index b31c506a..d2008ab8 100644 --- a/crates/ledger-gui/src/dock.rs +++ b/crates/ledger-gui/src/dock.rs @@ -749,16 +749,16 @@ impl Dock { if ui .add(egui::Button::new(RichText::new(chevron).size(14.0)).frame(false)) .on_hover_text(if self.open { - "Collapse the agent dock" + "Collapse the assistant panel" } else { - "Open the agent dock" + "Open the assistant panel" }) .clicked() { self.open = !self.open; } ui.label( - RichText::new(format!("{} Agent", icon::TERMINAL_WINDOW)) + RichText::new(format!("{} Assistant", icon::TERMINAL_WINDOW)) .font(crate::theme::semibold(12.5)) .color(p.text), ); @@ -787,7 +787,7 @@ impl Dock { && !ended && ui .button(icon::ARROW_CLOCKWISE) - .on_hover_text("Restart the agent") + .on_hover_text("Restart the assistant") .clicked() { restart = true; @@ -800,7 +800,7 @@ impl Dock { } } else { ui.label( - RichText::new("Optional: any agent can use these books") + RichText::new("Optional: any assistant can use these books") .size(12.0) .color(p.faint), ); @@ -816,7 +816,7 @@ impl Dock { match &mut self.state { State::Idle => {} State::Starting(_) => { - ui.label(RichText::new("Starting the agent…").color(p.muted)); + ui.label(RichText::new("Starting the assistant…").color(p.muted)); } State::Failed(why) => { ui.add_space(6.0); @@ -840,7 +840,7 @@ impl Dock { ui.hyperlink_to(format!("{} instructions", i.label), &i.page); ui.label( RichText::new( - "You never need this: any agent you run yourself reaches the same books.", + "You never need this: any assistant you run yourself reaches the same books.", ) .color(p.faint), ); diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 80290487..eb4a4f9d 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -184,7 +184,7 @@ pub fn book_in_root(root: Option<&std::path::Path>, book: Option<&str>) -> Resul id } None => books.into_iter().next().ok_or_else(|| { - "there are no books yet: your agent makes them (`wanderbooks books create`)." + "there are no books yet: your assistant makes them (`wanderbooks books create`)." .to_string() })?, }; diff --git a/crates/ledger-gui/src/menu.rs b/crates/ledger-gui/src/menu.rs index f97b4213..8a62cbdf 100644 --- a/crates/ledger-gui/src/menu.rs +++ b/crates/ledger-gui/src/menu.rs @@ -240,7 +240,7 @@ impl Job { let mut notes = Vec::new(); if !p.tin_gaps.is_empty() { notes.push(format!( - "{} TIN(s) aren't in it (the README says which): ask your agent to collect them.", + "{} TIN(s) aren't in it (the README says which): ask your assistant to collect them.", p.tin_gaps.len() )); } @@ -279,7 +279,7 @@ impl Job { .filter(|l| l.may_file() && l.tin.is_none()) .count(); let note = (gaps > 0).then(|| { - format!("{gaps} payee(s) a 1099 is or may be due for have no TIN in it: ask your agent to collect them.") + format!("{gaps} payee(s) a 1099 is or may be due for have no TIN in it: ask your assistant to collect them.") }); Ok((path, note)) } diff --git a/crates/ledger-gui/src/pages/assets.rs b/crates/ledger-gui/src/pages/assets.rs index a6c9922e..c1aad8a9 100644 --- a/crates/ledger-gui/src/pages/assets.rs +++ b/crates/ledger-gui/src/pages/assets.rs @@ -81,7 +81,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out.push(Notice { problem: true, text: format!( - "Depreciation not yet posted through {}: {} — ask the bookkeeper to run depreciation{}.", + "Depreciation not yet posted through {}: {} — ask your assistant to run depreciation{}.", fmt::date(due.through), fmt::dollars(due_amount), if due.periods.is_empty() { @@ -108,7 +108,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out.push(Notice { problem: true, text: format!( - "The books carry {} more accumulated depreciation than the schedules through {} — ask the bookkeeper to check the depreciation entries.", + "The books carry {} more accumulated depreciation than the schedules through {} — ask your assistant to check the depreciation entries.", fmt::dollars(neg(unposted)), fmt::date(r.as_of) ), @@ -119,7 +119,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out.push(Notice { problem: true, text: format!( - "{} in the asset cost accounts isn't in the register — ask the bookkeeper to register it with books.register_asset.", + "{} in the asset cost accounts isn't in the register — ask your assistant to register it.", fmt::dollars(unregistered) ), }); @@ -127,7 +127,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out.push(Notice { problem: true, text: format!( - "{} of registered cost isn't in the books' asset cost accounts — ask the bookkeeper to check the purchase entries.", + "{} of registered cost isn't in the books' asset cost accounts — ask your assistant to check the purchase entries.", fmt::dollars(neg(unregistered)) ), }); @@ -137,7 +137,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out.push(Notice { problem: true, text: format!( - "{} of accumulated depreciation in the books isn't from any asset's depreciation runs — ask the bookkeeper to find the entries behind it.", + "{} of accumulated depreciation in the books isn't from any asset's depreciation runs — ask your assistant to find the entries behind it.", fmt::dollars(unattributed) ), }); @@ -160,12 +160,11 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec { out } -/// "Tax basis not recorded for 2 assets — ask the bookkeeper to record it -/// (books.set_asset_tax_basis).", or `None` when every asset held has one. +/// "Tax basis not recorded for 2 assets — ask your assistant to record it", or `None` when every asset held has one. pub fn missing_tax_notice(missing: usize) -> Option { (missing > 0).then(|| { format!( - "Tax basis not recorded for {} — ask the bookkeeper to record {} (books.set_asset_tax_basis): bought by the company, contributed by a member from business use, or contributed from personal use.", + "Tax basis not recorded for {} — ask your assistant to record {}: bought by the company, contributed by a member from business use, or contributed from personal use.", fmt::count(missing, "asset", "assets"), if missing == 1 { "it" } else { "each" } ) @@ -511,7 +510,7 @@ pub fn show_register(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui, icon::PACKAGE, "No fixed assets", - "Equipment the company capitalizes appears here once the bookkeeper registers it (books.register_asset).", + "Equipment the company capitalizes appears here once your assistant registers it.", ) }); return; @@ -526,7 +525,7 @@ pub fn show_register(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui, icon::PACKAGE, "The register can't be computed", - &format!("{e}. Ask the bookkeeper to find the record behind it."), + &format!("{e}. Ask your assistant to find the record behind it."), ) }); return; @@ -1025,7 +1024,7 @@ pub fn show_asset(ui: &mut Ui, b: &Books, id: AssetId, shell: &mut Shell<'_>) { } None => { widgets::pill(ui, "No tag yet", p.warning, p.warning_soft) - .on_hover_text("Ask the bookkeeper to label it (books.label_asset)."); + .on_hover_text("Ask your assistant to label it."); } } ui.label(RichText::new(&a.description).font(theme::bold(22.0))); @@ -1201,7 +1200,7 @@ pub fn show_asset(ui: &mut Ui, b: &Books, id: AssetId, shell: &mut Shell<'_>) { &Notice { problem: true, text: format!( - "{} of depreciation for finished months isn't posted — ask the bookkeeper to run depreciation.", + "{} of depreciation for finished months isn't posted — ask your assistant to run depreciation.", fmt::dollars(due) ), }, @@ -1448,7 +1447,7 @@ fn tax_card(ui: &mut Ui, a: &Asset) { ui.add( egui::Label::new( RichText::new( - "Ask the bookkeeper to record it (books.set_asset_tax_basis): was it bought by the company, contributed by a member from business use, or converted from personal use? For a contribution, book cost is the fair market value at contribution; tax depreciation starts from the depreciable basis — the CPA's.", + "Ask your assistant to record it: was it bought by the company, contributed by a member from business use, or converted from personal use? For a contribution, book cost is the fair market value at contribution; tax depreciation starts from the depreciable basis — the CPA's.", ) .font(theme::regular(12.5)) .color(p.muted), diff --git a/crates/ledger-gui/src/pages/cash.rs b/crates/ledger-gui/src/pages/cash.rs index d7b76069..58d86b7a 100644 --- a/crates/ledger-gui/src/pages/cash.rs +++ b/crates/ledger-gui/src/pages/cash.rs @@ -50,7 +50,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui, icon::BANK, "No cash accounts found", - "Name an asset account \"checking\", \"savings\", or \"cash\", or ask the agent to set the books' cash accounts.", + "Name an asset account \"checking\", \"savings\", or \"cash\", or ask your assistant to set the books' cash accounts.", ) }); return; diff --git a/crates/ledger-gui/src/pages/company.rs b/crates/ledger-gui/src/pages/company.rs index a0ae88ca..820be682 100644 --- a/crates/ledger-gui/src/pages/company.rs +++ b/crates/ledger-gui/src/pages/company.rs @@ -176,7 +176,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { if c.profile.iter().all(|(k, _)| k == "base_currency") { ui.label( RichText::new( - "No company facts set yet: the agent records them as you give them.", + "No company facts set yet: your assistant records them as you give them.", ) .color(p.muted), ); @@ -201,7 +201,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { } ui.label( RichText::new( - "Kept in the books: the agent changes settings, with who decided and when.", + "Kept in the books: your assistant changes settings, with who decided and when.", ) .font(theme::regular(12.0)) .color(p.muted), diff --git a/crates/ledger-gui/src/pages/invoices.rs b/crates/ledger-gui/src/pages/invoices.rs index e1a29219..d1b6c080 100644 --- a/crates/ledger-gui/src/pages/invoices.rs +++ b/crates/ledger-gui/src/pages/invoices.rs @@ -241,7 +241,7 @@ pub fn show_list(ui: &mut Ui, b: &Books, bills: bool, shell: &mut Shell<'_>) { 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.", + "What customers owe the company and what it owes vendors, each figure read from the ledger, tied to its account. Your assistant issues, records and voids them.", if bills { "enter a new bill" } else { @@ -367,9 +367,9 @@ pub fn show_list(ui: &mut Ui, b: &Books, bills: bool, shell: &mut Shell<'_>) { ( if bills { "No bills" } else { "No invoices" }, if bills { - "A vendor's bill appears here once the bookkeeper records it (books.create_bill)." + "A vendor's bill appears here once your assistant records it." } else { - "An invoice appears here once the bookkeeper issues it (books.create_invoice)." + "An invoice appears here once your assistant creates it." }, ) } else { diff --git a/crates/ledger-gui/src/pages/overview.rs b/crates/ledger-gui/src/pages/overview.rs index 8a19b547..64082619 100644 --- a/crates/ledger-gui/src/pages/overview.rs +++ b/crates/ledger-gui/src/pages/overview.rs @@ -57,7 +57,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { fn headline(b: &Books) -> String { let k = &b.kpis; let Some(first) = k.first_entry else { - return "No transactions yet. Once your agent records some, this page fills in on its own." + return "No transactions yet. Once your assistant records some, this page fills in on its own." .into(); }; let mut s = format!( diff --git a/crates/ledger-gui/src/pages/parties.rs b/crates/ledger-gui/src/pages/parties.rs index 4dde7cb8..f21b7776 100644 --- a/crates/ledger-gui/src/pages/parties.rs +++ b/crates/ledger-gui/src/pages/parties.rs @@ -342,7 +342,7 @@ pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui, icon::ADDRESS_BOOK, "No parties yet", - "Vendors, customers, contractors, and anyone else the company deals with appear here once the bookkeeper adds them.", + "Vendors, customers, contractors, and anyone else the company deals with appear here once your assistant adds them.", ) }); return; diff --git a/crates/ledger-gui/src/pages/projects.rs b/crates/ledger-gui/src/pages/projects.rs index 0978017d..6b837a07 100644 --- a/crates/ledger-gui/src/pages/projects.rs +++ b/crates/ledger-gui/src/pages/projects.rs @@ -129,7 +129,7 @@ pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) { ui, icon::BRIEFCASE, "No projects yet", - "The agent adds them (books.add_project). Tag lines with a project to see what it earns and costs.", + "Your assistant adds them. Tag lines with a project to see what it earns and costs.", ) }); return; diff --git a/crates/ledger-gui/src/pages/reports.rs b/crates/ledger-gui/src/pages/reports.rs index b04fc0e6..c6918e5a 100644 --- a/crates/ledger-gui/src/pages/reports.rs +++ b/crates/ledger-gui/src/pages/reports.rs @@ -1112,7 +1112,7 @@ fn tax(b: &Books, s: NaiveDate, e: NaiveDate) -> Table { /// note saying why, never a guess. fn cant_compute(mut t: Table, why: &ledger_core::LedgerError) -> Table { t.note(format!( - "This report can't be computed: {why}. Ask the bookkeeper to find the record behind it." + "This report can't be computed: {why}. Ask your assistant to find the record behind it." )); t } diff --git a/crates/ledger-gui/src/welcome.rs b/crates/ledger-gui/src/welcome.rs index 9f696671..a03e5954 100644 --- a/crates/ledger-gui/src/welcome.rs +++ b/crates/ledger-gui/src/welcome.rs @@ -161,7 +161,7 @@ impl Welcome { ui.label(RichText::new("Welcome to wanderbooks").font(crate::theme::bold(28.0))); ui.label( RichText::new( - "Your company's books, kept by an agent and checked by you. A few short steps; nothing here needs a terminal.", + "Your company's books, kept by an assistant and checked by you. A few short steps; nothing here needs a terminal.", ) .color(p.muted), ); @@ -241,7 +241,7 @@ impl Welcome { if st.root { ui.label(RichText::new("Made. Only your account can open it.").color(p.muted)); } else { - ui.label("Wanderbooks keeps your books in a folder that only your account can open. Your agent reaches them through the app, never by looking in the folder."); + ui.label("Wanderbooks keeps your books in a folder that only your account can open. Your assistant reaches them through the app, never by looking in the folder."); if ui .add_enabled(!busy, egui::Button::new("Set it up")) .clicked() @@ -334,7 +334,7 @@ impl Welcome { ); return; } - ui.label("A short name for the books: lowercase letters, digits and hyphens (your company's name, say). You can name the company itself afterwards, with your agent."); + ui.label("A short name for the books: lowercase letters, digits and hyphens (your company's name, say). You can name the company itself afterwards, with your assistant."); ui.add_enabled( !busy, egui::TextEdit::singleline(&mut self.id) @@ -370,11 +370,11 @@ impl Welcome { Self::card( ui, 4, - "An agent to keep them", + "An assistant to keep them", agents.iter().any(|(_, r)| r.is_ok()), step4_active, |ui| { - ui.label("An agent (Claude Code or Codex) records your transactions, checks receipts and answers questions, through the books' own tools. This connects it; the app also has a panel along the bottom of its window that runs it for you. You never need either: any agent you run yourself can reach the same books."); + ui.label("An assistant (Claude Code or Codex) records your transactions, checks receipts and answers questions. This connects it; the app also has a panel along the bottom of its window that runs it for you. You never need either: any assistant you run yourself can reach the same books."); for (agent, result) in &agents { match result { Ok(lines) => { @@ -415,7 +415,7 @@ impl Welcome { } } if ui - .add_enabled(!busy, egui::Button::new("I'll use my own agent")) + .add_enabled(!busy, egui::Button::new("I'll use my own assistant")) .clicked() { self.agent_later = true; diff --git a/crates/ledger-gui/src/widgets.rs b/crates/ledger-gui/src/widgets.rs index b2833537..8fa9f309 100644 --- a/crates/ledger-gui/src/widgets.rs +++ b/crates/ledger-gui/src/widgets.rs @@ -518,7 +518,7 @@ pub fn copy_prompt(ui: &mut Ui, prompt: &str) { let label = if recently { format!("{} Copied", egui_phosphor::regular::CHECK) } else { - format!("{} Ask the agent", egui_phosphor::regular::SPARKLE) + format!("{} Ask your assistant", egui_phosphor::regular::SPARKLE) }; let r = ui .add( @@ -532,7 +532,7 @@ pub fn copy_prompt(ui: &mut Ui, prompt: &str) { .corner_radius(CornerRadius::same(6)), ) .on_hover_text(format!( - "Copies this prompt for your agent session:\n\n{prompt}" + "Copies this prompt for your assistant:\n\n{prompt}" )); if r.clicked() { ui.ctx().copy_text(prompt.to_string()); diff --git a/crates/ledger-gui/tests/assets.rs b/crates/ledger-gui/tests/assets.rs index d2403f29..0d3682be 100644 --- a/crates/ledger-gui/tests/assets.rs +++ b/crates/ledger-gui/tests/assets.rs @@ -261,7 +261,7 @@ fn depreciation_due_is_the_register_through_the_last_finished_month() { "{:?}", n[0].text ); - assert!(n[0].text.contains("ask the bookkeeper to run depreciation")); + assert!(n[0].text.contains("ask your assistant to run depreciation")); let accruing = r.unposted_depreciation() - due.amount; assert!(accruing > Decimal::ZERO); assert!(n[1].text.contains(&fmt::dollars(accruing))); @@ -541,7 +541,7 @@ fn basis_figures_are_ledger_cores() { assert_eq!(r.missing_basis, 1); let want = missing_tax_notice(1).unwrap(); assert!(want.starts_with("Tax basis not recorded for 1 asset")); - assert!(want.contains("books.set_asset_tax_basis")); + assert!(want.contains("ask your assistant to record it")); assert!(notices(b, &r).iter().any(|n| n.problem && n.text == want)); assert_eq!(missing_tax_notice(0), None); assert!( From e34b18ec73a77fd35a81d76574a80a378cc529b7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:16:26 -0700 Subject: [PATCH 6/7] feat(gui): one Another assistant card, a popover for Ask your assistant, one Books menu entry The four untested tools shared one text four times: now one card. The copied sentence no longer pushes the page down: a popover under the button. The Books menu's two connect entries became one that opens the Connect page. Link::Working has no glyph (it is a drawn arc). Shape baselines re-blessed: assist_{working,none,connected,connect_page,ask} in light and dark. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/connect.rs | 327 +++++++++--------- crates/ledger-gui/src/connections.rs | 6 +- crates/ledger-gui/src/owner.rs | 34 +- crates/ledger-gui/tests/assistants.rs | 34 +- crates/ledger-gui/tests/owner_menu.rs | 30 +- .../tests/snapshots/assist_ask_dark.shapes | 2 +- .../tests/snapshots/assist_ask_light.shapes | 2 +- .../snapshots/assist_connect_page_dark.shapes | 2 +- .../assist_connect_page_light.shapes | 2 +- .../snapshots/assist_connected_dark.shapes | 2 +- .../snapshots/assist_connected_light.shapes | 2 +- .../tests/snapshots/assist_none_dark.shapes | 2 +- .../tests/snapshots/assist_none_light.shapes | 2 +- .../snapshots/assist_working_dark.shapes | 2 +- .../snapshots/assist_working_light.shapes | 2 +- 15 files changed, 236 insertions(+), 215 deletions(-) diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index c61a670e..9c7c3786 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -234,6 +234,12 @@ pub fn asking_is_offered(ctx: &egui::Context) -> bool { .is_some_and(|c| c.serves) } +/// Ask the window to open the Connect page (the Books menu's "Connect an +/// assistant…"; the same as clicking the link under "Ask your assistant"). +pub fn open_page(ctx: &egui::Context) { + ctx.data_mut(|d| d.insert_temp(go_key(), true)); +} + /// 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())) @@ -257,7 +263,6 @@ pub fn ask_button(ui: &mut Ui, what: &str) { 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)) @@ -273,66 +278,81 @@ pub fn ask_button(ui: &mut Ui, what: &str) { 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)); + ui.ctx() + .data_mut(|d| d.insert_temp(ask_said_key(), (what.to_string(), now, resp.rect))); } 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. +/// What follows a click on "Ask your assistant": a small popover under the +/// button (so nothing on the page moves) saying what was copied and, with +/// no assistant connected, where to connect one. It goes away after a few +/// seconds, or on the next click anywhere else. Drawn by the page header; +/// nothing while the button has not been clicked. pub fn ask_feedback(ui: &mut Ui) { - let Some(c) = ui.ctx().data(|d| d.get_temp::(ask_key())) else { + let ctx = ui.ctx().clone(); + let Some(c) = 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 said: Option<(String, f64, egui::Rect)> = ctx.data(|d| d.get_temp(ask_said_key())); let now = ui.input(|i| i.time); - let Some((what, at)) = said else { return }; + let Some((what, at, button)) = said else { + return; + }; + let forget = || ctx.data_mut(|d| d.remove::<(String, f64, egui::Rect)>(ask_said_key())); if now - at >= 8.0 { - ui.ctx() - .data_mut(|d| d.remove_temp::<(String, f64)>(ask_said_key())); + forget(); 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)); - } + let p = pal(&ctx); + let shown = egui::Area::new(egui::Id::new("wanderbooks-ask-popover")) + .order(egui::Order::Foreground) + .pivot(egui::Align2::RIGHT_TOP) + .fixed_pos(button.right_bottom() + vec2(0.0, 6.0)) + .constrain(true) + .show(&ctx, |ui| { + Frame::popup(ui.style()) + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .show(ui, |ui| { + ui.set_max_width(380.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_wrapped(|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)); + } + }); + } + }); }); + // A click anywhere else puts it away; so does the click on its link. + let rect = shown.response.rect; + let (pressed, at_pos) = ctx.input(|i| (i.pointer.any_pressed(), i.pointer.interact_pos())); + let outside = at_pos.is_some_and(|pos| !rect.contains(pos) && !button.contains(pos)); + if pressed && outside { + forget(); } + ctx.request_repaint_after(std::time::Duration::from_millis(500)); } // ---- the Connect page ------------------------------------------------------- @@ -341,45 +361,25 @@ pub fn ask_feedback(ui: &mut Ui) { 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 agent the owner can connect with one button. + agent: crate::owner::Agent, + /// The words that add it to the tool by hand (before the command), as + /// the tool's own documentation gives them. + add_by_hand: &'static str, } -/// The tools of "On this computer", in the order of plan 3.3. -const TOOLS: [Tool; 6] = [ +/// The tools of "On this computer" that have a button of their own; every +/// other assistant shares the "Another assistant" card. +const TOOLS: [Tool; 2] = [ Tool { name: "Claude Code", - agent: Some(crate::owner::Agent::Claude), - add_by_hand: Some("claude mcp add --scope user"), + agent: crate::owner::Agent::Claude, + add_by_hand: "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, + agent: crate::owner::Agent::Codex, + add_by_hand: "codex mcp add", }, ]; @@ -527,9 +527,7 @@ impl State { want = Some(w); } } - if TOOLS.iter().any(|t| t.agent.is_none()) { - key_row(ui, status, book, &owner, busy, &mut want); - } + another_row(ui, status, book, &owner, &commands, busy, &mut want); if let Some((what, keep, work)) = want { self.start(ui, jobs, what, &keep, work); } @@ -665,7 +663,7 @@ fn tool_row( ); } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if let (Some(agent), Some(owner)) = (tool.agent, owner) + if let (agent, Some(owner)) = (tool.agent, owner) && ui .add_enabled(!busy, egui::Button::new(format!("Connect {}", tool.name))) .on_hover_text(format!( @@ -708,96 +706,113 @@ fn tool_row( 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 - )) + let line = format!("{} {name} -- {bridge}", tool.add_by_hand); + 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), + ); + }); } -/// The step the tools without a button share: the key they read, made once. -fn key_row( +/// The one card for every other assistant: the command, the key it reads +/// (made once), and the names we have not tried. +fn another_row( ui: &mut Ui, status: &Status, book: &str, owner: &Option>, + commands: &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() - } - }) - }), - )); - } + let name = format!("wanderbooks-{book}"); + 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.label(RichText::new("Another assistant").font(theme::semibold(14.5))); + ui.add_space(4.0); + ui.label( + RichText::new(format!( + "Any assistant that can run a local tool (a program it runs on this computer) works. Add one named “{name}”, with this command:" + )) + .font(theme::regular(13.0)) + .color(p.text), + ); + match commands { + Some(Ok(c)) => command_box(ui, &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(2.0); + ui.label( + RichText::new(format!( + "It reads {}'s key, made 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() + } + }) + }), + )); + } + ui.add_space(2.0); + ui.label( + RichText::new( + "Then restart it. We haven't tested Gemini CLI, Grok Build, Muse Code or Cursor yet.", + ) + .font(theme::regular(12.5)) + .color(p.muted), + ); + }); + ui.add_space(6.0); } /// Text in a box, with a Copy button. diff --git a/crates/ledger-gui/src/connections.rs b/crates/ledger-gui/src/connections.rs index 17fd455d..6f458e12 100644 --- a/crates/ledger-gui/src/connections.rs +++ b/crates/ledger-gui/src/connections.rs @@ -63,14 +63,14 @@ pub enum Link { 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). + /// each, so it reads without colour (plugs apart, plugs together; the + /// spinning arc of Working is drawn, so it has no glyph). 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), + Link::Working => None, } } } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 4c98e612..72b2a0d0 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -8,8 +8,8 @@ //! GOAL: the owner backs up, restores, starts new books, closes the books //! and connects an agent from the viewer, without a terminal. //! SOURCE: plan P2 ("Viewer menu (D-19)": "Back up now", "Restore…", -//! "New books…", "Close the books", "Connect Claude Code" and -//! "Connect Codex"; "Nothing in the viewer writes a book"); D-32 +//! "New books…", "Close the books" and "Connect an assistant…"; the +//! page it opens carries the two connect buttons; "Nothing in the viewer writes a book"); D-32 //! (no confinement: the viewer asks the server itself, as the //! command line does); plan 3.9 and D-39 (the format upgrade: the //! go-ahead asked at every open until given, with the owner @@ -709,25 +709,13 @@ impl OwnerMenu { }; } ui.separator(); - for agent in [Agent::Claude, Agent::Codex] { - if ui - .button(format!("{} Connect {}", icon::PLUGS_CONNECTED, agent.label())) - .on_hover_text(format!( - "Let {} reach these books (it keeps their token in a file in the data root)", - agent.label() - )) - .clicked() - { - let (o, b) = (owner.clone(), book.clone()); - start = Some(( - format!("Connect {}", agent.label()), - Effect::Changes(match agent { - Agent::Claude => "Connecting Claude Code to these books", - Agent::Codex => "Connecting Codex to these books", - }), - Box::new(move || o.connect(agent, &b)), - )); - } + if ui + .button(format!("{} Connect an assistant…", icon::PLUGS_CONNECTED)) + .on_hover_text("Open the page that connects Claude Code, Codex or another assistant to these books") + .clicked() + { + crate::connect::open_page(ui.ctx()); + ui.close(); } if let Some(upgrade) = &books.format_upgrade { ui.separator(); @@ -768,7 +756,7 @@ impl OwnerMenu { ui.separator(); if ui .button(format!("{} Close the books", icon::POWER)) - .on_hover_text("Close the books now: agents' sessions and every other holder let go") + .on_hover_text("Close the books now: assistants' sessions and every other holder let go") .clicked() { self.dialog = Dialog::Close; @@ -862,7 +850,7 @@ impl OwnerMenu { Dialog::Close => { egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-close")).show(ctx, |ui| { ui.heading("Close the books?"); - ui.label("Agents' sessions and everything else holding them let go. They open again when something holds them."); + ui.label("Assistants' sessions and everything else holding them let go. They open again when something holds them."); ui.horizontal(|ui| { if ui.button("Close the books").clicked() { let o = owner.clone(); diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 402da3a7..2fcaf7ae 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -487,6 +487,7 @@ fn ask_your_assistant_copies_one_ready_sentence() { refresh(&mut h); h.state_mut().goto(Route::Transactions); h.run_steps(3); + let below = h.get_by_label_contains("recorded, newest first").rect(); h.get_by_role_and_label(Role::Button, "Ask your assistant") .click(); h.step(); @@ -495,6 +496,11 @@ fn ask_your_assistant_copies_one_ready_sentence() { ["In my Wanderbooks books for Wanderland Labs, please record a new transaction."] ); h.run_steps(2); + assert_eq!( + h.get_by_label_contains("recorded, newest first").rect(), + below, + "the feedback is a popover: the page does not move" + ); // With none connected it says so, and where to connect one. assert!( h.query_by_label_contains("No assistant is connected yet.") @@ -568,14 +574,7 @@ fn the_top_bar_state_opens_the_connect_page_which_lists_and_revokes() { 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", - ] { + for tool in ["Claude Code", "Codex", "Another assistant"] { assert!( h.query_all_by_label(tool).next().is_some(), "a row for {tool}" @@ -597,8 +596,8 @@ fn the_top_bar_state_opens_the_connect_page_which_lists_and_revokes() { 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" + 1, + "the program and its arguments, once, on the card for any other assistant" ); h.get_all_by_label("Or do it yourself, in a terminal") .next() @@ -671,6 +670,16 @@ fn the_connect_buttons_do_what_connect_does() { h.query_by_label_contains("Codex reaches the books.") .is_some() ); + until(&mut h, "the page is idle", |a| { + !a.views()[0].connect_state().busy() + }); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Connect Claude Code") + .click(); + h.run_steps(2); + wait_for("connect ran for Claude Code", || { + owner.said().contains(&"connect claude alpha".to_string()) + }); h.get_by_role_and_label(Role::Button, "Make the key") .click(); h.run_steps(2); @@ -1016,5 +1025,10 @@ fn pictures() { // 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}")); + // The Connect page tall enough to show "Another assistant". + let (_w3, mut tall) = three_states(dark, 1, egui::vec2(1440.0, 1300.0)); + tall.state_mut().goto(Route::Connect); + tall.run_steps(4); + save(&mut tall, &format!("9-connect-another-{mode}")); } } diff --git a/crates/ledger-gui/tests/owner_menu.rs b/crates/ledger-gui/tests/owner_menu.rs index 4e2bda08..cbd2ab1f 100644 --- a/crates/ledger-gui/tests/owner_menu.rs +++ b/crates/ledger-gui/tests/owner_menu.rs @@ -181,11 +181,15 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { assert_eq!(f.asked.lock().unwrap()[start], "back up acme"); assert!(h.query_by_label_contains("is its disk connected").is_some()); - // Connect Claude Code. + // Connect an assistant…: opens the Connect page, asks the owner nothing + // (the page's own buttons carry the connecting: tests/assistants.rs). open_menu(&mut h); - h.get_by_label_contains("Connect Claude Code").click(); - settle(&mut h, &f, start + 2); - assert_eq!(f.asked.lock().unwrap()[start + 1], "connect Claude acme"); + h.get_by_label_contains("Connect an assistant…").click(); + h.run_steps(4); + assert_eq!(h.state().route(), &Route::Connect); + assert_eq!(f.asked.lock().unwrap().len(), start + 1); + assert!(h.query_by_label_contains("Connect Claude Code").is_some()); + assert!(h.query_by_label_contains("Connect Codex").is_some()); // New books: asked for, then made. let page_fields = h @@ -205,8 +209,8 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { .type_text("beta"); h.run_steps(2); h.get_by_label("Make them").click(); - settle(&mut h, &f, start + 3); - assert_eq!(f.asked.lock().unwrap()[start + 2], "new beta USD"); + settle(&mut h, &f, start + 2); + assert_eq!(f.asked.lock().unwrap()[start + 1], "new beta USD"); // Restore: previewed (the backup checked), then done for that plan. open_menu(&mut h); @@ -227,9 +231,9 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { "not before it is checked" ); h.get_by_label("Check it").click(); - settle(&mut h, &f, start + 4); + settle(&mut h, &f, start + 3); assert_eq!( - f.asked.lock().unwrap()[start + 3], + f.asked.lock().unwrap()[start + 2], "plan /media/disk/acme.git None false" ); assert!( @@ -237,9 +241,9 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { .is_some() ); h.get_by_label("Restore it").click(); - settle(&mut h, &f, start + 5); + settle(&mut h, &f, start + 4); assert_eq!( - f.asked.lock().unwrap()[start + 4], + f.asked.lock().unwrap()[start + 3], "restore /media/disk/acme.git acme 7" ); @@ -249,13 +253,13 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { h.run_steps(3); h.get_by_label("Cancel").click(); h.run_steps(3); - assert_eq!(f.asked.lock().unwrap().len(), start + 5); + assert_eq!(f.asked.lock().unwrap().len(), start + 4); open_menu(&mut h); h.get_by_label_contains("Close the books").click(); h.run_steps(3); h.get_by_label("Close the books").click(); - settle(&mut h, &f, start + 6); - assert_eq!(f.asked.lock().unwrap()[start + 5], "close"); + settle(&mut h, &f, start + 5); + assert_eq!(f.asked.lock().unwrap()[start + 4], "close"); // The viewer wrote nothing of the books. drop(h); diff --git a/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes index 4dad9afc..26bbef66 100644 --- a/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_ask_dark.shapes @@ -1 +1 @@ -554a45de5050b79d +d4672239e98f338e diff --git a/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes b/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes index 8f6ab98b..6b64c70b 100644 --- a/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_ask_light.shapes @@ -1 +1 @@ -fffc3e5adaa00db0 +47a1f842b40cdf15 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes index b596b6df..e58c6ce9 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes @@ -1 +1 @@ -e8b3ce383a13c776 +2abd53e6457106f8 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes index 7c77cfb2..26abeaee 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes @@ -1 +1 @@ -3271d551e50db504 +b990ac9586df492a diff --git a/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes index c01b28ef..60526284 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connected_dark.shapes @@ -1 +1 @@ -9530691dfcdedf6b +6642f21a3644e1f4 diff --git a/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes index fd637ecd..11080e00 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connected_light.shapes @@ -1 +1 @@ -5f60b24231b7a370 +e425621386ec002f diff --git a/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes index 54873482..aead0299 100644 --- a/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_none_dark.shapes @@ -1 +1 @@ -9bc7803073cd0434 +79ee857f24de8131 diff --git a/crates/ledger-gui/tests/snapshots/assist_none_light.shapes b/crates/ledger-gui/tests/snapshots/assist_none_light.shapes index 68a78c2f..235d24dd 100644 --- a/crates/ledger-gui/tests/snapshots/assist_none_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_none_light.shapes @@ -1 +1 @@ -fea19947b5c1a09e +d236cd60218a8061 diff --git a/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes index 1ab2b0bb..9f937324 100644 --- a/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_working_dark.shapes @@ -1 +1 @@ -334251b6f2666663 +8d565039aff8c64c diff --git a/crates/ledger-gui/tests/snapshots/assist_working_light.shapes b/crates/ledger-gui/tests/snapshots/assist_working_light.shapes index a32351a4..35adc9df 100644 --- a/crates/ledger-gui/tests/snapshots/assist_working_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_working_light.shapes @@ -1 +1 @@ -31ed42032e1844c9 +7014f0d713dbc1d8 From fd847701e84dd623934f42a0422a181cc6d84be0 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:23:11 -0700 Subject: [PATCH 7/7] fix(host,gui): the Connect page's keys: never replaced, no admin, revoked by id, a quoted command, a leftover file said Make the key asks the server first and never replaces: a live key whose copy is missing here may be in use, so it is said in words and left alone. A page-made key carries read, write and post, not admin (the connect command keeps its scopes). Revoke names the key's id, so a stale row cannot end a newer key of the same name; a revoke that leaves the token file says the key is dead and where the file is. The copyable command is single-quoted for a POSIX shell and PowerShell, and refused when cmd.exe would act on a part. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 13 +- crates/ledger-cli/tests/app_server.rs | 185 ++++++++++++++++++++- crates/ledger-gui/src/connect.rs | 25 +-- crates/ledger-gui/src/owner.rs | 17 +- crates/ledger-gui/tests/assistants.rs | 3 +- crates/ledger-host/src/app_server.rs | 49 ++++-- crates/ledger-host/src/commands.rs | 210 +++++++++++++++++++++--- crates/ledger-host/tests/shell_quote.rs | 141 ++++++++++++++++ 8 files changed, 588 insertions(+), 55 deletions(-) create mode 100644 crates/ledger-host/tests/shell_quote.rs diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index ba57781c..3a6bfb9e 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -142,6 +142,7 @@ impl ledger_gui::owner::Owner for ViewerOwner { .tokens .into_iter() .map(|t| TokenRow { + id: t.id, book: t.book, name: t.name, scopes: t.scopes, @@ -151,8 +152,8 @@ impl ledger_gui::owner::Owner for ViewerOwner { Ok(Roster { assistants, tokens }) } - fn serve_revoke(&self, book: &str, name: &str) -> Result { - self.server.revoke_token(book, name) + fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result { + self.server.revoke_token(book, name, id) } fn command_line(&self, words: &[&str]) -> Result { @@ -160,7 +161,13 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn make_key(&self, book: &str) -> Result { - ledger_host::commands::ensure_key(&self.common, book) + use ledger_store::auth::Scope; + // What a page-made key may do: read, draft and post; never admin. + ledger_host::commands::ensure_key( + &self.common, + book, + &[Scope::Read, Scope::Write, Scope::Post], + ) } fn close_books(&self) -> Result { diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index a3f0be0d..54f2e796 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -766,7 +766,13 @@ fn the_roster_lists_a_connected_key_and_revoking_it_ends_its_use() { assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*token)); // Revoked: said in words, and no longer usable. - let said = server.revoke_token(BOOK, "agent").unwrap(); + let id = roster + .tokens + .iter() + .find(|t| t.book == BOOK && t.name == "agent") + .map(|t| t.id.clone()) + .unwrap(); + let said = server.revoke_token(BOOK, "agent", &id).unwrap(); assert!(said.contains("access"), "{said}"); // (a) the roster no longer lists the key, nor a session on it, let after = server.roster(Duration::from_secs(30)).unwrap(); @@ -787,6 +793,181 @@ fn the_roster_lists_a_connected_key_and_revoking_it_ends_its_use() { // (c) and the token file's copy is gone. assert_eq!(keeper.get(&account).unwrap(), None); // Asking again for a key that is gone says so, and breaks nothing. - assert!(server.revoke_token(BOOK, "agent").is_err()); + assert!(server.revoke_token(BOOK, "agent", &id).is_err()); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} + +/// The host's own `Common` on `home`'s root: what the window's owner holds. +fn common_on(home: &Home) -> ledger_host::commands::Common { + ledger_host::commands::Common { + root: Some(home.root()), + ..Default::default() + } +} + +/// The id of the live key `agent` of `BOOK`, by the roster. +fn key_id(server: &AppServer) -> Option { + server + .roster(Duration::from_secs(30)) + .unwrap() + .tokens + .iter() + .find(|t| t.book == BOOK && t.name == "agent") + .map(|t| t.id.clone()) +} + +/// The scopes of the live key `agent` of `BOOK`, by the roster. +fn key_scopes(server: &AppServer) -> Vec { + server + .roster(Duration::from_secs(30)) + .unwrap() + .tokens + .iter() + .find(|t| t.book == BOOK && t.name == "agent") + .map(|t| t.scopes.clone()) + .unwrap() +} + +/// "Make the key" (the Connect page) makes the key once, with read, write +/// and post and no admin; a second click, or a click with the copy here +/// gone, replaces nothing and says why in words; a revoke of a row whose +/// key was since replaced ends nothing. +#[test] +fn make_the_key_never_replaces_a_key_and_a_stale_revoke_ends_nothing() { + use ledger_store::auth::Scope; + let scopes = [Scope::Read, Scope::Write, Scope::Post]; + let home = Home::new("app-make-key"); + let run = home.run(); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + home.create(BOOK, "USD"); + assert_eq!(server.open_book(BOOK), Ok(None)); + let common = common_on(&home); + let account = ledger_host::tokens::Account::new(&home.root(), BOOK, "agent"); + let keeper = ledger_host::tokens::keeper(&run); + + // Made once, and kept; read, write and post, not admin. + assert_eq!( + ledger_host::commands::ensure_key(&common, BOOK, &scopes), + Ok(true) + ); + let first = key_id(&server).expect("the key was made"); + let text = keeper.get(&account).unwrap().expect("its copy is kept"); + assert_eq!( + key_scopes(&server), + ["books:read", "books:write", "books:post"] + ); + + // A second click: nothing is made, nothing replaced. + assert_eq!( + ledger_host::commands::ensure_key(&common, BOOK, &scopes), + Ok(false) + ); + assert_eq!(key_id(&server).as_deref(), Some(first.as_str())); + assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*text)); + + // The key works for ordinary bookkeeping and is refused an admin call. + let mut bridge = Bridge::start(&home); + assert!(bridge.initialize().get("error").is_none()); + let read = bridge.start_call(); + assert!( + read.get("error").is_none() && read["result"]["isError"] != json!(true), + "{read}" + ); + let admin = bridge.ask( + "tools/call", + json!({"name": "books.access_log", "arguments": {}}), + ); + let refused = admin.get("error").is_some() || admin["result"]["isError"] == json!(true); + assert!(refused, "an admin call must be refused: {admin}"); + assert!( + admin.to_string().contains("books:admin"), + "it is refused for want of admin: {admin}" + ); + + // The copy here goes missing while the key lives (an assistant may be + // using it): said in words, and nothing is replaced. + keeper.delete(&account).unwrap(); + let said = ledger_host::commands::ensure_key(&common, BOOK, &scopes).unwrap_err(); + assert!( + said.contains("already exists") && said.contains("revoke it"), + "{said}" + ); + assert!(!said.contains(&*text), "never the key's text"); + assert_eq!(key_id(&server).as_deref(), Some(first.as_str())); + assert_eq!(keeper.get(&account).unwrap(), None, "no copy was made"); + // The assistant already using the key is not cut off. + let still = bridge.start_call(); + assert!(still.get("error").is_none(), "{still}"); + + // The same when the copy here is not the live key's text. + keeper.set(&account, "wb_not_the_key").unwrap(); + let said = ledger_host::commands::ensure_key(&common, BOOK, &scopes).unwrap_err(); + assert!(said.contains("not its text any more"), "{said}"); + assert_eq!(key_id(&server).as_deref(), Some(first.as_str())); + + // The key is made again elsewhere (a row of the old one is on screen): + // revoking the old row's id ends nothing, and says why. + let newer_text = home.token_with(BOOK, "agent", &["read", "write", "post"]); + keeper.set(&account, &newer_text).unwrap(); + let newer = key_id(&server).unwrap(); + assert_ne!(newer, first); + let said = server.revoke_token(BOOK, "agent", &first).unwrap_err(); + assert!(said.contains("already replaced or revoked"), "{said}"); + assert_eq!(key_id(&server).as_deref(), Some(newer.as_str())); + assert_eq!( + keeper.get(&account).unwrap().as_deref(), + Some(newer_text.as_str()), + "the newer key's copy stays" + ); + // Its own id ends it. + assert!(server.revoke_token(BOOK, "agent", &newer).is_ok()); + assert_eq!(key_id(&server), None); + assert_eq!(keeper.get(&account).unwrap(), None); + drop(bridge); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} + +/// A key ended whose token file copy cannot be deleted is not reported as +/// done: the words say the key is dead and where the file is, and never +/// hold the file's text. +#[cfg(unix)] +#[test] +fn a_revoke_that_leaves_the_token_file_says_so() { + use std::os::unix::fs::PermissionsExt; + // SAFETY: geteuid has no preconditions. + if unsafe { libc::geteuid() } == 0 { + return; // root deletes in a read-only folder: nothing to show + } + let home = Home::new("app-revoke-left"); + let run = home.run(); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + home.create(BOOK, "USD"); + assert_eq!(server.open_book(BOOK), Ok(None)); + let token = home.token_with(BOOK, "agent", &["read"]); + let account = ledger_host::tokens::Account::new(&home.root(), BOOK, "agent"); + let keeper = ledger_host::tokens::keeper(&run); + keeper.set(&account, &token).unwrap(); + let id = key_id(&server).unwrap(); + let folder = run.join("tokens"); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o500)).unwrap(); + let result = server.revoke_token(BOOK, "agent", &id); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o700)).unwrap(); + let said = result.unwrap_err(); + assert!(said.contains("key is dead"), "{said}"); + assert!(said.contains("a file with its text remains at"), "{said}"); + assert!( + said.contains( + &ledger_host::commands::token_file_path(&run, BOOK, "agent") + .display() + .to_string() + ), + "{said}" + ); + assert!(!said.contains(&*token), "never the file's text"); + // The key is dead all the same. + assert_eq!(key_id(&server), None); + assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*token)); assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); } diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 9c7c3786..ee75922a 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -442,7 +442,9 @@ impl State { if let Some((what, rx)) = &self.job && let Ok(result) = rx.try_recv() { - if what.starts_with("Revoke") && result.is_ok() { + // Whatever came of it (a key already gone, a file left behind), + // the list is read again. + if what.starts_with("Revoke") { self.refresh = true; } self.done = Some((what.clone(), result)); @@ -587,7 +589,7 @@ impl State { ); return; } - let mut revoke: Option = None; + let mut revoke: Option<(String, String)> = None; for row in &rows { Frame::new() .fill(p.surface) @@ -608,7 +610,7 @@ impl State { }); ui.add_space(6.0); } - if let (Some(name), Some(owner)) = (revoke, owner.clone()) { + if let (Some((name, id)), Some(owner)) = (revoke, owner.clone()) { self.confirm = None; let b = book.to_string(); self.start( @@ -616,7 +618,7 @@ impl State { jobs, format!("Revoke {name}"), "Ending an assistant's access", - Box::new(move || owner.serve_revoke(&b, &name)), + Box::new(move || owner.serve_revoke(&b, &name, &id)), ); } } @@ -795,7 +797,7 @@ fn another_row( Box::new(move || { o.make_key(&b).map(|made| { if made { - "made, and kept on this computer.".to_string() + "made, and kept on this computer. It can read the books, draft entries and post them; it cannot see the access record.".to_string() } else { "it was already made.".to_string() } @@ -851,7 +853,7 @@ fn connection_row( row: &Connection<'_>, status: &Status, confirm: &mut Option, - revoke: &mut Option, + revoke: &mut Option<(String, String)>, busy: bool, can_revoke: bool, ) { @@ -887,12 +889,12 @@ fn connection_row( if !can_revoke { return; } - if confirm.as_deref() == Some(t.name.as_str()) { + if confirm.as_deref() == Some(t.id.as_str()) { if ui .add_enabled(!busy, egui::Button::new("Yes, revoke")) .clicked() { - *revoke = Some(t.name.clone()); + *revoke = Some((t.name.clone(), t.id.clone())); } if ui.button("Keep it").clicked() { *confirm = None; @@ -902,11 +904,14 @@ fn connection_row( .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()); + *confirm = Some(t.id.clone()); } }); }); - if confirm.as_deref() == Some(row.name.as_str()) { + if row + .token + .is_some_and(|t| confirm.as_deref() == Some(t.id.as_str())) + { ui.label( RichText::new(format!( "Revoke the key “{}”? Anything using it is cut off now; {}'s books are not changed.", diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 72b2a0d0..64d4b096 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -190,6 +190,9 @@ pub struct Assistant { /// A token, as listed: who may connect to a company (never its text). #[derive(Clone, Debug, PartialEq, Eq)] pub struct TokenRow { + /// Its id: what a revoke names, so a row of a key since replaced + /// cannot end the new one. + pub id: String, /// The company it opens. pub book: String, /// Its name. @@ -262,9 +265,11 @@ pub trait Owner: Send + Sync { fn serve_roster(&self) -> Result { Ok(Roster::default()) } - /// End the token `name` of the company `book` (what `wanderbooks token - /// revoke` does): `Ok` says what was done, in words. Blocks. - fn serve_revoke(&self, _book: &str, _name: &str) -> Result { + /// End the token `name`, whose id is `id`, of the company `book` (what + /// `wanderbooks token revoke` does, for that one key): `Ok` says what + /// was done, in words; a key already replaced or revoked is an `Err` + /// that says so. Blocks. + fn serve_revoke(&self, _book: &str, _name: &str, _id: &str) -> Result { Err("not here".into()) } /// This program run with `words`, as a line to type in a terminal (the @@ -274,8 +279,10 @@ pub trait Owner: Send + Sync { Err("not here".into()) } /// The key an assistant needs to reach the company `book` exists (made - /// now if it did not): `Ok(true)` when it was made now. What `connect` - /// does first, for an assistant set up by hand. Blocks. + /// now if it did not), able to read, draft and post but not to see the + /// access record: `Ok(true)` when it was made now. It never replaces a + /// key: one that exists with no copy here is an `Err` that says so. + /// Blocks. fn make_key(&self, _book: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 2fcaf7ae..28ba5ceb 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -187,7 +187,7 @@ impl Owner for Fake { .clone() .unwrap_or_else(|| Ok(Roster::default())) } - fn serve_revoke(&self, book: &str, name: &str) -> Result { + fn serve_revoke(&self, book: &str, name: &str, _id: &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)); @@ -246,6 +246,7 @@ fn session(book: &str, token: &str, program: &str, running: u32, last: Option<&s fn token(book: &str, name: &str) -> TokenRow { TokenRow { + id: format!("tok_{book}_{name}"), book: book.into(), name: name.into(), scopes: ["books:read", "books:write", "books:post"] diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index bd036ea5..91b30fd8 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -419,29 +419,50 @@ impl AppServer { Ok(Roster { sessions, tokens }) } - /// End the token `name` of the company `book`, as `wanderbooks token - /// revoke` does (INVARIANT 12): the server ends the token and the - /// sessions it opened, and the token file's copy is removed. `Ok` says - /// what was done, in words; a token file that could not be cleaned is - /// said, and the token is revoked all the same. - pub fn revoke_token(&self, book: &str, name: &str) -> Result { + /// End the key `id`, named `name`, of the company `book`, as + /// `wanderbooks token revoke` does (INVARIANT 12): the server ends that + /// key and the sessions it opened, and the token file's copy is + /// removed. It goes by the key's id, never its name alone: a row that + /// shows a key since replaced must not end the new one. `Ok` says what + /// was done, in words. When the key is ended but the token file's copy + /// cannot be deleted, that is an `Err` that says so (the key is dead; a + /// file holding its text remains at that path), never its text. + pub fn revoke_token(&self, book: &str, name: &str, id: &str) -> Result { self.wait_ready(READY_WAIT)?; let request = Request::TokenRevoke { book: book.into(), name: name.into(), - id: None, + id: Some(id.into()), }; match self.ask_raw(request, Some(Duration::from_secs(30))) { Ok(Response::TokenRevoked(t)) => { let said = format!("Ended {:?}'s access to {}.", t.name, t.book); match crate::commands::forget_token_file(&self.run, book, name) { Ok(()) => Ok(said), - Err(why) => Ok(format!( - "{said} Its token file still holds its text ({why}); it opens nothing now." - )), + Err(why) => { + let at = crate::commands::token_file_path(&self.run, book, name); + Err(format!( + "{said} The key is dead and opens nothing now. But the copy of its text kept on this computer could not be deleted ({why}); a file with its text remains at {}. Delete that file yourself.", + at.display() + )) + } } } - Ok(Response::Refused(why)) => Err(why), + Ok(Response::Refused(why)) => { + // Refused because that key is gone (replaced or revoked + // since the row was read), or for another reason. + let gone = matches!( + self.ask_raw(Request::TokenList, Some(Duration::from_secs(10))), + Ok(Response::Tokens(list)) if !list.iter().any(|t| t.id == id) + ); + Err(if gone { + format!( + "This key was already replaced or revoked, so nothing was ended. The list now shows the keys of {book} as they stand." + ) + } else { + why + }) + } Ok(other) => Err(format!("the books server answered oddly: {other:?}")), Err(e) => Err(e.to_string()), } @@ -697,9 +718,9 @@ impl AppHost { self.running()?.roster(wait) } - /// End a token (INVARIANT 12). - pub fn revoke_token(&self, book: &str, name: &str) -> Result { - self.running()?.revoke_token(book, name) + /// End the key `id` (INVARIANT 12). + pub fn revoke_token(&self, book: &str, name: &str, id: &str) -> Result { + self.running()?.revoke_token(book, name, id) } /// The format upgrade of the company `id` (INVARIANT 10). diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 278055eb..eb2c74a5 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1435,27 +1435,189 @@ pub fn bridge_serve_args(common: &Common, book: &str) -> Result Result { - Ok(program_args(common, words)? - .iter() - .map(|a| { - let a = a.to_string_lossy(); - if a.contains(char::is_whitespace) { - format!("\"{a}\"") - } else { - a.into_owned() - } - }) - .collect::>() - .join(" ")) +/// Whether `c` may stand in a shell word unquoted, in a POSIX shell. +fn unix_plain(c: char) -> bool { + c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c) } -/// The default token of the books `book` exists and its copy is in the token -/// file (made now if it is not): what `connect` does first. `Ok(true)` when -/// it was made now. -pub fn ensure_key(common: &Common, book: &str) -> Result { +/// `part` as one word of a POSIX shell line (sh, bash, zsh, fish): left as +/// it is when every character is plain, else in single quotes, in which +/// nothing is special but `'` itself, written `'\''`. +pub fn quote_unix(part: &str) -> String { + if !part.is_empty() && part.chars().all(unix_plain) { + return part.to_string(); + } + format!("'{}'", part.replace('\'', "'\\''")) +} + +/// `part` as one word of a Windows line: left as it is when every +/// character is plain (the same in PowerShell and in cmd.exe), else in +/// PowerShell's single quotes (a `'`, and the curly quotes PowerShell +/// reads as one, doubled). Single quotes mean nothing to cmd.exe, so a +/// part that needs them and holds a character cmd.exe acts on (`&`, `|`, +/// `<`, `>`, `^`, `%`, `"`, `!`, or a control character) is refused: +/// pasted into cmd.exe it could run something else. Returns the word and +/// whether it was quoted. +pub fn quote_windows(part: &str) -> Result<(String, bool), String> { + let plain = |c: char| c.is_ascii_alphanumeric() || "_@+:./\\-".contains(c); + if !part.is_empty() && part.chars().all(plain) { + return Ok((part.to_string(), false)); + } + if let Some(bad) = part + .chars() + .find(|c| c.is_control() || "&|<>^%\"!".contains(*c)) + { + return Err(format!( + "a folder or file name on the way to the program holds the character {bad:?}, which cannot be written in a line that is safe to paste into both PowerShell and cmd.exe: move the program to a folder without it" + )); + } + let doubled: String = part + .chars() + .flat_map(|c| { + let twice = matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}'); + std::iter::repeat_n(c, if twice { 2 } else { 1 }) + }) + .collect(); + Ok((format!("'{doubled}'"), true)) +} + +/// `parts` as one line to paste in a terminal: for a POSIX shell, or (with +/// `windows`) for PowerShell (plain parts only: cmd.exe too). A line with +/// a quoted program in PowerShell starts with `&`, which cmd.exe does not +/// take: such a line is for PowerShell alone (it fails in cmd.exe, it +/// never runs another program, see `quote_windows`). +pub fn shell_line(parts: &[String], windows: bool) -> Result { + if !windows { + return Ok(parts + .iter() + .map(|p| quote_unix(p)) + .collect::>() + .join(" ")); + } + let mut words = Vec::new(); + for (i, p) in parts.iter().enumerate() { + let (word, quoted) = quote_windows(p)?; + words.push(if i == 0 && quoted { + format!("& {word}") + } else { + word + }); + } + Ok(words.join(" ")) +} + +/// This program run with `words`, as a line to paste in a terminal, quoted +/// so that it runs as it reads (`shell_line`). A part that is not valid +/// text is an error, never a guess. +pub fn command_line(common: &Common, words: &[&str]) -> Result { + let parts = program_args(common, words)? + .into_iter() + .map(|a| { + a.into_string().map_err(|_| { + "a folder or file name on the way to the program is not valid text, so no command can be shown for it" + .to_string() + }) + }) + .collect::, String>>()?; + shell_line(&parts, cfg!(windows)) +} + +/// Why a key that lives on the server cannot be handed out from this +/// computer: said in words (INVARIANT 7: nothing is replaced). +fn key_in_use(book: &str, name: &str, why: KeyState) -> String { + match why { + KeyState::CopyMissing => format!( + "A key called “{name}” for {book} already exists, but its copy is not on this computer, so it cannot be handed to an assistant from here. It may be in use by an assistant now, so nothing was changed. To start over, revoke it under “Who can reach these books” and make the key again." + ), + _ => format!( + "A key called “{name}” for {book} already exists, but the copy on this computer is not its text any more (it was made again elsewhere). Nothing was changed. To start over, revoke it under “Who can reach these books” and make the key again." + ), + } +} + +/// How the default key of a company stands. +#[derive(Clone, Copy, PartialEq, Eq)] +enum KeyState { + /// No live key of that name. + Absent, + /// A live key, and this computer holds its text. + Kept, + /// A live key, and this computer holds no copy. + CopyMissing, + /// A live key, and the copy here is not its text. + CopyStale, +} + +/// Ask the server whether the key `account` names is live, and whether +/// the copy in the token file is its text. +fn key_state( + common: &Common, + keeper: &crate::tokens::Keeper, + account: &crate::tokens::Account, + book: &str, +) -> Result { + let copy = keeper.get(account)?; + let sha256 = copy + .as_deref() + .map(|t| ledger_store::journal::sha256_hex(t.as_bytes())) + .unwrap_or_default(); + let request = Request::TokenCheck { + book: book.to_string(), + name: crate::tokens::DEFAULT_NAME.to_string(), + sha256, + }; + match with_server(common, request)? { + Response::TokenChecked { live: None, .. } => Ok(KeyState::Absent), + Response::TokenChecked { matches: true, .. } => Ok(KeyState::Kept), + Response::TokenChecked { .. } if copy.is_none() => Ok(KeyState::CopyMissing), + Response::TokenChecked { .. } => Ok(KeyState::CopyStale), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } +} + +/// The default key of the books `book` exists, with `scopes`, and its copy +/// is in the token file (made now if there is none): what the window's +/// "Make the key" does. `Ok(true)` when it was made now, `Ok(false)` when +/// it was there already. It never replaces a key (INVARIANT 7): a live key +/// whose copy is missing here may be in use by an assistant, so that is an +/// `Err` that says what to do, and nothing changes. +pub fn ensure_key( + common: &Common, + book: &str, + scopes: &[ledger_store::auth::Scope], +) -> Result { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + let found = + ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + let account = crate::tokens::Account::new(found.path(), &book, crate::tokens::DEFAULT_NAME); + let keeper = crate::tokens::keeper(&run); + let name = crate::tokens::DEFAULT_NAME; + match key_state(common, &keeper, &account, &book)? { + KeyState::Kept => return Ok(false), + KeyState::Absent => {} + other => return Err(key_in_use(&book, name, other)), + } + let scopes: Vec = scopes.iter().map(|s| s.as_str().to_string()).collect(); + match make_token(common, &book, name, scopes, false) { + Ok(_) => Ok(true), + Err(why) => match key_state(common, &keeper, &account, &book) { + // Another window made it between the question and the make: + // theirs stands, and this one made nothing. + Ok(KeyState::Kept) => Ok(false), + Ok(KeyState::Absent) | Err(_) => Err(why), + Ok(other) => Err(key_in_use(&book, name, other)), + }, + } +} + +/// What `connect` does first: the default key's copy is in the token file, +/// or the key is made again with every scope (replacing a live key whose +/// copy is missing: the owner asked to connect an agent here). +fn ensure_agent_key(common: &Common, book: &str) -> Result { let book = ledger_store::root::BookId::parse(book) .map_err(|e| e.to_string())? .to_string(); @@ -1474,6 +1636,14 @@ pub fn ensure_key(common: &Common, book: &str) -> Result { Ok(true) } +/// Where the token file copy of the token `name` of `book` is kept +/// (`run_dir` is the root's `run/` folder). +pub fn token_file_path(run_dir: &Path, book: &str, name: &str) -> PathBuf { + let root = run_dir.parent().unwrap_or(run_dir).to_path_buf(); + let account = crate::tokens::Account::new(&root, book, name); + crate::tokens::keeper(run_dir).file(&account) +} + /// A revoked token's copy in the token file goes with it (what `token /// revoke` does after the server has ended the token). `run_dir` is the /// root's `run/` folder. @@ -1506,7 +1676,7 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result Vec { + let out = Command::new("sh") + .arg("-c") + .arg(format!("printf '%s\\0' {line}")) + .output() + .expect("sh runs"); + assert!(out.status.success(), "sh refused: {line}"); + let mut words: Vec = out + .stdout + .split(|b| *b == 0) + .map(|w| String::from_utf8(w.to_vec()).unwrap()) + .collect(); + assert_eq!(words.pop().as_deref(), Some(""), "ends with a NUL"); + words +} + +/// A small deterministic generator (no extra dependency). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } +} + +/// Random text weighted to what a shell cares about. +fn random_part(rng: &mut Rng) -> String { + const SPECIAL: &[char] = &[ + ' ', '\t', '\n', '$', '`', ';', '&', '|', '<', '>', '(', ')', '{', '}', '[', ']', '*', '?', + '~', '#', '!', '\'', '"', '\\', '%', '^', '=', ',', ':', '/', '.', '-', '_', '+', '@', 'a', + 'Z', '0', 'é', '日', '😀', + ]; + let len = (rng.next() % 14) as usize; + (0..len) + .map(|_| SPECIAL[(rng.next() % SPECIAL.len() as u64) as usize]) + .collect() +} + +#[cfg(unix)] +#[test] +fn a_posix_shell_reads_back_exactly_the_parts_whatever_they_hold() { + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + for _ in 0..150 { + let n = 1 + (rng.next() % 4) as usize; + let parts: Vec = (0..n).map(|_| random_part(&mut rng)).collect(); + let line = shell_line(&parts, false).unwrap(); + assert_eq!(sh_words(&line), parts, "line: {line}"); + } + // The ones that bite, by name. + for part in [ + "/home/a b/$HOME/`id`/;rm -rf x/&|'q'\"", + "it's", + "''", + "", + "-", + "a\nb", + "~/x", + "*", + ] { + let parts = vec![part.to_string(), "mcp".to_string()]; + let line = shell_line(&parts, false).unwrap(); + assert_eq!(sh_words(&line), parts, "line: {line}"); + } +} + +#[test] +fn plain_parts_are_left_as_they_are() { + assert_eq!(quote_unix("mcp"), "mcp"); + assert_eq!( + quote_unix("/opt/wander-books/bin_1.2/x@y:z,w=1+2%3"), + "/opt/wander-books/bin_1.2/x@y:z,w=1+2%3" + ); + assert_eq!(quote_unix("a b"), "'a b'"); + assert_eq!(quote_unix("it's"), "'it'\\''s'"); + assert_eq!(quote_unix(""), "''"); + let line = shell_line( + &[ + "/opt/wb".into(), + "mcp".into(), + "--book".into(), + "acme".into(), + ], + false, + ); + assert_eq!(line.unwrap(), "/opt/wb mcp --book acme"); +} + +#[test] +fn powershell_quoting_doubles_quotes_and_refuses_what_cmd_would_act_on() { + // Plain: the same line in PowerShell and cmd.exe. + let plain = shell_line(&["C:\\wb\\wanderbooks.exe".into(), "mcp".into()], true).unwrap(); + assert_eq!(plain, "C:\\wb\\wanderbooks.exe mcp"); + // A space: PowerShell's single quotes, and `&` to run a quoted program. + let spaced = shell_line(&["C:\\Program Files\\wb\\x.exe".into(), "mcp".into()], true).unwrap(); + assert_eq!(spaced, "& 'C:\\Program Files\\wb\\x.exe' mcp"); + // A quote is doubled (also the curly ones PowerShell reads as quotes). + assert_eq!(quote_windows("it's").unwrap(), ("'it''s'".into(), true)); + assert_eq!( + quote_windows("a\u{2019}b").unwrap(), + ("'a\u{2019}\u{2019}b'".into(), true) + ); + // `$` and a backtick are literal in single quotes. + assert_eq!(quote_windows("$x`y").unwrap(), ("'$x`y'".into(), true)); + // What cmd.exe acts on: refused, in words. + for bad in [ + "a&b", "a|b", "ab", "a^b", "50%", "a\"b", "hi!", "a\nb", + ] { + let why = quote_windows(bad).unwrap_err(); + assert!(why.contains("cmd.exe"), "{bad}: {why}"); + assert!(shell_line(&[bad.to_string()], true).is_err()); + } +}