Merge branch 't3/p15-a4-connect-page': connection states, Ask your assistant, the Connect page (P15 A4)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:23:35 -07:00
commit c3efb6b301
46 files changed
+4085 -149

No files matched your search

+54
View File
@@ -116,6 +116,60 @@ impl ledger_gui::owner::Owner for ViewerOwner {
self.server.exited()
}
fn serve_roster(&self) -> Result<ledger_gui::owner::Roster, String> {
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 {
id: t.id,
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, id: &str) -> Result<String, String> {
self.server.revoke_token(book, name, id)
}
fn command_line(&self, words: &[&str]) -> Result<String, String> {
ledger_host::commands::command_line(&self.common, words)
}
fn make_key(&self, book: &str) -> Result<bool, String> {
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<String, String> {
ledger_host::commands::close_books(&self.common)
}
+257
View File
@@ -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,257 @@ 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 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();
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", &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<String> {
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<String> {
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);
}
+278 -14
View File
@@ -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<String>,
/// 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<chrono::DateTime<chrono::Utc>>,
}
/// 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<chrono::Utc> {
self.fixed_now.unwrap_or_else(chrono::Utc::now)
}
/// Fix "now" (tests and screenshots).
pub fn set_now(&mut self, now: chrono::DateTime<chrono::Utc>) {
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<Status> = 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<Status> = 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<Tab> = 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),
+87 -14
View File
@@ -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<String>,
/// 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<R>(
}
}
/// 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
+931
View File
@@ -0,0 +1,931 @@
//! 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<egui::Pos2> = (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::<AskContext>(ask_key()))
.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::<bool>(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::<AskContext>(ask_key())) else {
return;
};
if !c.serves {
return;
}
let p = pal(ui.ctx());
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(ask_said_key(), (what.to_string(), now, resp.rect)));
}
resp.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Ask your assistant")
});
}
fn ask_said_key() -> egui::Id {
egui::Id::new("wanderbooks-ask-said")
}
/// 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 ctx = ui.ctx().clone();
let Some(c) = ctx.data(|d| d.get_temp::<AskContext>(ask_key())) else {
return;
};
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, button)) = said else {
return;
};
let forget = || ctx.data_mut(|d| d.remove::<(String, f64, egui::Rect)>(ask_said_key()));
if now - at >= 8.0 {
forget();
return;
}
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 -------------------------------------------------------
/// A tool the page has a row for.
struct Tool {
/// Its name.
name: &'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" that have a button of their own; every
/// other assistant shares the "Another assistant" card.
const TOOLS: [Tool; 2] = [
Tool {
name: "Claude Code",
agent: crate::owner::Agent::Claude,
add_by_hand: "claude mcp add --scope user",
},
Tool {
name: "Codex",
agent: crate::owner::Agent::Codex,
add_by_hand: "codex mcp add",
},
];
type Outcome = Result<String, String>;
/// 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<Commands, String>)>,
/// A job under way: what it is, and its answer.
job: Option<(String, Receiver<Outcome>)>,
/// What the last job said.
done: Option<(String, Outcome)>,
/// The key whose Revoke was clicked once: the second click does it.
confirm: Option<String>,
/// 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()
{
// 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));
self.job = None;
}
}
fn start(
&mut self,
ui: &Ui,
jobs: &crate::jobs::Spawner,
what: String,
keep: &str,
work: Box<dyn FnOnce() -> 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<Arc<dyn Owner>>,
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);
}
}
another_row(ui, status, book, &owner, &commands, 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<Arc<dyn Owner>>,
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<(String, String)> = 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, id)), 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, &id)),
);
}
}
}
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<dyn FnOnce() -> 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<Arc<dyn Owner>>,
commands: &Option<Result<Commands, String>>,
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 (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}");
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 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<Arc<dyn Owner>>,
commands: &Option<Result<Commands, String>>,
busy: bool,
want: &mut Want,
) {
let p = pal(ui.ctx());
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. 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()
}
})
}),
));
}
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.
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<String>,
revoke: &mut Option<(String, String)>,
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.id.as_str()) {
if ui
.add_enabled(!busy, egui::Button::new("Yes, revoke"))
.clicked()
{
*revoke = Some((t.name.clone(), t.id.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.id.clone());
}
});
});
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.",
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),
);
}
}
+573
View File
@@ -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; 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 => None,
}
}
}
/// 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<Assistant>,
/// The tokens of this company: who may connect.
pub tokens: Vec<TokenRow>,
/// "Now", for "10 seconds ago" (fixed in tests and screenshots).
pub now: DateTime<Utc>,
}
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<String> {
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<Connection<'_>> {
let mut rows: Vec<Connection<'_>> = 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<Utc>) -> 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<Utc>) -> 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<Utc>> {
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<DateTime<Utc>>, now: DateTime<Utc>) -> 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::<String>() + 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<Instant>,
/// The latest answer and when it came.
answer: Option<(Instant, Result<Roster, String>)>,
}
/// The latest answer of the server's sessions request (INVARIANT 2).
pub struct Connections {
shared: Arc<Mutex<Shared>>,
}
impl Default for Connections {
fn default() -> Self {
Self::new()
}
}
fn lock(m: &Mutex<Shared>) -> 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<Mutex<Shared>>);
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<dyn Owner>, 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<Roster> {
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<Roster> {
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<String> {
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<Utc>,
) -> 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<Utc>,
) -> 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
}
}
+7 -7
View File
@@ -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),
);
+3 -1
View File
@@ -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;
@@ -182,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()
})?,
};
+2 -2
View File
@@ -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))
}
+4 -1
View File
@@ -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,
}
}
+98 -23
View File
@@ -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
@@ -153,6 +153,65 @@ 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<String>,
/// Its version.
pub client_version: Option<String>,
/// The model it said it is, if it did.
pub model: Option<String>,
/// 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<LastCall>,
}
/// 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.
pub name: String,
/// What it may do (books:read, books:write, books:post, books:admin).
pub scopes: Vec<String>,
/// 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<Assistant>,
/// Every live token.
pub tokens: Vec<TokenRow>,
}
/// 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 +258,34 @@ pub trait Owner: Send + Sync {
fn serve_exited(&self) -> Option<String> {
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<Roster, String> {
Ok(Roster::default())
}
/// 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<String, String> {
Err("not here".into())
}
/// This program run with `words`, as a line to type in a terminal (the
/// program's own path, the words, the data root if one was named): what
/// the Connect page shows for an assistant it has no button for.
fn command_line(&self, _words: &[&str]) -> Result<String, String> {
Err("not here".into())
}
/// The key an assistant needs to reach the company `book` exists (made
/// 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<bool, String> {
Err("not here".into())
}
/// Close the books: everything holding them lets go.
fn close_books(&self) -> Result<String, String>;
/// New, empty books `id` in `currency`.
@@ -629,25 +716,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();
@@ -688,7 +763,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;
@@ -782,7 +857,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();
+2 -1
View File
@@ -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,
+14 -14
View File
@@ -81,7 +81,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec<Notice> {
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<Notice> {
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<Notice> {
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<Notice> {
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<Notice> {
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<Notice> {
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<String> {
(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" }
)
@@ -499,10 +498,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| {
@@ -510,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;
@@ -525,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;
@@ -1024,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)));
@@ -1200,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)
),
},
@@ -1447,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),
+1 -1
View File
@@ -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;
+4 -3
View File
@@ -158,10 +158,11 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let mut kept_go: Option<Route> = 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 => {
@@ -175,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),
);
@@ -200,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),
+2 -1
View File
@@ -46,13 +46,14 @@ fn grid(ui: &mut Ui, b: &Books, selected: Option<u64>, 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<String> = b.attachments.iter().map(|a| a.category.clone()).collect();
cats.sort();
+9 -4
View File
@@ -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.",
"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 {
"create a new invoice"
},
);
let mut side = bills;
if widgets::segmented(
@@ -362,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 {
+3
View File
@@ -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),
}
+1 -1
View File
@@ -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!(
+3 -2
View File
@@ -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| {
@@ -341,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;
+2 -2
View File
@@ -122,14 +122,14 @@ 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(
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;
+1 -1
View File
@@ -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
}
+2 -1
View File
@@ -64,13 +64,14 @@ fn list(ui: &mut Ui, b: &Books, selected: Option<u64>, 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;
+1
View File
@@ -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(),
}
}
+20
View File
@@ -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<Arc<dyn Owner>> {
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
+15 -3
View File
@@ -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<String>,
/// 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);
}
+6 -6
View File
@@ -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;
+43 -2
View File
@@ -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
@@ -477,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(
@@ -491,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());
+2 -2
View File
@@ -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!(
File diff suppressed because it is too large. Load diff
+17 -13
View File
@@ -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);
@@ -0,0 +1 @@
d4672239e98f338e
@@ -0,0 +1 @@
47a1f842b40cdf15
@@ -0,0 +1 @@
2abd53e6457106f8
@@ -0,0 +1 @@
b990ac9586df492a
@@ -0,0 +1 @@
6642f21a3644e1f4
@@ -0,0 +1 @@
e425621386ec002f
@@ -0,0 +1 @@
79ee857f24de8131
@@ -0,0 +1 @@
d236cd60218a8061
@@ -0,0 +1 @@
8d565039aff8c64c
@@ -0,0 +1 @@
7014f0d713dbc1d8
+102
View File
@@ -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<admin::BookSessions>,
/// Every live token.
pub tokens: Vec<admin::TokenInfo>,
}
/// The books server, a child process of this one.
pub struct AppServer {
run: PathBuf,
@@ -377,6 +395,79 @@ 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<Roster, String> {
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 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<String, String> {
self.wait_ready(READY_WAIT)?;
let request = Request::TokenRevoke {
book: book.into(),
name: name.into(),
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) => {
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)) => {
// 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()),
}
}
/// 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 +712,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<Roster, String> {
self.running()?.roster(wait)
}
/// End the key `id` (INVARIANT 12).
pub fn revoke_token(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.running()?.revoke_token(book, name, id)
}
/// The format upgrade of the company `id` (INVARIANT 10).
pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result<Vec<String>, String> {
match self.running() {
+256 -30
View File
@@ -1402,6 +1402,259 @@ pub fn connect(
}
}
/// 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<Vec<std::ffi::OsString>, 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 args: Vec<std::ffi::OsString> = 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())?;
args.push("--root".into());
args.push(found.path().as_os_str().to_os_string());
}
args.extend(common.knobs.args().into_iter().map(Into::into));
Ok(args)
}
/// The command an assistant runs to reach the books `book`: this program
/// and `mcp --book <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<Vec<std::ffi::OsString>, String> {
let book = ledger_store::root::BookId::parse(book)
.map_err(|e| e.to_string())?
.to_string();
program_args(common, &["mcp", "--book", &book])
}
/// 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)
}
/// `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<String, String> {
if !windows {
return Ok(parts
.iter()
.map(|p| quote_unix(p))
.collect::<Vec<_>>()
.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<String, String> {
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::<Result<Vec<String>, 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<KeyState, String> {
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<bool, String> {
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<String> = 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<bool, String> {
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)
}
/// 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.
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 <book>` added to the agent's own list as
@@ -1420,41 +1673,16 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result<Vec<Str
"{label} isn't installed here (no `{cli}` on the PATH, nor where its installer puts it)"
)
})?;
// 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 serve = bridge_serve_args(common, &book)?;
let mut lines = Vec::new();
// The token: kept in its file, or made now.
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_none() {
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)?;
if ensure_agent_key(common, &book)? {
lines.push(format!(
"Made the agent token of the books {book}, kept in a token file in the data root."
));
}
// The agent's own list: the books' entry made anew.
let name = format!("wanderbooks-{book}");
let mut serve: Vec<std::ffi::OsString> = 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 +3037,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!(
+141
View File
@@ -0,0 +1,141 @@
//! The line the Connect page shows to copy (commands.rs INVARIANT 8; plan
//! P15 unit A4).
//!
//! ```text
//! GOAL: a command pasted into a terminal runs as it reads: whatever a
//! path holds, a POSIX shell gets back exactly the parts it was
//! given; PowerShell's quoting doubles what it must; a part that
//! cannot be written safely for both PowerShell and cmd.exe is
//! refused, in words, never shown.
//! SOURCE: WB-app-1 (the window shows an exact command), POSIX shell
//! command language, "Quoting": single quotes keep every
//! character literal but the single quote itself.
//! INVARIANTS:
//! 1. For any parts, `sh` reads the Unix line back as those parts.
//! 2. Plain parts are left as they are.
//! 3. PowerShell: a `'` is doubled; a part with a character cmd.exe
//! acts on and that needs quoting is refused.
//! ```
use ledger_host::commands::{quote_unix, quote_windows, shell_line};
#[cfg(unix)]
use std::process::Command;
/// The parts a POSIX shell reads from `line` as the words of a command,
/// by `printf` (which prints each word then a NUL).
#[cfg(unix)]
fn sh_words(line: &str) -> Vec<String> {
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<String> = 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<String> = (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", "a<b", "a>b", "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());
}
}
+1
View File
@@ -255,4 +255,5 @@ Three new rows, none above changed status, and the floor stands.
|---|---|---|---|
| Books home: a visible folder per book, `<Documents>/Wanderbooks/<id>`, 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 |
+98
View File
@@ -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-<n>`. 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
(`<this program> 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`).