feat(gui): each company's assistants: three states, Ask your assistant, the Connect page, a warning before closing

P15 unit A4, plan 3.3 and D-79. The window only reads the books, so it
now says so by what it offers. Each company is in one of three states
(no assistant, connected, working) read from the books server's own
sessions answer, never waited for, drawn as a shape on its tab and said
in words with the last thing done at the right of the top bar; the
sidebar gives up no height, because the links must all fit at 1479x519.
Where a button that edits would be there is "Ask your assistant", which
copies a ready sentence. The Connect page has a row per local tool with
exact commands, the keys with who is on each, and Revoke through the
existing command path. Closing the window or a tab with an assistant
connected warns first, before and never beside the server's own close.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:03:35 -07:00
1 parent 1d1a2a5a88
commit 022c0c642f
32 files changed
+3083 -40

No files matched your search

+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
+911
View File
@@ -0,0 +1,911 @@
//! What the window says about assistants: the state mark, the top bar's
//! assistant state, "Ask your assistant", and the Connect page (plan P15
//! 3.3). The window only reads the books; to change anything a person asks
//! an assistant, and these are where it says so. The word is "assistant".
//!
//! ```text
//! GOAL: a person who has never heard of any of this can see that they may
//! read everything here, that to change anything they ask an
//! assistant, whether one is connected, and how to connect one; and
//! they can end an assistant's access.
//! SOURCE: plan/p15-app-and-relay.md 3.3 (the word is "assistant"; every
//! tab carries one of three states as a shape and a word; "Ask your
//! assistant" where a button that edits would be, copying a ready
//! sentence; Connect is a page per company: on this computer, a row
//! per tool, and the connections with Revoke); D-77 (bookkeeping is
//! through an assistant, the window reads); WB-assist-1,
//! WB-assist-3, WB-assist-4.
//! INVARIANTS:
//! 1. One place per fact: a tab carries the state as a shape (the same
//! three shapes everywhere: plugs apart, plugs together, a turning
//! arc), with the words in its hover; the front company's state is
//! said in words once, at the right of its top bar, with what it last
//! did; the Connect page lists the keys and who is on each. None of
//! them repeats the company's name or the status card's "Live". The
//! state takes no height: the sidebar's links must all fit at
//! 1479x519 (`tests/sidenav.rs`), so nothing is added above them.
//! 2. The state is never colour alone: each has its own shape and its
//! own word; colour only adds.
//! 3. "Ask your assistant" copies one ready sentence naming the company
//! and what the page is for ("In my Wanderbooks books for Acme,
//! please create a new invoice."); with no assistant connected it
//! says so and where to connect one. It writes nothing: it only puts
//! the sentence on the clipboard.
//! 4. The Connect page shows exact instructions, and only ones this
//! build can stand behind: Claude Code and Codex have a button that
//! does what `wanderbooks connect` does and the command it runs; for
//! any other tool the page gives the program and arguments an
//! assistant must run, and says the tool is untested. No config format
//! is shown that the repository does not document.
//! 5. Revoke asks once, then calls what `wanderbooks token revoke` calls
//! (the owner's `serve_revoke`); the window writes no books. Its job
//! holds the window open until it ends (owner.rs INVARIANT 6).
//! 6. Nothing here blocks the frame: every request of the server runs
//! off the UI thread; what is shown while it is not known is "not
//! known", never a guess.
//! 7. The web half of the page (the switch, the address, the steps for
//! Claude and ChatGPT) is unit B3's: `State::web_section` is its
//! place, and it draws nothing until then.
//! ```
use crate::connections::{Connection, Link, Status, describe, program_name};
use crate::owner::Owner;
use crate::theme::{self, pal};
use egui::{Align, CornerRadius, Frame, Layout, Margin, RichText, Sense, Stroke, Ui, vec2};
use egui_phosphor::regular as icon;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, channel};
// ---- the shape of a state ---------------------------------------------------
/// Paint the mark of `link` centred on `at`, `size` points across: plugs
/// apart (no assistant), plugs together (connected), a turning arc
/// (working). Nothing for `Link::Unknown`.
pub fn paint_mark(ui: &Ui, at: egui::Pos2, size: f32, link: Link) {
let p = pal(ui.ctx());
match link {
Link::Unknown => {}
Link::None => {
ui.painter().text(
at,
egui::Align2::CENTER_CENTER,
icon::PLUGS,
egui::FontId::proportional(size),
p.faint,
);
}
Link::Connected => {
ui.painter().text(
at,
egui::Align2::CENTER_CENTER,
icon::PLUGS_CONNECTED,
egui::FontId::proportional(size),
p.positive,
);
}
Link::Working => {
// A three-quarter arc, turning.
let r = size * 0.36;
let turn = (ui.input(|i| i.time) * 1.6).fract() as f32 * std::f32::consts::TAU;
let points: Vec<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)
}
/// 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 id = ui.id().with("ask-your-assistant");
let button = egui::Button::new(
RichText::new(format!("{} Ask your assistant", icon::CHAT_CENTERED_TEXT))
.font(theme::semibold(13.0))
.color(p.accent),
)
.fill(p.accent_soft)
.stroke(Stroke::new(1.0, p.accent))
.corner_radius(CornerRadius::same(8))
.min_size(vec2(0.0, 30.0));
let resp = ui.add(button).on_hover_text(
"Copies a sentence to paste into your assistant: this window only reads the books",
);
if resp.clicked() {
ui.ctx().copy_text(sentence(&c.company, what));
let now = ui.input(|i| i.time);
ui.ctx().data_mut(|d| d.insert_temp(id, now));
}
resp.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Ask your assistant")
});
let said_at: Option<f64> = ui.ctx().data(|d| d.get_temp(id));
let now = ui.input(|i| i.time);
if let Some(at) = said_at
&& now - at < 8.0
{
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(500));
ui.ctx()
.data_mut(|d| d.insert_temp(ask_said_key(), (what.to_string(), at)));
}
}
fn ask_said_key() -> egui::Id {
egui::Id::new("wanderbooks-ask-said")
}
/// The line under a page's title that follows a click on "Ask your
/// assistant": what was copied, and, with no assistant connected, where to
/// connect one. Drawn by the page header; nothing while it has not been
/// clicked.
pub fn ask_feedback(ui: &mut Ui) {
let Some(c) = ui.ctx().data(|d| d.get_temp::<AskContext>(ask_key())) else {
return;
};
let said: Option<(String, f64)> = ui.ctx().data(|d| d.get_temp(ask_said_key()));
let now = ui.input(|i| i.time);
let Some((what, at)) = said else { return };
if now - at >= 8.0 {
ui.ctx()
.data_mut(|d| d.remove_temp::<(String, f64)>(ask_said_key()));
return;
}
let p = pal(ui.ctx());
ui.add_space(6.0);
ui.label(
RichText::new(format!(
"{} Copied: “{}” Paste it into your assistant.",
icon::CHECK,
sentence(&c.company, &what)
))
.font(theme::regular(13.0))
.color(p.muted),
);
if c.link == Link::None {
ui.horizontal(|ui| {
ui.label(
RichText::new("No assistant is connected yet.")
.font(theme::regular(13.0))
.color(p.warning),
);
if ui.link("Connect an assistant").clicked() {
ui.ctx().data_mut(|d| d.insert_temp(go_key(), true));
}
});
}
}
// ---- the Connect page -------------------------------------------------------
/// A tool the page has a row for.
struct Tool {
/// Its name.
name: &'static str,
/// The agent the owner can connect with one button, if it can.
agent: Option<crate::owner::Agent>,
/// The words that add it to the tool by hand (before the command), if
/// the repository documents them; None says: give the program and its
/// arguments (INVARIANT 4).
add_by_hand: Option<&'static str>,
}
/// The tools of "On this computer", in the order of plan 3.3.
const TOOLS: [Tool; 6] = [
Tool {
name: "Claude Code",
agent: Some(crate::owner::Agent::Claude),
add_by_hand: Some("claude mcp add --scope user"),
},
Tool {
name: "Codex",
agent: Some(crate::owner::Agent::Codex),
add_by_hand: Some("codex mcp add"),
},
Tool {
name: "Gemini CLI",
agent: None,
add_by_hand: None,
},
Tool {
name: "Grok Build",
agent: None,
add_by_hand: None,
},
Tool {
name: "Muse Code",
agent: None,
add_by_hand: None,
},
Tool {
name: "Cursor",
agent: None,
add_by_hand: None,
},
];
type Outcome = Result<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()
{
if what.starts_with("Revoke") && result.is_ok() {
self.refresh = true;
}
self.done = Some((what.clone(), result));
self.job = None;
}
}
fn start(
&mut self,
ui: &Ui,
jobs: &crate::jobs::Spawner,
what: String,
keep: &str,
work: Box<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);
}
}
if TOOLS.iter().any(|t| t.agent.is_none()) {
key_row(ui, status, book, &owner, busy, &mut want);
}
if let Some((what, keep, work)) = want {
self.start(ui, jobs, what, &keep, work);
}
if self.job.is_some() {
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.spinner();
ui.label(
RichText::new("Working…")
.font(theme::regular(13.0))
.color(p.muted),
);
});
} else if let Some((what, result)) = &self.done {
ui.add_space(6.0);
match result {
Ok(said) => ui.label(
RichText::new(format!("{what}: {said}"))
.font(theme::regular(13.0))
.color(p.muted),
),
Err(why) => ui.label(
RichText::new(format!("{what}: {why}"))
.font(theme::regular(13.0))
.color(p.warning),
),
};
}
self.web_section(ui, status);
ui.add_space(24.0);
self.connections(ui, status, book, &owner, jobs);
});
}
/// "Connections": every key to these books, who is connected on it,
/// what it may do, when it last did anything, and Revoke.
fn connections(
&mut self,
ui: &mut Ui,
status: &Status,
book: &str,
owner: &Option<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> = None;
for row in &rows {
Frame::new()
.fill(p.surface)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(CornerRadius::same(8))
.inner_margin(Margin::symmetric(12, 10))
.show(ui, |ui| {
ui.set_width(ui.available_width());
connection_row(
ui,
row,
status,
&mut self.confirm,
&mut revoke,
self.job.is_some(),
owner.is_some(),
);
});
ui.add_space(6.0);
}
if let (Some(name), Some(owner)) = (revoke, owner.clone()) {
self.confirm = None;
let b = book.to_string();
self.start(
ui,
jobs,
format!("Revoke {name}"),
"Ending an assistant's access",
Box::new(move || owner.serve_revoke(&b, &name)),
);
}
}
}
fn section(ui: &mut Ui, title: &str) {
ui.label(RichText::new(title).font(theme::semibold(17.0)));
ui.add_space(4.0);
}
type Want = Option<(String, String, Box<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 (Some(agent), Some(owner)) = (tool.agent, owner)
&& ui
.add_enabled(!busy, egui::Button::new(format!("Connect {}", tool.name)))
.on_hover_text(format!(
"Makes a key for these books and adds them to {}",
tool.name
))
.clicked()
{
let (o, b) = (owner.clone(), book.to_string());
let keep = match agent {
crate::owner::Agent::Claude => "Connecting Claude Code to these books",
crate::owner::Agent::Codex => "Connecting Codex to these books",
};
want = Some((
format!("Connect {}", tool.name),
keep.to_string(),
Box::new(move || o.connect(agent, &b).map(|lines| lines.join(" "))),
));
}
});
});
ui.add_space(4.0);
match commands {
Some(Ok(c)) => by_hand(ui, tool, book, &c.bridge),
Some(Err(why)) => {
ui.label(
RichText::new(format!("The command could not be worked out: {why}"))
.font(theme::regular(12.5))
.color(p.warning),
);
}
None => {}
}
});
ui.add_space(6.0);
want
}
/// The exact text for a tool, copyable.
fn by_hand(ui: &mut Ui, tool: &Tool, book: &str, bridge: &str) {
let p = pal(ui.ctx());
let name = format!("wanderbooks-{book}");
match tool.add_by_hand {
Some(add) => {
let line = format!("{add} {name} -- {bridge}");
egui::CollapsingHeader::new(
RichText::new("Or do it yourself, in a terminal")
.font(theme::regular(12.5))
.color(p.muted),
)
.id_salt(("by-hand", tool.name))
.show(ui, |ui| {
ui.label(
RichText::new("Run this once:")
.font(theme::regular(12.5))
.color(p.muted),
);
command_box(ui, &line);
ui.label(
RichText::new(format!(
"Then restart {}. It reaches the books as “{name}”.",
tool.name
))
.font(theme::regular(12.5))
.color(p.muted),
);
});
}
None => {
ui.label(
RichText::new(format!(
"In {}, add a local tool (a program it runs on this computer) named “{name}”, with this command:",
tool.name
))
.font(theme::regular(13.0))
.color(p.text),
);
command_box(ui, bridge);
ui.label(
RichText::new(format!(
"Then restart {}. If it asks for the program and its arguments separately, the program is the first word and the rest are its arguments. We haven't tested {} yet.",
tool.name, tool.name
))
.font(theme::regular(12.5))
.color(p.muted),
);
}
}
}
/// The step the tools without a button share: the key they read, made once.
fn key_row(
ui: &mut Ui,
status: &Status,
book: &str,
owner: &Option<Arc<dyn Owner>>,
busy: bool,
want: &mut Want,
) {
let p = pal(ui.ctx());
ui.add_space(2.0);
ui.label(
RichText::new(format!(
"For the others, make {}'s key first (once):",
status.company
))
.font(theme::regular(13.0))
.color(p.muted),
);
if let Some(owner) = owner
&& ui
.add_enabled(!busy, egui::Button::new("Make the key"))
.on_hover_text(
"Makes the key these books give an assistant, and keeps it on this computer",
)
.clicked()
{
let (o, b) = (owner.clone(), book.to_string());
*want = Some((
"Make the key".to_string(),
"Making the key".to_string(),
Box::new(move || {
o.make_key(&b).map(|made| {
if made {
"made, and kept on this computer.".to_string()
} else {
"it was already made.".to_string()
}
})
}),
));
}
}
/// Text in a box, with a Copy button.
fn command_box(ui: &mut Ui, text: &str) {
let p = pal(ui.ctx());
Frame::new()
.fill(p.bg)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(CornerRadius::same(6))
.inner_margin(Margin::symmetric(10, 8))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
if ui.button(format!("{} Copy", icon::COPY)).clicked() {
ui.ctx().copy_text(text.to_string());
}
ui.with_layout(Layout::left_to_right(Align::Min), |ui| {
ui.add(
egui::Label::new(
RichText::new(text).font(egui::FontId::monospace(12.0)),
)
.wrap()
.selectable(true),
);
});
});
});
});
}
/// One key of these books: its name, what is connected on it, what it may
/// do, and Revoke (asked once).
fn connection_row(
ui: &mut Ui,
row: &Connection<'_>,
status: &Status,
confirm: &mut Option<String>,
revoke: &mut Option<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.name.as_str()) {
if ui
.add_enabled(!busy, egui::Button::new("Yes, revoke"))
.clicked()
{
*revoke = Some(t.name.clone());
}
if ui.button("Keep it").clicked() {
*confirm = None;
}
} else if ui
.add_enabled(!busy, egui::Button::new("Revoke"))
.on_hover_text("Ends this key: the assistant using it is cut off and cannot reach these books again")
.clicked()
{
*confirm = Some(t.name.clone());
}
});
});
if confirm.as_deref() == Some(row.name.as_str()) {
ui.label(
RichText::new(format!(
"Revoke the key “{}”? Anything using it is cut off now; {}'s books are not changed.",
row.name, status.company
))
.font(theme::regular(12.5))
.color(p.warning),
);
}
for a in &row.sessions {
ui.label(
RichText::new(describe(a, status.now))
.font(theme::regular(12.5))
.color(p.text),
);
}
}
+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, a
/// spinning arc).
pub fn glyph(self) -> Option<&'static str> {
match self {
Link::Unknown => None,
Link::None => Some(icon::PLUGS),
Link::Connected => Some(icon::PLUGS_CONNECTED),
Link::Working => Some(icon::CIRCLE_NOTCH),
}
}
}
/// Everything the window shows of one company's assistants. Made by the
/// app each frame from the latest answer (`Connections::status_of`).
#[derive(Clone, Debug, PartialEq)]
pub struct Status {
/// The window runs a books server: without one there is nothing to
/// connect to, and none of this is shown.
pub serves: bool,
/// The server is not coming up: its start failed or it has exited
/// (the notice under the tab bar says why).
pub down: bool,
/// The company's name, as the tab says it.
pub company: String,
/// The state.
pub link: Link,
/// The assistants connected to this company, the longest connected
/// first.
pub assistants: Vec<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
}
}
+2
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;
+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,
}
}
+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,
+2 -1
View File
@@ -499,10 +499,11 @@ fn date_controls(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) -> NaiveDate {
pub fn show_register(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let p = pal(ui.ctx());
page(ui, "assets", |ui| {
widgets::page_header(
widgets::page_header_ask(
ui,
"Fixed assets",
"Everything the company owns as a fixed asset: its label, what it cost, how much has been depreciated, and what it's worth on the books, reconciled to the general ledger.",
"add a fixed asset",
);
if b.ledger.registered_assets().next().is_none() {
widgets::card(ui, |ui| {
+2 -1
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 => {
+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();
+6 -1
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.",
if bills {
"enter a new bill"
} else {
"create a new invoice"
},
);
let mut side = bills;
if widgets::segmented(
+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),
}
+2 -1
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| {
+1 -1
View File
@@ -122,7 +122,7 @@ pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let p = pal(ui.ctx());
page(ui, "projects", |ui| {
let all = listed(b);
widgets::page_header(ui, "Projects", &summary(&all));
widgets::page_header_ask(ui, "Projects", &summary(&all), "add a project");
if all.is_empty() {
widgets::card(ui, |ui| {
widgets::empty(
+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);
}
+41
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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
554a45de5050b79d
@@ -0,0 +1 @@
fffc3e5adaa00db0
@@ -0,0 +1 @@
e8b3ce383a13c776
@@ -0,0 +1 @@
3271d551e50db504
@@ -0,0 +1 @@
9530691dfcdedf6b
@@ -0,0 +1 @@
5f60b24231b7a370
@@ -0,0 +1 @@
9bc7803073cd0434
@@ -0,0 +1 @@
fea19947b5c1a09e
@@ -0,0 +1 @@
334251b6f2666663
@@ -0,0 +1 @@
31ed42032e1844c9
+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`).