feat(host,gui): the window can ask the books server who is connected, and end a token

Unit A4 of plan P15 needs the window to read who is connected to each
open company and to end a token. Both go through admin requests the
server already answers (Sessions, TokenList, TokenRevoke): the window's
server handle gains a quick roster (an Err in words while the server is
starting, gone or slow; never a wait) and a revoke that does what
`wanderbooks token revoke` does, including removing the token file's
copy. The command that reaches a company's books is now made in one
place (`bridge_serve_args`) for `connect` and for the Connect page.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 09:28:50 -07:00
1 parent 4c474ee1d9
commit 016f1b2afc
4 files changed
+260 -20

No files matched your search

+43
View File
@@ -116,6 +116,49 @@ 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 {
book: t.book,
name: t.name,
scopes: t.scopes,
created: t.created,
})
.collect();
Ok(Roster { assistants, tokens })
}
fn serve_revoke(&self, book: &str, name: &str) -> Result<String, String> {
self.server.revoke_token(book, name)
}
fn bridge_command(&self, book: &str) -> Result<String, String> {
ledger_host::commands::bridge_command_line(&self.common, book)
}
fn close_books(&self) -> Result<String, String> {
ledger_host::commands::close_books(&self.common)
}
+74
View File
@@ -153,6 +153,62 @@ pub struct UpdateWaiting {
pub staged_at: String,
}
/// A call an assistant made last, as the server says it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LastCall {
/// The tool (or the resource's address).
pub tool: String,
/// "ok", "error", or "refused: CODE".
pub outcome: String,
/// When it finished (UTC, RFC 3339).
pub at: String,
}
/// One assistant connected to a company, from the server's sessions
/// request (plan P15 3.1): what it said of itself (asserted, never
/// checked) and what it is doing. Never a token's text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Assistant {
/// The company it is connected to (the id of its books).
pub book: String,
/// The NAME of the token it opened its session with.
pub token: String,
/// The program's name, as it said at the start.
pub client_name: Option<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 {
/// 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 +255,24 @@ 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` of the company `book` (what `wanderbooks token
/// revoke` does): `Ok` says what was done, in words. Blocks.
fn serve_revoke(&self, _book: &str, _name: &str) -> Result<String, String> {
Err("not here".into())
}
/// The command an assistant runs to reach the company `book`, as text
/// to type (the program and `mcp --book ID`, quoted for a terminal):
/// what the Connect page shows for an assistant it has no button for.
fn bridge_command(&self, _book: &str) -> Result<String, 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`.
+81
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,58 @@ impl AppServer {
}
}
/// Who is connected to each open company, and every live token
/// (INVARIANT 12). It does not wait for the server to be ready: a
/// server still starting is an `Err`, and so is one that does not
/// answer within `wait`.
pub fn roster(&self, wait: Duration) -> Result<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 token `name` of the company `book`, as `wanderbooks token
/// revoke` does (INVARIANT 12): the server ends the token and the
/// sessions it opened, and the token file's copy is removed. `Ok` says
/// what was done, in words; a token file that could not be cleaned is
/// said, and the token is revoked all the same.
pub fn revoke_token(&self, book: &str, name: &str) -> Result<String, String> {
self.wait_ready(READY_WAIT)?;
let request = Request::TokenRevoke {
book: book.into(),
name: name.into(),
id: None,
};
match self.ask_raw(request, Some(Duration::from_secs(30))) {
Ok(Response::TokenRevoked(t)) => {
let said = format!("Ended {:?}'s access to {}.", t.name, t.book);
match crate::commands::forget_token_file(&self.run, book, name) {
Ok(()) => Ok(said),
Err(why) => Ok(format!(
"{said} Its token file still holds its text ({why}); it opens nothing now."
)),
}
}
Ok(Response::Refused(why)) => Err(why),
Ok(other) => Err(format!("the books server answered oddly: {other:?}")),
Err(e) => Err(e.to_string()),
}
}
/// The owner's go-ahead for the format upgrade of the company `id`,
/// with the owner passphrase they typed, sent to the server as the
/// host sends it (INVARIANT 10): what came of it, a line each; or why
@@ -621,6 +691,17 @@ impl AppHost {
.collect()
}
/// Who is connected, and which tokens are live (INVARIANT 12): quick,
/// for a server that is not running or not ready an `Err`.
pub fn roster(&self, wait: Duration) -> Result<Roster, String> {
self.running()?.roster(wait)
}
/// End a token (INVARIANT 12).
pub fn revoke_token(&self, book: &str, name: &str) -> Result<String, String> {
self.running()?.revoke_token(book, name)
}
/// The format upgrade of the company `id` (INVARIANT 10).
pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result<Vec<String>, String> {
match self.running() {
+62 -20
View File
@@ -1402,6 +1402,66 @@ pub fn connect(
}
}
/// The command an assistant runs to reach the books `book`: this program's
/// own executable and `mcp --book <book>`, with `--root` when the data root
/// was named and the knobs this run was given. The one place it is made:
/// `connect_agent` registers it, and the window's Connect page shows it to
/// be typed into an assistant that has no `connect` of its own.
pub fn bridge_serve_args(common: &Common, book: &str) -> Result<Vec<std::ffi::OsString>, String> {
let book = ledger_store::root::BookId::parse(book)
.map_err(|e| e.to_string())?
.to_string();
// A translocated macOS app's path (P11a step 6) is not a place to point
// an agent: the copy goes away with the app.
let exe = crate::start::this_executable()?;
if let Some(why) = crate::start::translocation_refusal(&exe) {
return Err(why.to_string());
}
let mut serve: Vec<std::ffi::OsString> = vec![
exe.into_os_string(),
"mcp".into(),
"--book".into(),
book.into(),
];
if common.root.is_some() {
let found =
ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?;
serve.push("--root".into());
serve.push(found.path().as_os_str().to_os_string());
}
serve.extend(common.knobs.args().into_iter().map(Into::into));
Ok(serve)
}
/// [`bridge_serve_args`] as text, for an assistant that is set up by hand:
/// a part with a space in it is quoted for a terminal.
pub fn bridge_command_line(common: &Common, book: &str) -> Result<String, String> {
let args = bridge_serve_args(common, book)?;
Ok(args
.iter()
.map(|a| {
let a = a.to_string_lossy();
if a.contains(char::is_whitespace) {
format!("\"{a}\"")
} else {
a.into_owned()
}
})
.collect::<Vec<_>>()
.join(" "))
}
/// A revoked token's copy in the token file goes with it (what `token
/// revoke` does after the server has ended the token). `run_dir` is the
/// root's `run/` folder.
pub fn forget_token_file(run_dir: &Path, book: &str, name: &str) -> Result<(), String> {
let root = run_dir.parent().unwrap_or(run_dir).to_path_buf();
let account = crate::tokens::Account::new(&root, book, name);
crate::tokens::keeper(run_dir)
.delete(&account)
.map_err(|e| e.to_string())
}
/// Let the agent `agent` ("claude" or "codex") reach the books `book`:
/// their token kept in its token file (made if none is), and `wanderbooks
/// mcp --book <book>` added to the agent's own list as
@@ -1420,12 +1480,7 @@ 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 =
@@ -1444,17 +1499,6 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result<Vec<Str
}
// 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 +2853,7 @@ pub fn token(
let (answer, run_dir) = with_server_in(&common, request).map_err(fail)?;
match answer {
Response::TokenRevoked(t) => {
let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf();
let account = crate::tokens::Account::new(&root, &book, &name);
let forgot = crate::tokens::keeper(&run_dir).delete(&account);
let forgot = forget_token_file(&run_dir, &book, &name);
println!("Revoked the token {:?} for the books {}.", t.name, t.book);
if let Err(why) = forgot {
eprintln!(