Merge branch 't3/p15-c1-desktop-packages': packages for Windows, macOS and Linux, and the Claude desktop extension (P15 C1)

The two Connect page baselines are re-blessed on the merged code: the
page gained the extension row here and the stopped test clock on main.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 15:57:46 -07:00
commit 813042a7a6
53 files changed
+3875 -276

No files matched your search

+10
View File
@@ -24,6 +24,11 @@ ledger-mcp = { path = "../ledger-mcp" }
ledger-store = { path = "../ledger-store" }
ledger-gui = { path = "../ledger-gui", optional = true }
# The parent's console for a command run in a terminal (console.rs): the
# raw bindings, already in the lockfile through ledger-store.
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] }
[dev-dependencies]
base64 = "0.22"
chrono = "0.4"
@@ -70,6 +75,8 @@ workspace = true
# program: `just package-linux`. Paths are relative to the workspace root.
[package.metadata.generate-rpm]
name = "wanderbooks"
# Backups run the system's git (WB-pkg-4): dnf fetches it.
requires = { git = "*" }
summary = "Double-entry bookkeeping your agent keeps and you can read"
license = "MIT OR Apache-2.0"
url = "https://wanderbooks.ai"
@@ -77,5 +84,8 @@ assets = [
{ source = "target/release/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" },
{ source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" },
{ source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" },
{ source = "deploy/packaging/icons/512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/wanderbooks.png", mode = "0644" },
{ source = "LICENSE-MIT", dest = "/usr/share/doc/wanderbooks/LICENSE-MIT", mode = "0644" },
{ source = "LICENSE-APACHE", dest = "/usr/share/doc/wanderbooks/LICENSE-APACHE", mode = "0644" },
{ source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" },
]
+85
View File
@@ -0,0 +1,85 @@
//! The program's console on Windows (plan P15 unit C1, WB-pkg-2).
//!
//! The installed program is one executable that is the window, the books
//! server child and the assistants' bridge. Built for the Windows GUI
//! subsystem (`windows_subsystem = "windows"` in `main.rs`), a double-click
//! or a Start Menu entry opens no console window. The same file still has
//! to be a command line: a person who types `wanderbooks books list` in a
//! terminal needs the words printed there, and an assistant that starts
//! `wanderbooks mcp --book X` hands it pipes, which a GUI-subsystem
//! program receives as they are.
//!
//! ```text
//! GOAL: no console window when the program starts as an app; its words
//! reach the terminal that started it as a command; a pipe handed to
//! it is never replaced.
//! SOURCE: WB-pkg-2 (one executable); Microsoft's documentation of
//! AttachConsole(ATTACH_PARENT_PROCESS) and SetStdHandle.
//! INVARIANTS:
//! 1. A standard handle the parent gave (a pipe, a file) is left as it
//! is; only a missing one (null or invalid) is pointed at the
//! parent's console (CONIN$ for input, CONOUT$ for output and
//! errors).
//! 2. With no parent console (a Start Menu launch, an assistant that
//! gave pipes and has no console) nothing is attached and nothing is
//! opened: the program never makes a console window of its own.
//! SCENARIOS:
//! 1. IF an assistant starts `mcp` with three pipes: SHOULD speak over
//! them, unchanged.
//! 2. IF a terminal starts `books list`: SHOULD print into the terminal.
//! 3. IF the Start Menu starts it with no words: SHOULD open the window
//! and no console.
//! ```
//!
//! Not run on Windows by the author (the unit was written on Linux); the
//! `release` workflow's Windows job builds it, and the first install is
//! the evidence for the scenarios.
/// Point the missing standard handles at the parent's console, if there
/// is one (INVARIANTS 1 and 2). A no-op everywhere but Windows.
#[cfg(windows)]
pub fn attach_parent_console() {
use std::os::windows::io::IntoRawHandle;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Console::{
ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE,
STD_OUTPUT_HANDLE, SetStdHandle,
};
// SAFETY: plain Win32 calls with no pointers of ours; a failure is a
// value, and the handles opened below are given to the process, which
// keeps them open for its life.
unsafe {
let missing = |id| {
let handle = GetStdHandle(id);
handle.is_null() || handle == INVALID_HANDLE_VALUE
};
let wanted = [
(STD_INPUT_HANDLE, "CONIN$", true),
(STD_OUTPUT_HANDLE, "CONOUT$", false),
(STD_ERROR_HANDLE, "CONOUT$", false),
];
if !wanted.iter().any(|(id, _, _)| missing(*id)) {
return;
}
if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
return;
}
for (id, device, input) in wanted {
if !missing(id) {
continue;
}
let opened = std::fs::OpenOptions::new()
.read(input)
.write(!input)
.open(device);
if let Ok(file) = opened {
SetStdHandle(id, file.into_raw_handle());
}
}
}
}
/// Nothing to do where a program is a console program already.
#[cfg(not(windows))]
pub fn attach_parent_console() {}
+34 -2
View File
@@ -9,6 +9,13 @@
//! From nothing to the first post: `wanderbooks setup`, `wanderbooks books
//! create ID`, `wanderbooks connect claude --book ID` (then talk to the
//! agent).
//!
//! On Windows the executable is built for the GUI subsystem, so starting
//! it from the Start Menu opens no console window; `console` gives a
//! command run in a terminal its words back (WB-pkg-2).
#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")]
mod console;
use std::env;
use std::io::Write;
@@ -275,6 +282,18 @@ impl ledger_gui::owner::Owner for ViewerOwner {
)
}
fn claude_desktop_extension(
&self,
book: &str,
company: &str,
) -> Result<ledger_gui::owner::ExtensionMade, String> {
let made = ledger_host::extension::claude_desktop_extension(&self.common, book, company)?;
Ok(ledger_gui::owner::ExtensionMade {
file: made.path.display().to_string(),
folder: made.folder.display().to_string(),
})
}
fn new_books(&self, id: &str, currency: &str) -> Result<String, String> {
ledger_host::commands::new_books_and_home(&self.common, id, currency)
}
@@ -390,6 +409,15 @@ impl ledger_gui::owner::Owner for ViewerOwner {
})
}
fn newer_version(&self) -> Option<ledger_gui::owner::NewerVersion> {
ledger_host::commands::newer_version(&self.common).map(|(version, page)| {
ledger_gui::owner::NewerVersion {
version,
page: page.to_string(),
}
})
}
fn check_for_updates(&self) -> Result<Vec<String>, String> {
ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l])
}
@@ -683,8 +711,7 @@ fn is_bare_launch(words: &[String], stdin_is_terminal: bool) -> bool {
}
fn main() {
#[cfg(unix)]
ledger_host::update::set_program_version(env!("CARGO_PKG_VERSION"));
ledger_host::set_program_version(env!("CARGO_PKG_VERSION"));
// A file's path may be any name the system takes: the file commands
// get the words as given. Everything else is text.
let given: Vec<std::ffi::OsString> = env::args_os().skip(1).collect();
@@ -700,6 +727,11 @@ fn main() {
eprintln!("error: an argument isn't UTF-8 text");
std::process::exit(2);
};
// A command run in a terminal prints there; the app (no words) opens
// no console at all (console.rs).
if !words.is_empty() {
console::attach_parent_console();
}
// A bare launch is the viewer.
if is_bare_launch(&words, std::io::IsTerminal::is_terminal(&std::io::stdin())) {
std::process::exit(run_gui(Vec::new()));
+144
View File
@@ -0,0 +1,144 @@
//! The Claude desktop extension the Connect page writes (plan P15 unit C1,
//! WB-pkg-5): its package is Anthropic's MCP Bundle, and its manifest is
//! checked against Anthropic's published schema for manifest version 0.3
//! (`tests/fixtures/mcpb/`, with where it came from).
//!
//! ```text
//! GOAL: a package the Claude desktop app can install, naming this
//! program's bridge for one company, with nothing secret in it.
//! SOURCE: WB-pkg-5; Anthropic's MCP Bundle manifest specification
//! (the manifest page and the version 0.3 JSON schema of its
//! mcpb repository on GitHub); the writer's own spec block in
//! the host crate.
//! INVARIANTS:
//! 1. The package is a zip whose root holds `manifest.json`; every file
//! the manifest names (`icon`, `server.entry_point`) is in the zip.
//! 2. The manifest validates against the 0.3 schema, which refuses any
//! field the specification does not define.
//! 3. The server is a `binary` whose command is the program's path and
//! whose arguments are `mcp --book <id>`.
//! SCENARIOS:
//! 1. A package made for a company with an awkward name validates.
//! 2. Every required field of the schema is present.
//! ```
use serde_json::Value;
use std::io::Read;
fn schema() -> jsonschema::Validator {
let text = include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json");
jsonschema::validator_for(&serde_json::from_str::<Value>(text).unwrap()).unwrap()
}
fn made(company: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let bridge: Vec<std::ffi::OsString> = [
"/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks",
"mcp",
"--book",
"acme",
]
.map(Into::into)
.to_vec();
let made = ledger_host::extension::write_in(dir.path(), "acme", company, "0.1.0", &bridge)
.expect("the package is written");
(dir, made.path)
}
fn read(path: &std::path::Path) -> (Value, Vec<String>) {
let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap();
let names: Vec<String> = (0..zip.len())
.map(|i| zip.by_index(i).unwrap().name().unwrap().to_string())
.collect();
let mut text = String::new();
zip.by_name("manifest.json")
.expect("manifest.json is at the root of the package")
.read_to_string(&mut text)
.unwrap();
(serde_json::from_str(&text).unwrap(), names)
}
#[test]
fn the_manifest_is_one_the_published_schema_accepts() {
for company in [
"Wanderland Labs LLC",
"Quote \" and <markup> & \u{e9}\u{4e2d}",
&"long ".repeat(100),
"",
] {
let (_dir, path) = made(company);
let (manifest, _) = read(&path);
let errors: Vec<String> = schema()
.iter_errors(&manifest)
.map(|e| format!("{e} at {}", e.instance_path()))
.collect();
assert!(errors.is_empty(), "{company:?}: {errors:?}\n{manifest:#}");
// The check is not vacuous: a field the specification lacks, or a
// missing required one, is refused.
let mut extra = manifest.clone();
extra["no_such_field"] = Value::Bool(true);
assert!(!schema().is_valid(&extra));
let mut short = manifest.clone();
short.as_object_mut().unwrap().remove("author");
assert!(!schema().is_valid(&short));
}
}
#[test]
fn every_file_the_manifest_names_is_in_the_package() {
let (_dir, path) = made("Acme");
let (manifest, names) = read(&path);
assert_eq!(manifest["manifest_version"], "0.3");
for named in [
manifest["icon"].as_str().unwrap(),
manifest["server"]["entry_point"].as_str().unwrap(),
] {
assert!(names.iter().any(|n| n == named), "{named} in {names:?}");
}
// The schema's required fields, by the schema's own list.
let schema: Value =
serde_json::from_str(include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json")).unwrap();
for field in schema["required"].as_array().unwrap() {
assert!(manifest.get(field.as_str().unwrap()).is_some(), "{field}");
}
for field in schema["properties"]["server"]["required"]
.as_array()
.unwrap()
{
assert!(manifest["server"].get(field.as_str().unwrap()).is_some());
}
}
#[test]
fn the_server_runs_this_programs_bridge_for_the_company() {
let (_dir, path) = made("Acme");
let (manifest, _) = read(&path);
let server = &manifest["server"];
assert_eq!(server["type"], "binary");
assert_eq!(
server["mcp_config"]["command"],
"/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks"
);
assert_eq!(
server["mcp_config"]["args"],
serde_json::json!(["mcp", "--book", "acme"])
);
// The package carries no program (the one executable is the installed
// one) and no key.
let (_, names) = read(&path);
assert_eq!(names.len(), 3, "{names:?}");
assert_eq!(manifest["name"], "wanderbooks-acme");
}
/// The 512 px icon is a PNG (the manifest's `icon` is "a png icon file").
#[test]
fn the_icon_is_a_png() {
let (_dir, path) = made("Acme");
let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap();
let mut head = [0u8; 8];
zip.by_name("icon.png")
.unwrap()
.read_exact(&mut head)
.unwrap();
assert_eq!(&head, b"\x89PNG\r\n\x1a\n");
}
+10
View File
@@ -0,0 +1,10 @@
mcpb-manifest-v0.3.schema.json is Anthropic's published JSON Schema for the
manifest.json of an MCP Bundle (.mcpb, formerly the Desktop Extension .dxt),
manifest_version 0.3, copied verbatim on 2026-11-21 from
https://github.com/anthropics/mcpb (schemas/mcpb-manifest-v0.3.schema.json,
main branch). The specification's prose is MANIFEST.md in the same
repository; the install steps are Claude's help article "Getting started
with Local MCP servers on Claude Desktop" (support.claude.com).
The repository's licence: Apache-2.0 for new contributions, MIT for older
ones (its LICENSE file); both fit this project's MIT OR Apache-2.0. It is
a test fixture only and is not shipped.
@@ -0,0 +1,376 @@
{
"type": "object",
"properties": {
"$schema": {
"type": "string"
},
"dxt_version": {
"type": "string",
"const": "0.3",
"description": "@deprecated Use manifest_version instead"
},
"manifest_version": {
"type": "string",
"const": "0.3"
},
"name": {
"type": "string"
},
"display_name": {
"type": "string"
},
"version": {
"type": "string"
},
"description": {
"type": "string"
},
"long_description": {
"type": "string"
},
"author": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"url": {
"type": "string",
"format": "uri"
}
},
"required": [
"name"
],
"additionalProperties": false
},
"repository": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"url": {
"type": "string",
"format": "uri"
}
},
"required": [
"type",
"url"
],
"additionalProperties": false
},
"homepage": {
"type": "string",
"format": "uri"
},
"documentation": {
"type": "string",
"format": "uri"
},
"support": {
"type": "string",
"format": "uri"
},
"icon": {
"type": "string"
},
"icons": {
"type": "array",
"items": {
"type": "object",
"properties": {
"src": {
"type": "string"
},
"size": {
"type": "string",
"pattern": "^\\d+x\\d+$"
},
"theme": {
"type": "string",
"minLength": 1
}
},
"required": [
"src",
"size"
],
"additionalProperties": false
}
},
"screenshots": {
"type": "array",
"items": {
"type": "string"
}
},
"localization": {
"type": "object",
"properties": {
"resources": {
"type": "string",
"pattern": "\\$\\{locale\\}"
},
"default_locale": {
"type": "string",
"pattern": "^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$"
}
},
"required": [
"resources",
"default_locale"
],
"additionalProperties": false
},
"server": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"python",
"node",
"binary"
]
},
"entry_point": {
"type": "string"
},
"mcp_config": {
"type": "object",
"properties": {
"command": {
"type": "string"
},
"args": {
"type": "array",
"items": {
"type": "string"
}
},
"env": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"platform_overrides": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"command": {
"$ref": "#/properties/server/properties/mcp_config/properties/command"
},
"args": {
"$ref": "#/properties/server/properties/mcp_config/properties/args"
},
"env": {
"$ref": "#/properties/server/properties/mcp_config/properties/env"
}
},
"additionalProperties": false
}
}
},
"required": [
"command"
],
"additionalProperties": false
}
},
"required": [
"type",
"entry_point",
"mcp_config"
],
"additionalProperties": false
},
"tools": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"description": {
"type": "string"
}
},
"required": [
"name"
],
"additionalProperties": false
}
},
"tools_generated": {
"type": "boolean"
},
"prompts": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"description": {
"type": "string"
},
"arguments": {
"type": "array",
"items": {
"type": "string"
}
},
"text": {
"type": "string"
}
},
"required": [
"name",
"text"
],
"additionalProperties": false
}
},
"prompts_generated": {
"type": "boolean"
},
"keywords": {
"type": "array",
"items": {
"type": "string"
}
},
"license": {
"type": "string"
},
"privacy_policies": {
"type": "array",
"items": {
"type": "string",
"format": "uri"
}
},
"compatibility": {
"type": "object",
"properties": {
"claude_desktop": {
"type": "string"
},
"platforms": {
"type": "array",
"items": {
"type": "string",
"enum": [
"darwin",
"win32",
"linux"
]
}
},
"runtimes": {
"type": "object",
"properties": {
"python": {
"type": "string"
},
"node": {
"type": "string"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
"user_config": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"string",
"number",
"boolean",
"directory",
"file"
]
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"required": {
"type": "boolean"
},
"default": {
"anyOf": [
{
"type": "string"
},
{
"type": "number"
},
{
"type": "boolean"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"multiple": {
"type": "boolean"
},
"sensitive": {
"type": "boolean"
},
"min": {
"type": "number"
},
"max": {
"type": "number"
}
},
"required": [
"type",
"title",
"description"
],
"additionalProperties": false
}
},
"_meta": {
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": {}
}
}
},
"required": [
"name",
"version",
"description",
"author",
"server"
],
"additionalProperties": false,
"$schema": "http://json-schema.org/draft-07/schema#"
}
+709
View File
@@ -0,0 +1,709 @@
//! The packages (plan P15 unit C1; WB-pkg-1 to WB-pkg-7): what can be checked
//! on Linux about the Windows installer, the macOS app, the Linux entries and
//! the one source of the version. For Windows and macOS the release workflow
//! is the real test (each packaging step fails loudly); these tests keep the
//! files it builds from true to the rules.
//!
//! ```text
//! GOAL: an installed Wanderbooks is one executable at a stable path, named
//! Wanderbooks everywhere a person sees it, with the licences beside
//! it; installing a newer one over it, or uninstalling it, never
//! touches the person's books.
//! SOURCE: WB-pkg-1 (installs like a normal program), WB-pkg-2 (one
//! executable, a stable bridge path), WB-pkg-6 (one version, one
//! name), WB-pkg-7 (the release carries the licences); D-77.
//! INVARIANTS:
//! 1. The version is written once (ledger-cli's Cargo.toml); the packaging
//! scripts read it through deploy/packaging/version.sh.
//! 2. The Windows installer is per user (no administrator), installs one
//! program, and its uninstaller names nothing but what the installer
//! put in its own folder: no recursive removal, no wildcard, no data
//! folder.
//! 3. The macOS bundle holds one program at Contents/MacOS/wanderbooks, an
//! Info.plist whose identifier, name, version and executable agree with
//! the scripts, and the licences.
//! 4. The Linux desktop entries launch plain `wanderbooks` (an AppImage's
//! launcher appends what it is given) with the icon, the name, and the
//! window's app id.
//! 5. Every package carries LICENSE-MIT, LICENSE-APACHE and
//! THIRD-PARTY-NOTICES.txt.
//! SCENARIOS:
//! 1. The bundle script run on Linux with a stand-in program makes a
//! bundle whose plist and files match the rules above.
//! ```
use std::path::{Path, PathBuf};
use std::process::Command;
fn root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
fn read(path: &str) -> String {
std::fs::read_to_string(root().join(path)).unwrap_or_else(|e| panic!("{path}: {e}"))
}
/// The lines of `text` that are not comments (`;` for NSIS, `#` for shell
/// and TOML).
fn code(text: &str) -> Vec<&str> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with(';') && !l.starts_with('#'))
.collect()
}
const LICENCE_FILES: [&str; 3] = ["LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt"];
// ---- the version, written once ---------------------------------------------------
#[cfg(unix)]
#[test]
fn the_version_is_written_once_and_every_script_reads_it_from_there() {
let out = Command::new("sh")
.arg(root().join("deploy/packaging/version.sh"))
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
let said = String::from_utf8(out.stdout).unwrap();
assert_eq!(said.trim(), env!("CARGO_PKG_VERSION"));
// The Linux packager's own file carries a version the build script
// overwrites; it must not drift from the source.
let packager = read("deploy/packaging/packager.toml");
let line = code(&packager)
.into_iter()
.find(|l| l.starts_with("version = "))
.unwrap();
assert_eq!(line, format!("version = \"{}\"", env!("CARGO_PKG_VERSION")));
// No packaging script or workflow assigns a literal version.
for file in [
"deploy/packaging/windows/build-windows.sh",
"deploy/packaging/macos/build-macos.sh",
".github/workflows/release.yml",
] {
for line in code(&read(file)) {
let assigns = line.starts_with("version=") || line.starts_with("version:");
let literal = line.split(['=', ':']).nth(1).is_some_and(|v| {
v.trim()
.trim_matches('"')
.chars()
.next()
.is_some_and(|c| c.is_ascii_digit())
});
assert!(!(assigns && literal), "{file}: a literal version: {line}");
}
}
for file in [
"deploy/packaging/windows/build-windows.sh",
"deploy/packaging/macos/build-macos.sh",
"deploy/packaging/build-linux.sh",
] {
let text = read(file);
assert!(
text.contains("version.sh") || text.contains("ledger-cli/Cargo.toml"),
"{file} does not read the version from its one source"
);
}
}
#[cfg(unix)]
#[test]
fn a_version_that_is_not_three_numbers_is_refused() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("deploy/packaging")).unwrap();
std::fs::create_dir_all(dir.path().join("crates/ledger-cli")).unwrap();
std::fs::copy(
root().join("deploy/packaging/version.sh"),
dir.path().join("deploy/packaging/version.sh"),
)
.unwrap();
for (toml, ok) in [
("version = \"0.2.0\"\n", true),
("version = \"0.2.0-rc1\"\n", false),
("version = \"two\"\n", false),
("", false),
] {
std::fs::write(dir.path().join("crates/ledger-cli/Cargo.toml"), toml).unwrap();
let out = Command::new("sh")
.arg(dir.path().join("deploy/packaging/version.sh"))
.output()
.unwrap();
assert_eq!(out.status.success(), ok, "{toml:?}: {out:?}");
}
}
// ---- Windows --------------------------------------------------------------------
#[test]
fn the_windows_installer_is_per_user_and_installs_one_program() {
let nsi = read("deploy/packaging/windows/wanderbooks.nsi");
let lines = code(&nsi);
let has = |needle: &str| lines.iter().any(|l| l.contains(needle));
// No administrator prompt; everything in the person's own profile.
assert!(has("RequestExecutionLevel user"));
assert!(has(r#"InstallDir "$LOCALAPPDATA\Programs\Wanderbooks""#));
assert!(
!lines.iter().any(|l| l.contains("HKLM")),
"per-machine registry"
);
assert!(!has("SetShellVarContext all"), "all users' Start Menu");
// A Start Menu entry named Wanderbooks, with the icon.
assert!(has(
r#"CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe""#
));
assert!(has(r#"!define NAME "Wanderbooks""#));
assert!(has("wanderbooks.ico"));
// An uninstaller, listed in Settings > Apps, whose name is the product's.
assert!(has("WriteUninstaller"));
assert!(has(r#""DisplayName" "${NAME}""#));
assert!(has("UninstallString"));
// One program: the only .exe installed besides the uninstaller.
let programs: Vec<&&str> = lines
.iter()
.filter(|l| l.starts_with("File ") && l.contains(".exe"))
.collect();
assert_eq!(programs.len(), 1, "{programs:?}");
assert!(programs[0].contains("/oname=wanderbooks.exe"));
// The licences travel with it.
for file in LICENCE_FILES {
assert!(has(&format!("/oname={file}")), "{file} is not installed");
}
}
/// WB-pkg-1: the uninstaller removes what the installer put in its own
/// folder and nothing else; the books are in the data folder, which it never
/// names.
#[test]
fn the_uninstaller_never_removes_the_books() {
let nsi = read("deploy/packaging/windows/wanderbooks.nsi");
let lines = code(&nsi);
let start = lines
.iter()
.position(|l| l.starts_with(r#"Section "Uninstall""#))
.expect("an uninstall section");
let section = &lines[start..];
let mut removals = 0;
for line in section {
let word = line.split_whitespace().next().unwrap_or("");
if matches!(word, "Delete" | "RMDir" | "DeleteRegKey" | "DeleteRegValue") {
removals += 1;
assert!(!line.contains("/r"), "a recursive removal: {line}");
assert!(
!line.contains('*') && !line.contains('?'),
"a wildcard: {line}"
);
let ok = line.contains("$INSTDIR")
|| line.contains("$SMPROGRAMS")
|| line.contains("${UNINSTALL_KEY}")
|| line.contains("${APP_KEY}");
assert!(
ok,
"removes something that is not the program's own: {line}"
);
}
}
assert!(removals >= 6, "the uninstaller removes the installed files");
// The data folder, the roaming settings and the keys are named nowhere
// in the script's code (the comments say where the books are).
for line in &lines {
for data in [
"$LOCALAPPDATA\\wanderbooks",
"$APPDATA",
"\\link",
"legacy",
"books\\",
] {
assert!(!line.contains(data), "{data} named: {line}");
}
}
// Only the registry keys of its own.
let keys: Vec<&&str> = lines
.iter()
.filter(|l| l.starts_with("!define") && l.contains("_KEY"))
.collect();
assert_eq!(keys.len(), 2, "{keys:?}");
assert!(keys[0].contains(r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks"));
assert!(keys[1].contains(r"Software\Wanderbooks"));
}
/// If NSIS is installed here, the script compiles with stand-in files
/// (the release workflow compiles it for real on Windows).
#[test]
fn the_installer_script_compiles_when_nsis_is_here() {
let Some(makensis) = std::env::var_os("PATH").and_then(|p| {
std::env::split_paths(&p)
.map(|d| d.join("makensis"))
.find(|f| f.is_file())
}) else {
eprintln!(
"makensis is not installed here: the Windows job of the release workflow compiles the installer"
);
return;
};
let dir = tempfile::tempdir().unwrap();
let p = dir.path();
std::fs::write(p.join("wanderbooks.exe"), b"MZ").unwrap();
for f in LICENCE_FILES {
std::fs::write(p.join(f), b"x").unwrap();
}
std::fs::copy(
root().join("deploy/packaging/icons/wanderbooks.ico"),
p.join("wanderbooks.ico"),
)
.unwrap();
let out = Command::new(makensis)
.arg("-V2")
.arg(format!("-DVERSION={}", env!("CARGO_PKG_VERSION")))
.arg(format!("-DPROGRAM={}", p.join("wanderbooks.exe").display()))
.arg(format!("-DICON={}", p.join("wanderbooks.ico").display()))
.arg(format!("-DLICENSES={}", p.display()))
.arg(format!("-DOUTFILE={}", p.join("setup.exe").display()))
.arg(root().join("deploy/packaging/windows/wanderbooks.nsi"))
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stdout)
);
assert!(p.join("setup.exe").metadata().unwrap().len() > 0);
}
/// WB-pkg-2: on Windows the one executable is built for the GUI subsystem
/// (no console window for the app), and gives a terminal its words back.
#[test]
fn the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal() {
let main = read("crates/ledger-cli/src/main.rs");
assert!(
main.contains(
r#"#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")]"#
)
);
assert!(main.contains("console::attach_parent_console()"));
let console = read("crates/ledger-cli/src/console.rs");
assert!(console.contains("AttachConsole(ATTACH_PARENT_PROCESS)"));
// The server child the app starts has no console window of its own.
assert!(read("crates/ledger-host/src/app_server.rs").contains("NO_WINDOW"));
}
// ---- macOS ----------------------------------------------------------------------
/// The `<key>`/value pairs of a plist's top-level dict, as text. Good enough
/// for the plain plists here (no nesting).
fn plist(text: &str) -> Vec<(String, String)> {
let mut pairs = Vec::new();
let mut key: Option<String> = None;
for line in text.lines().map(str::trim) {
if let Some(k) = line
.strip_prefix("<key>")
.and_then(|l| l.strip_suffix("</key>"))
{
assert!(key.is_none(), "a key with no value: {k}");
key = Some(k.to_string());
} else if let Some(k) = key.take_if(|_| line.starts_with('<') && !line.starts_with("<!--"))
{
let value = line
.strip_prefix("<string>")
.and_then(|l| l.strip_suffix("</string>"))
.map(str::to_string)
.unwrap_or_else(|| line.to_string());
pairs.push((k, value));
}
}
assert!(key.is_none(), "a key with no value at the end");
pairs
}
#[cfg(unix)]
#[test]
fn the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let stand_in = dir.path().join("program");
std::fs::write(&stand_in, b"not a real program").unwrap();
let version = "0.0.7";
let out = Command::new("bash")
.arg(root().join("deploy/packaging/macos/build-macos.sh"))
.arg(version)
.env("WB_PROGRAM", &stand_in)
.env("WB_NO_ICNS", "1")
.env("WB_BUNDLE_ONLY", "1")
.output()
.unwrap();
let app = root().join(format!(
"target/packages/.stage-macos-{version}/Wanderbooks.app"
));
let cleanup = Cleanup(root().join(format!("target/packages/.stage-macos-{version}")));
assert!(
out.status.success(),
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
let exe = app.join("Contents/MacOS/wanderbooks");
assert!(exe.is_file());
assert_ne!(
exe.metadata().unwrap().permissions().mode() & 0o111,
0,
"not executable"
);
let programs: Vec<_> = std::fs::read_dir(app.join("Contents/MacOS"))
.unwrap()
.collect();
assert_eq!(programs.len(), 1, "one program in the bundle");
for file in LICENCE_FILES {
assert!(
app.join("Contents/Resources").join(file).is_file(),
"{file}"
);
}
let info = std::fs::read_to_string(app.join("Contents/Info.plist")).unwrap();
assert!(!info.contains('@'), "an unfilled placeholder: {info}");
let pairs = plist(&info);
let get = |k: &str| {
pairs
.iter()
.find(|(key, _)| key == k)
.unwrap_or_else(|| panic!("{k} is missing from Info.plist"))
.1
.clone()
};
assert_eq!(get("CFBundleIdentifier"), "ai.wanderbooks.app");
assert_eq!(get("CFBundleName"), "Wanderbooks");
assert_eq!(get("CFBundleDisplayName"), "Wanderbooks");
assert_eq!(get("CFBundleExecutable"), "wanderbooks");
assert_eq!(get("CFBundleShortVersionString"), version);
assert_eq!(get("CFBundleVersion"), version);
assert_eq!(get("CFBundlePackageType"), "APPL");
assert_eq!(get("LSMinimumSystemVersion"), "11.0");
assert_eq!(get("LSMultipleInstancesProhibited"), "<true/>");
assert!(get("NSDocumentsFolderUsageDescription").contains("Documents"));
drop(cleanup);
}
/// Removes a folder when dropped (a test's own scratch under `target/`).
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn the_entitlements_are_empty_on_purpose_and_say_why() {
let text = read("deploy/packaging/macos/entitlements.plist");
assert!(
code(&text).contains(&"<dict/>"),
"no entitlement is claimed without a reason"
);
assert!(text.contains("hardened runtime"));
assert!(text.contains("NOT sandboxed"));
}
#[test]
fn the_macos_script_signs_only_with_an_identity_and_names_no_secret() {
let script = read("deploy/packaging/macos/build-macos.sh");
// Secrets come from the environment, by name; none is written here.
for name in [
"WB_SIGN_IDENTITY",
"WB_NOTARY_APPLE_ID",
"WB_NOTARY_TEAM_ID",
"WB_NOTARY_PASSWORD",
] {
assert!(script.contains(name), "{name}");
}
assert!(script.contains("--options runtime"), "the hardened runtime");
assert!(script.contains("entitlements.plist"));
assert!(script.contains("notarytool submit"));
assert!(script.contains("stapler staple"));
assert!(script.contains("lipo -create"), "universal");
for line in code(&script) {
assert!(
!line.contains("password=") || line.contains("$("),
"a literal password: {line}"
);
}
}
// ---- Linux ----------------------------------------------------------------------
/// The `Key=Value` lines of a desktop entry.
fn desktop(text: &str) -> Vec<(String, String)> {
text.lines()
.filter_map(|l| l.split_once('='))
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn the_desktop_entries_launch_plain_wanderbooks_with_the_icon_and_the_window_id() {
// The id the window announces, which the launcher matches (Wayland, and
// X11's WM class).
let gui = read("crates/ledger-gui/src/lib.rs");
assert!(gui.contains(r#".with_app_id("wanderbooks")"#));
for file in [
"deploy/packaging/wanderbooks-static.desktop",
"deploy/packaging/wanderbooks.desktop",
] {
let entries = desktop(&read(file));
let get = |k: &str| {
entries
.iter()
.find(|(key, _)| key == k)
.unwrap_or_else(|| panic!("{file}: {k} is missing"))
.1
.clone()
};
assert_eq!(get("Type"), "Application", "{file}");
assert_eq!(get("Terminal"), "false", "{file}");
assert_eq!(get("StartupWMClass"), "wanderbooks", "{file}");
let categories = get("Categories");
assert!(
categories.starts_with("{{") || categories.ends_with(';'),
"{file}: {categories}"
);
// An AppImage's launcher appends what it is given to the Exec line:
// it names the program and nothing else.
let exec = get("Exec");
assert!(
exec == "wanderbooks" || exec == "{{exec}}",
"{file}: {exec}"
);
let name = get("Name");
assert!(
name == "Wanderbooks" || name == "{{name}}",
"{file}: {name}"
);
let icon = get("Icon");
assert!(
icon == "wanderbooks" || icon == "{{icon}}",
"{file}: {icon}"
);
}
// The static entry (the .rpm's) is a valid desktop file.
if let Some(tool) = std::env::var_os("PATH").and_then(|p| {
std::env::split_paths(&p)
.map(|d| d.join("desktop-file-validate"))
.find(|f| f.is_file())
}) {
let out = Command::new(tool)
.arg(root().join("deploy/packaging/wanderbooks-static.desktop"))
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stdout)
);
}
}
/// WB-pkg-7: every package carries the licences, and the Linux packages
/// install the icon their desktop entry names.
#[test]
fn every_package_carries_the_licences_and_the_icon() {
let deb_pacman = read("deploy/packaging/packager.toml");
let rpm = read("crates/ledger-cli/Cargo.toml");
let rpm_script = read("deploy/packaging/build-linux.sh");
let windows = read("deploy/packaging/windows/wanderbooks.nsi");
let mac = read("deploy/packaging/macos/build-macos.sh");
for file in LICENCE_FILES {
assert!(
deb_pacman.contains(&format!("\"{file}\" = ")),
"deb or pacman lacks {file}"
);
assert_eq!(
deb_pacman.matches(&format!("\"{file}\" = ")).count(),
3,
"the deb, the AppImage and the pacman package each carry {file}"
);
assert!(
rpm.contains(&format!("source = \"{file}\"")),
"rpm lacks {file}"
);
assert!(
rpm_script.contains(&format!("source = \"{file}\"")),
"rpm script lacks {file}"
);
assert!(
windows.contains(&format!("/oname={file}")),
"windows lacks {file}"
);
assert!(mac.contains(file), "macos lacks {file}");
}
assert!(rpm.contains("512x512/apps/wanderbooks.png"));
assert!(rpm_script.contains("512x512/apps/wanderbooks.png"));
for file in LICENCE_FILES {
assert!(
root().join(file).is_file(),
"{file} is not in the repository"
);
}
}
#[test]
fn no_package_runs_a_script_that_could_touch_the_books() {
let packager = read("deploy/packaging/packager.toml");
for key in [
"postrm",
"post-remove",
"before-remove",
"preinst",
"postinst",
"after-install",
"scripts",
] {
assert!(!packager.contains(key), "{key} in packager.toml");
}
let rpm = read("crates/ledger-cli/Cargo.toml");
for key in [
"post_uninstall",
"pre_uninstall",
"post_install_script",
"pre_install_script",
] {
assert!(!rpm.contains(key), "{key} in Cargo.toml");
}
}
// ---- the release workflow -------------------------------------------------------
/// WB-pkg-7: the release builds all three packages, ends in a DRAFT with the
/// SHA-256 sums, runs only on a version tag or by hand, and publishes
/// nothing by itself.
#[test]
fn the_release_workflow_makes_a_draft_of_all_three_packages_and_publishes_nothing() {
let text = read(".github/workflows/release.yml");
let lines = code(&text);
let has = |needle: &str| lines.iter().any(|l| l.contains(needle));
// Triggers: a tag or by hand; never an ordinary push or a pull request.
let on = lines
.iter()
.position(|l| *l == "on:")
.expect("an `on:` block");
let jobs = lines.iter().position(|l| *l == "jobs:").expect("jobs");
let triggers: Vec<&&str> = lines[on + 1..jobs].iter().collect();
assert!(
triggers.iter().any(|l| l.starts_with("tags:")),
"{triggers:?}"
);
assert!(triggers.iter().any(|l| l.starts_with("workflow_dispatch:")));
assert!(
!triggers
.iter()
.any(|l| l.starts_with("pull_request") || l.starts_with("schedule"))
);
let push = triggers
.iter()
.position(|l| l.starts_with("push:"))
.unwrap();
assert!(
triggers[push + 1].starts_with("tags:"),
"a push trigger without tags"
);
// All three systems, each tested on its own system before packaging.
for runner in ["ubuntu-24.04", "windows-latest", "macos-latest"] {
assert!(has(&format!("runs-on: {runner}")), "{runner}");
}
assert_eq!(
lines
.iter()
.filter(|l| l.contains("cargo test --workspace --no-fail-fast"))
.count(),
3,
"each system runs the workspace's tests"
);
// The three packages, the sums, the licences and the update note.
for needle in [
"just package-linux",
"build-windows.sh",
"build-macos.sh",
"sha256sum",
"SHA256SUMS.txt",
"THIRD-PARTY-NOTICES.txt",
"LICENSE-MIT",
"LICENSE-APACHE",
"latest.json",
"scripts/notices.sh --check",
] {
assert!(has(needle), "{needle} is not in the release workflow");
}
// A draft, never published, never a published release touched.
assert!(has("gh release create"));
assert!(has("--draft"));
for never in [
"--draft=false",
"gh release edit",
"gh-pages",
"prerelease=false",
"make_latest",
] {
assert!(!has(never), "{never} would publish");
}
assert!(has("never changes a published release"));
// Secrets are read by name from the secrets store, never written here.
for secret in [
"WINDOWS_CERTIFICATE_PFX_BASE64",
"APPLE_CERTIFICATE_P12_BASE64",
"APPLE_SIGNING_IDENTITY",
"APPLE_APP_SPECIFIC_PASSWORD",
] {
assert!(has(&format!("${{{{ secrets.{secret} }}}}")), "{secret}");
}
// Signing steps say so when they are skipped.
assert!(has("macOS signing skipped"));
assert!(read("deploy/packaging/windows/sign-windows.ps1").contains("Windows signing skipped"));
assert!(read("deploy/packaging/macos/build-macos.sh").contains("macOS notarization skipped"));
// The Windows job installs and uninstalls the installer, and checks the
// books' folder survives.
assert!(has("THE UNINSTALLER REMOVED THE BOOKS' FOLDER"));
assert!(has("subsystem -ne 2"));
}
#[test]
fn only_a_person_runs_the_workflow_that_publishes_the_repositories() {
let text = read(".github/workflows/publish-repos.yml");
let lines = code(&text);
let on = lines.iter().position(|l| *l == "on:").unwrap();
let jobs = lines.iter().position(|l| *l == "jobs:").unwrap();
for l in &lines[on + 1..jobs] {
assert!(
!(l.starts_with("push:") || l.starts_with("pull_request") || l.starts_with("schedule")),
"{l}: only workflow_dispatch may start it"
);
}
assert!(lines.iter().any(|l| l.starts_with("workflow_dispatch:")));
assert!(
lines.iter().any(|l| l.contains("isDraft")),
"it refuses a draft"
);
}
/// WB-pkg-4: on Linux git is a dependency of every package, so the package
/// manager fetches it; nothing carries a git of its own.
#[test]
fn the_linux_packages_depend_on_git_and_none_carries_one() {
let packager = read("deploy/packaging/packager.toml");
assert_eq!(
packager.matches("\"git\"").count(),
2,
"the deb and the pacman package depend on git"
);
assert!(read("crates/ledger-cli/Cargo.toml").contains("requires = { git = \"*\" }"));
assert!(read("deploy/packaging/aur/PKGBUILD").contains("'git'"));
for file in [
"deploy/packaging/windows/wanderbooks.nsi",
"deploy/packaging/macos/build-macos.sh",
] {
let text = read(file).to_lowercase();
assert!(
!text.contains("mingit") && !text.contains("git.exe"),
"{file} bundles a git"
);
}
}
+1 -1
View File
@@ -214,7 +214,7 @@ const WARN_AGE: std::time::Duration = std::time::Duration::from_secs(60);
const FIRST_CONNECT_KEY: &str = "first_connect_done";
/// What a window is called when no company is in front.
const TITLE: &str = "wanderbooks";
const TITLE: &str = "Wanderbooks";
impl App {
/// The live app over one company's books directory.
+81
View File
@@ -424,6 +424,9 @@ pub struct State {
new_address_asked: bool,
/// The address was just copied (the time, for the word "Copied").
copied_at: Option<f64>,
/// The folder the Claude desktop extension was written in, once it
/// was (set by the job that made it).
extension_folder: Arc<std::sync::Mutex<Option<String>>>,
}
/// The two lines an assistant set up by hand needs.
@@ -807,6 +810,7 @@ impl State {
want = Some(w);
}
}
self.desktop_row(ui, status, book, &owner, busy, &mut want);
another_row(ui, status, book, &owner, &commands, busy, &mut want);
if let Some((what, keep, work)) = want {
self.start(ui, jobs, what, &keep, work);
@@ -842,6 +846,83 @@ impl State {
});
}
/// The "Claude desktop app" row (WB-pkg-5): one button that writes the
/// one-click extension, and the steps that follow, in plain words.
fn desktop_row(
&mut self,
ui: &mut Ui,
status: &Status,
book: &str,
owner: &Option<Arc<dyn Owner>>,
busy: bool,
want: &mut Want,
) {
let p = pal(ui.ctx());
let made = self
.extension_folder
.lock()
.map(|f| f.clone())
.unwrap_or_default();
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("Claude desktop app").font(theme::semibold(14.5)));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if let Some(owner) = owner
&& ui
.add_enabled(!busy, egui::Button::new("Make the Claude extension"))
.on_hover_text(
"Writes one file you open in the Claude desktop app to add these books",
)
.clicked()
{
let (o, b, company) =
(owner.clone(), book.to_string(), status.company.clone());
let folder = self.extension_folder.clone();
*want = Some((
"Claude desktop extension".to_string(),
"Making the Claude desktop extension".to_string(),
Box::new(move || {
o.claude_desktop_extension(&b, &company).map(|made| {
if let Ok(mut f) = folder.lock() {
*f = Some(made.folder.clone());
}
format!(
"made {}. Next: open the Claude desktop app, go to Settings, then Extensions, then Advanced settings, choose Install Extension, and pick that file (or just open the file). Keep Wanderbooks open while you use Claude.",
made.file
)
})
}),
));
}
});
});
ui.add_space(4.0);
ui.label(
RichText::new(
"Adds these books to the Claude app on this computer with one file, so you type nothing.",
)
.font(theme::regular(13.0))
.color(p.muted),
);
if let Some(folder) = made {
ui.add_space(4.0);
if ui
.button(format!("{} Show the file", icon::FOLDER_OPEN))
.clicked()
{
crate::export::open(std::path::Path::new(&folder));
}
}
});
ui.add_space(6.0);
}
/// "Connections": every key to these books, who is connected on it,
/// what it may do, when it last did anything, and Revoke.
fn connections(
+11 -4
View File
@@ -141,10 +141,17 @@ pub fn open(path: &Path) {
#[cfg(target_os = "macos")]
let cmd = std::process::Command::new("open").arg(path).spawn();
#[cfg(target_os = "windows")]
let cmd = std::process::Command::new("cmd")
.args(["/C", "start", ""])
.arg(path)
.spawn();
let cmd = {
// The window has no console (WB-pkg-2): a console program it
// starts would open one for a moment, so it is told not to
// (CREATE_NO_WINDOW).
use std::os::windows::process::CommandExt;
std::process::Command::new("cmd")
.args(["/C", "start", ""])
.arg(path)
.creation_flags(0x0800_0000)
.spawn()
};
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let cmd = std::process::Command::new("xdg-open").arg(path).spawn();
let _ = cmd;
+33 -7
View File
@@ -138,14 +138,21 @@ pub fn run(
},
},
};
let mut viewport = egui::ViewportBuilder::default()
.with_title("Wanderbooks")
.with_app_id("wanderbooks")
.with_inner_size([1440.0, 920.0])
// Small on purpose: tiling window managers hand out small slots
// regardless, and every screen lays itself out to fit.
.with_min_inner_size([360.0, 400.0]);
// The window's own icon (the taskbar on Windows, X11): the packages'
// icon. macOS takes its icon from the app bundle, Wayland from the
// desktop entry; a failure to decode leaves the system's default.
if let Some(icon) = window_icon() {
viewport = viewport.with_icon(std::sync::Arc::new(icon));
}
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("wanderbooks")
.with_app_id("wanderbooks")
.with_inner_size([1440.0, 920.0])
// Small on purpose: tiling window managers hand out small slots
// regardless, and every screen lays itself out to fit.
.with_min_inner_size([360.0, 400.0]),
viewport,
// The platform's place for app settings, never the books' folder
// (prefs.rs).
persistence_path: prefs::prepare(),
@@ -201,3 +208,22 @@ mod exit_tests {
assert_eq!(Exit(1).to_string(), "exit code 1");
}
}
/// The icon every package carries (`deploy/packaging/icons`), as the window's
/// own (WB-pkg-6).
fn window_icon() -> Option<egui::IconData> {
eframe::icon_data::from_png_bytes(include_bytes!(
"../../../deploy/packaging/icons/512x512.png"
))
.ok()
}
#[cfg(test)]
mod window_icon_tests {
#[test]
fn the_windows_icon_is_the_packages_icon() {
let icon = super::window_icon().expect("the icon decodes");
assert_eq!((icon.width, icon.height), (512, 512));
assert_eq!(icon.rgba.len(), 512 * 512 * 4);
}
}
+95 -6
View File
@@ -412,6 +412,16 @@ pub trait Owner: Send + Sync {
fn command_line(&self, _words: &[&str]) -> Result<String, String> {
Err("not here".into())
}
/// The Claude desktop extension for the company `book` (shown as
/// `company`): the one-click package written where a person can open it,
/// the key made first if there was none. Blocks.
fn claude_desktop_extension(
&self,
_book: &str,
_company: &str,
) -> Result<ExtensionMade, 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
@@ -464,6 +474,11 @@ pub trait Owner: Send + Sync {
fn check_for_updates(&self) -> Result<Vec<String>, String> {
Err("not here".into())
}
/// A newer version exists, and where to get it (WB-pkg-3): what the
/// program's daily look found. Cheap: called every few seconds.
fn newer_version(&self) -> Option<NewerVersion> {
None
}
/// Accept the waiting update: the books' host installs it and restarts
/// onto it when no call is running, the books staying open.
fn apply_update(&self) -> Result<Vec<String>, String> {
@@ -476,6 +491,25 @@ pub trait Owner: Send + Sync {
}
}
/// A newer version of the program that the person may get and install over
/// this one (WB-pkg-3).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewerVersion {
/// Its version.
pub version: String,
/// The page to get it from: the program's own, never a feed's.
pub page: String,
}
/// The Claude desktop extension the Connect page made (WB-pkg-5).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtensionMade {
/// The package file, in full.
pub file: String,
/// The folder it is in.
pub folder: String,
}
/// The owner the program gave the viewer, for every company's view that
/// isn't given one of its own. It is the program's (one per process, as
/// the program is one), not a company's: each view takes a handle to it
@@ -623,6 +657,8 @@ pub struct OwnerMenu {
/// The update waiting, as last read, and when (re-read every few
/// seconds and after any job).
update: Option<(std::time::Instant, Option<UpdateWaiting>)>,
/// A newer version the person may get, as last read, and when.
newer: Option<(std::time::Instant, Option<NewerVersion>)>,
/// The tab's threads: every job is one of them (INVARIANT 6).
jobs: crate::jobs::Spawner,
}
@@ -668,6 +704,23 @@ impl OwnerMenu {
self.update.as_ref().and_then(|(_, u)| u.clone())
}
/// A newer version to get, if any (read now and then, not every frame).
fn newer_version(
&mut self,
ctx: &egui::Context,
owner: &Arc<dyn Owner>,
) -> Option<NewerVersion> {
if self
.newer
.as_ref()
.is_none_or(|(at, _)| at.elapsed() > UPDATE_LOOK)
{
self.newer = Some((std::time::Instant::now(), owner.newer_version()));
}
ctx.request_repaint_after(UPDATE_LOOK);
self.newer.as_ref().and_then(|(_, n)| n.clone())
}
/// The standing notices above the page: an update waiting for the
/// owner's accept, and a format upgrade the books wait for, whose
/// go-ahead is asked for once each open (INVARIANT 5).
@@ -689,7 +742,7 @@ impl OwnerMenu {
ui.horizontal_wrapped(|ui| {
ui.label(
RichText::new(format!(
"{} Version {} of wanderbooks is ready.",
"{} Version {} of Wanderbooks is ready.",
icon::ARROW_FAT_UP,
update.version
))
@@ -719,12 +772,48 @@ impl OwnerMenu {
ui.ctx(),
(
"Update".into(),
Effect::Changes("Updating wanderbooks"),
Effect::Changes("Updating Wanderbooks"),
work,
),
);
}
}
// No update of the program's own is waiting: is a newer version
// out for the person to get and install over this one?
else if let Some(newer) = self.newer_version(ui.ctx(), &owner) {
let p = crate::theme::pal(ui.ctx());
egui::Frame::new()
.fill(p.warning_soft)
.inner_margin(egui::Margin::symmetric(20, 10))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal_wrapped(|ui| {
ui.label(
RichText::new(format!(
"{} Version {} of Wanderbooks is available.",
icon::ARROW_FAT_UP,
newer.version
))
.font(crate::theme::semibold(13.0))
.color(p.warning),
);
ui.label(
RichText::new(
"Download it and install it over this one. Your books, keys and connections stay as they are.",
)
.font(crate::theme::regular(13.0))
.color(p.text),
);
if ui
.button("Open the download page")
.on_hover_text(newer.page.clone())
.clicked()
{
ui.ctx().open_url(egui::OpenUrl::new_tab(newer.page.clone()));
}
});
});
}
let Some(upgrade) = books.format_upgrade.clone() else {
return;
};
@@ -752,7 +841,7 @@ impl OwnerMenu {
);
ui.label(
RichText::new(
"An older version of wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.",
"An older version of Wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.",
)
.font(crate::theme::regular(13.0))
.color(p.text),
@@ -867,7 +956,7 @@ impl OwnerMenu {
ui.separator();
if ui
.button(format!("{} Check for updates", icon::ARROWS_CLOCKWISE))
.on_hover_text("Look for a newer version of wanderbooks now")
.on_hover_text("Look for a newer version of Wanderbooks now")
.clicked()
{
let o = owner.clone();
@@ -886,7 +975,7 @@ impl OwnerMenu {
let o = owner.clone();
start = Some((
"Update".into(),
Effect::Changes("Updating wanderbooks"),
Effect::Changes("Updating Wanderbooks"),
Box::new(move || o.apply_update()),
));
}
@@ -1148,7 +1237,7 @@ fn upgrade_dialog(
ui.heading("Upgrade these books' format?");
ui.add_space(4.0);
ui.label(format!(
"An older version of wanderbooks wrote these books, in journal format {}. The upgrade adds {}.",
"An older version of Wanderbooks wrote these books, in journal format {}. The upgrade adds {}.",
form.upgrade.from.format,
form.upgrade.adds().join(", ")
));
+1 -1
View File
@@ -158,7 +158,7 @@ impl Welcome {
ui.vertical_centered(|ui| {
ui.set_max_width(640.0);
ui.add_space(36.0);
ui.label(RichText::new("Welcome to wanderbooks").font(crate::theme::bold(28.0)));
ui.label(RichText::new("Welcome to Wanderbooks").font(crate::theme::bold(28.0)));
ui.label(
RichText::new(
"Your company's books, kept by an assistant and checked by you. A few short steps; nothing here needs a terminal.",
+55
View File
@@ -247,6 +247,17 @@ impl Owner for Fake {
self.note(format!("connect {} {book}", agent.key()));
Ok(vec![format!("{} reaches the books.", agent.label())])
}
fn claude_desktop_extension(
&self,
book: &str,
company: &str,
) -> Result<ledger_gui::owner::ExtensionMade, String> {
self.note(format!("extension {book} {company}"));
Ok(ledger_gui::owner::ExtensionMade {
file: "/docs/Wanderbooks/Extensions/wanderbooks-alpha.mcpb".into(),
folder: "/docs/Wanderbooks/Extensions".into(),
})
}
fn new_books(&self, _: &str, _: &str) -> Result<String, String> {
Err("not here".into())
}
@@ -731,6 +742,50 @@ fn the_connect_buttons_do_what_connect_does() {
drop(h);
}
/// WB-pkg-5: the "Claude desktop app" row makes the extension for this
/// company through the owner, then says in words what to do with the file.
#[test]
fn the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next() {
let w = World::new(&[("alpha", "Wanderland Labs")]);
let owner = Fake::new();
owner.answer(roster(vec![], vec![]));
let mut h = start(&w, &["alpha"], &owner);
refresh(&mut h);
h.state_mut().goto(Route::Connect);
h.run_steps(3);
assert!(h.query_by_label_contains("Claude desktop app").is_some());
assert!(
h.query_by_label_contains("Show the file").is_none(),
"nothing is made yet"
);
h.get_by_role_and_label(Role::Button, "Make the Claude extension")
.click();
h.run_steps(2);
wait_for("the extension was made", || {
owner
.said()
.contains(&"extension alpha Wanderland Labs".to_string())
});
until(&mut h, "it said what came of it", |a| {
a.views()[0].connect_state().said().is_some()
});
h.run_steps(2);
for words in [
"wanderbooks-alpha.mcpb",
"Settings",
"Extensions",
"Install Extension",
"Keep Wanderbooks open",
] {
assert!(
h.query_by_label_contains(words).is_some(),
"{words} is said on the page"
);
}
assert!(h.query_by_label_contains("Show the file").is_some());
drop(h);
}
// ---- 5: the warning before a close ---------------------------------------------
fn connected_alpha(owner: &Fake) {
@@ -1 +1 @@
b2f05e2383abc93a
c44ce509bf9179de
@@ -1 +1 @@
982cea77ed6d057f
ceb2e1edc0d868ff
+7 -7
View File
@@ -336,7 +336,7 @@ fn each_tab_shows_its_own_company_and_figures() {
loaded(&mut h);
assert_eq!(titles(&h), ["Alpha Co", "Beta Co"]);
assert_eq!(h.state().active(), Some(0));
assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks");
assert_eq!(h.state().window_title(), "Alpha Co · Wanderbooks");
// Alpha: cash 10,000.00 less 1,234.56 rent is 8,765.44.
assert!(shows(&h, "8,765.44"), "alpha's cash: {:?}", texts(&h));
@@ -354,7 +354,7 @@ fn each_tab_shows_its_own_company_and_figures() {
// Beta: cash 25,000.00 less 777.77 is 24,222.23.
show_tab(&mut h, "Beta Co");
assert_eq!(h.state().active(), Some(1));
assert_eq!(h.state().window_title(), "Beta Co · wanderbooks");
assert_eq!(h.state().window_title(), "Beta Co · Wanderbooks");
assert!(
matches!(h.state().route(), Route::Overview),
"a tab opens on its overview, not on the page the other was on"
@@ -768,7 +768,7 @@ fn start_up_restores_the_open_tabs_their_order_and_the_one_in_front() {
assert_eq!(titles(&h), ["Gamma Co", "Alpha Co", "Beta Co"]);
assert_eq!(h.state().active(), Some(1), "the same one in front");
assert!(h.state().views().iter().all(|v| v.error().is_none()));
assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks");
assert_eq!(h.state().window_title(), "Alpha Co · Wanderbooks");
// No record: the data root's first, alone.
let h2 = start_with_prefs(&w, &[]);
@@ -894,15 +894,15 @@ fn closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window()
show_tab(&mut h, "Beta Co");
close_tab(&mut h, "Beta Co");
assert_eq!(titles(&h), ["Alpha Co", "Gamma Co"]);
assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks");
assert_eq!(h.state().window_title(), "Gamma Co · Wanderbooks");
// A tab behind the front one closing leaves the front one in front.
close_tab(&mut h, "Alpha Co");
assert_eq!(titles(&h), ["Gamma Co"]);
assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks");
assert_eq!(h.state().window_title(), "Gamma Co · Wanderbooks");
// The last one.
close_tab(&mut h, "Gamma Co");
assert!(h.state().views().is_empty());
assert_eq!(h.state().window_title(), "wanderbooks");
assert_eq!(h.state().window_title(), "Wanderbooks");
assert!(shows(&h, "No company is open"), "{:?}", texts(&h));
assert!(
shows(&h, "Open a company with the + at the top of the window."),
@@ -1737,7 +1737,7 @@ fn the_status_card_shows_the_company_in_front_and_follows_the_tab() {
"alpha's hue left the card"
);
// The window's title still names the company.
assert_eq!(h.state().window_title(), "Beta Co · wanderbooks");
assert_eq!(h.state().window_title(), "Beta Co · Wanderbooks");
}
}
+57 -2
View File
@@ -21,6 +21,7 @@ use std::sync::{Arc, Mutex, OnceLock};
struct Fake {
asked: Mutex<Vec<String>>,
staged: Mutex<bool>,
newer: Mutex<bool>,
}
impl Fake {
@@ -57,6 +58,12 @@ impl Owner for Fake {
staged_at: "2026-10-30T08:00:00Z".into(),
})
}
fn newer_version(&self) -> Option<ledger_gui::owner::NewerVersion> {
(*self.newer.lock().unwrap()).then(|| ledger_gui::owner::NewerVersion {
version: "9.2.0".into(),
page: "https://example.test/releases/latest".into(),
})
}
fn check_for_updates(&self) -> Result<Vec<String>, String> {
self.said("check");
*self.staged.lock().unwrap() = true;
@@ -159,7 +166,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts(
// owner, and the notice goes once it is installed.
for _ in 0..60 {
h.run_steps(2);
if h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready")
if h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready")
.is_some()
{
break;
@@ -167,7 +174,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts(
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(
h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready")
h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready")
.is_some(),
"no notice"
);
@@ -194,3 +201,51 @@ fn books_outside_a_data_root_have_no_update_notice() {
assert!(h.query_by_label_contains("is ready.").is_none());
*f.staged.lock().unwrap() = false;
}
/// WB-pkg-3: with no update of the program's own waiting, a newer version
/// the daily look found is told in a standing notice that says where to
/// get it and that books, keys and connections stay; an update that is
/// waiting is the only notice shown (one at a time).
#[test]
fn a_newer_version_is_told_with_where_to_get_it() {
let _alone = alone();
let f = fake();
*f.newer.lock().unwrap() = true;
let (_dir, _book, b) = books(true);
let mut h = harness(b);
for _ in 0..60 {
h.run_steps(2);
if h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available")
.is_some()
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(
h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available")
.is_some(),
"no notice"
);
assert!(
h.query_by_label_contains("Your books, keys and connections stay as they are")
.is_some()
);
assert!(h.query_by_label("Open the download page").is_some());
// One notice at a time: a staged update wins.
*f.staged.lock().unwrap() = true;
for _ in 0..60 {
h.run_steps(2);
if h.query_by_label_contains("is ready.").is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(h.query_by_label_contains("is ready.").is_some());
assert!(
h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available")
.is_none()
);
*f.staged.lock().unwrap() = false;
*f.newer.lock().unwrap() = false;
}
+2
View File
@@ -25,6 +25,8 @@ rpassword = "7"
# Token texts and passphrases are wiped from memory when dropped.
zeroize = "1"
minisign-verify = "0.3.0"
# The Claude desktop extension is a zip file (extension.rs).
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+45 -30
View File
@@ -1525,39 +1525,45 @@ pub fn update_waiting(_common: &Common) -> Option<UpdateWaiting> {
None
}
/// "Check for updates": look at the feed now, whatever the daily look
/// last did, and stage a newer release if there is one (it never swaps
/// the program: accepting is [`apply_update`]). What came of it.
#[cfg(unix)]
/// "Check for updates": say whether a newer version exists and where to
/// get it (the note of [`crate::newer`], looked at now whatever the last
/// look was). Where a program may replace itself (an AppImage, a program
/// put somewhere by hand, with a release key) a newer release is also
/// downloaded and checked, for [`apply_update`] (it never swaps the
/// program: accepting is). What came of it.
pub fn check_for_updates(common: &Common) -> Result<String, String> {
let found =
ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?;
let mine = crate::update::program_version();
if let crate::update::Install::PackageManaged(manager) = crate::update::this_install()? {
return Err(format!(
"this install is updated by {manager}, not here: use the package manager"
));
}
match crate::update::stage_if_due(&found, mine, Duration::ZERO) {
Ok(Some(version)) => Ok(format!(
"Version {version} is downloaded and checked. Accept it to start using it."
)),
Ok(None) => Ok(match update_waiting(common) {
Some(u) => format!(
"Version {} is downloaded and checked. Accept it to start using it.",
u.version
),
None => format!("You have the newest version ({mine})."),
}),
Err(why) => Err(why.to_string()),
let mine = crate::program_version();
#[cfg(unix)]
if let Ok(crate::update::Install::SelfUpdating(_)) = crate::update::this_install() {
match crate::update::stage_if_due(&found, mine, Duration::ZERO) {
Ok(Some(version)) => {
return Ok(format!(
"Version {version} is downloaded and checked. Accept it to start using it."
));
}
Ok(None) => {
if let Some(u) = update_waiting(common) {
return Ok(format!(
"Version {} is downloaded and checked. Accept it to start using it.",
u.version
));
}
}
// No release key or local feed: the look below still tells.
Err(_) => {}
}
}
crate::newer::check_now(found.path(), mine)
}
/// Checking for updates isn't built for this platform: say so, and
/// change nothing.
#[cfg(not(unix))]
pub fn check_for_updates(_common: &Common) -> Result<String, String> {
Err(NO_SELF_UPDATE.into())
/// The newer version the window may tell the person of, with where to get
/// it: what the last (daily) look found, a look begun when one is due.
pub fn newer_version(common: &Common) -> Option<(String, &'static str)> {
let found = ledger_store::root::Root::find(common.root.as_deref()).ok()?;
let version = crate::newer::found_and_refresh(found.path(), crate::program_version())?;
Some((version, crate::newer::DOWNLOAD_PAGE))
}
/// Accept the staged update: the books' host installs it and restarts
@@ -1893,7 +1899,7 @@ pub fn ensure_key(
/// 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> {
pub(crate) 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();
@@ -1967,11 +1973,20 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result<Vec<Str
// Each call within a minute: an agent's command that hangs is said,
// never waited on for good.
let run_cli = |args: Vec<std::ffi::OsString>| -> Result<std::process::Output, String> {
let mut child = std::process::Command::new(&program)
let mut command = std::process::Command::new(&program);
command
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
// The window has no console (WB-pkg-2): this one is not to open
// a console of its own for a moment (CREATE_NO_WINDOW).
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000);
}
let mut child = command
.spawn()
.map_err(|e| format!("{label} couldn't be run: {}", e.kind()))?;
let deadline = std::time::Instant::now() + CONNECT_WAIT;
+317
View File
@@ -0,0 +1,317 @@
//! The Claude desktop extension for a company (plan P15 unit C1, 3.3).
//!
//! The Connect page's "Claude desktop app" row writes a one-click
//! extension package that makes the Claude desktop app run this program's
//! bridge (`wanderbooks mcp --book X`) for one company. The format is
//! Anthropic's MCP Bundle ("MCPB"): a zip archive, extension `.mcpb`,
//! holding a `manifest.json`. (The format was called "Desktop Extension",
//! `.dxt`, until it was renamed; the manifest spec's page says so.)
//!
//! ```text
//! GOAL: a person double-clicks one file, or picks it under Claude
//! desktop's Settings > Extensions > Advanced settings > Install
//! Extension, and Claude can keep that company's books, with no
//! command typed and no file edited.
//! SOURCE: WB-pkg-5; Anthropic's MCP Bundle manifest specification,
//! version 0.3 (the manifest page and the version 0.3 JSON
//! schema of Anthropic's mcpb repository on GitHub, read
//! 2026-11-21) and Claude's help article "Getting started with
//! Local MCP servers on Claude Desktop" (the install steps).
//! INVARIANTS:
//! 1. The manifest holds only fields the specification defines, with
//! `manifest_version` "0.3", a `server` of type `binary` whose
//! `mcp_config.command` is this program's own stable path (the one a
//! terminal agent is registered with: `commands::bridge_serve_args`,
//! which refuses a translocated app) and whose arguments are `mcp
//! --book <id>` (and `--root` when the root was named). The package
//! carries no program: the one executable is the installed one, so
//! an update of the app is an update of the extension.
//! 2. No key, token, passphrase or path of the data root is in the
//! package: the bridge reads its key from the token file the app
//! keeps, as it does for a terminal agent (`ensure_agent_key` makes
//! it, once).
//! 3. The package is written under `<Documents>/Wanderbooks/Extensions/`
//! (a folder a person can open; not a book's home, which holds four
//! files and nothing else), by a temporary file and a rename.
//! 4. The package is for the system it was made on (`platforms`).
//! SCENARIOS:
//! 1. IF the program is installed at a stable path: SHOULD write
//! `wanderbooks-<id>.mcpb` that validates against the 0.3 schema.
//! 2. IF the program runs from a translocated macOS copy: SHOULD write
//! nothing and say to move it first.
//! 3. IF the company's name holds quotes, markup or a very long text:
//! SHOULD appear as text in the manifest, bounded.
//! ```
//!
//! Not run against a real Claude desktop app by the author (written on
//! Linux, with no Claude desktop at hand): the manifest is checked
//! against the published schema in `crates/ledger-cli/tests/extension.rs`;
//! that Claude accepts a `binary` extension whose command is an absolute
//! path to a program outside the package is the part to try first on a
//! real install.
use crate::commands::Common;
use serde_json::{Value, json};
use std::io::Write;
use std::path::{Path, PathBuf};
/// The manifest specification this package follows.
pub const MANIFEST_VERSION: &str = "0.3";
/// The icon the package carries (the app's own, 512 px).
const ICON: &[u8] = include_bytes!("../../../deploy/packaging/icons/512x512.png");
/// The longest company name or description put in a manifest, in
/// characters.
const LONGEST: usize = 120;
/// What was written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Made {
/// The package.
pub path: PathBuf,
/// The folder it is in, for the person to open.
pub folder: PathBuf,
}
/// `<documents>/Wanderbooks/Extensions`: where the packages go. A book's id
/// is lower case, so no company's books home can have this name.
pub fn extensions_dir_in(documents: &Path) -> PathBuf {
documents.join("Wanderbooks").join("Extensions")
}
/// The file's name for a book: `wanderbooks-<id>.mcpb`.
pub fn file_name(book: &str) -> String {
format!("wanderbooks-{book}.mcpb")
}
/// `process.platform`'s name for this system, as the manifest's
/// `compatibility.platforms` spells it.
pub fn platform_name() -> &'static str {
match std::env::consts::OS {
"macos" => "darwin",
"windows" => "win32",
other => other,
}
}
/// `text` cut to [`LONGEST`] characters, with control characters turned
/// into spaces: a name is text in the manifest and nothing else.
fn tidy(text: &str) -> String {
text.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.take(LONGEST)
.collect::<String>()
.trim()
.to_string()
}
/// The manifest (INVARIANT 1) for `book`, kept by `company`, run by
/// `command` with `args`, made for `platform`.
pub fn manifest(
book: &str,
company: &str,
version: &str,
command: &str,
args: &[String],
platform: &str,
) -> Value {
let company = match tidy(company) {
name if name.is_empty() => book.to_string(),
name => name,
};
json!({
"manifest_version": MANIFEST_VERSION,
"name": format!("wanderbooks-{book}"),
"display_name": format!("Wanderbooks: {company}"),
"version": version,
"description": format!("Lets Claude keep the books of {company} in Wanderbooks."),
"long_description": format!(
"Connects the Claude desktop app to the books of {company}, which Wanderbooks keeps on this computer. Claude reads them, drafts entries and, when you let it, posts them. Wanderbooks must be open, with these books open in a tab, for Claude to reach them."
),
"author": { "name": "Wanderbooks", "url": "https://wanderbooks.ai" },
"homepage": "https://wanderbooks.ai",
"icon": "icon.png",
"license": "MIT OR Apache-2.0",
"keywords": ["bookkeeping", "accounting", "wanderbooks"],
"server": {
"type": "binary",
"entry_point": "server/README.txt",
"mcp_config": { "command": command, "args": args }
},
"tools_generated": true,
"compatibility": { "platforms": [platform] }
})
}
/// What `server/README.txt` says (the manifest's entry point is a file in
/// the package; the program it names is the installed one).
const README: &str = "This extension carries no program of its own.\n\
It runs the Wanderbooks app you installed, as `wanderbooks mcp --book <id>`,\n\
so Claude can keep one company's books. Open Wanderbooks first, with those\n\
books open in a tab. If you move or reinstall Wanderbooks somewhere else,\n\
make this extension again from the app's Assistants page.\n";
/// The package's bytes: a zip of `manifest.json`, `icon.png` and
/// `server/README.txt` (INVARIANT 1).
pub fn package_bytes(manifest: &Value) -> Result<Vec<u8>, String> {
use zip::write::SimpleFileOptions;
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
let text = serde_json::to_vec_pretty(manifest).map_err(|e| e.to_string())?;
let mut out = std::io::Cursor::new(Vec::new());
let mut zip = zip::ZipWriter::new(&mut out);
let mut add = |name: &str, bytes: &[u8]| -> Result<(), String> {
zip.start_file(name, options)
.map_err(|e| format!("can't make the package: {e}"))?;
zip.write_all(bytes)
.map_err(|e| format!("can't make the package: {e}"))
};
add("manifest.json", &text)?;
add("icon.png", ICON)?;
add("server/README.txt", README.as_bytes())?;
zip.finish()
.map_err(|e| format!("can't make the package: {e}"))?;
Ok(out.into_inner())
}
/// Write the extension for `book` (company `company`) under `documents`,
/// for the program and arguments `bridge` (`program, args…`). The key is
/// the caller's to have made (INVARIANT 2).
pub fn write_in(
documents: &Path,
book: &str,
company: &str,
version: &str,
bridge: &[std::ffi::OsString],
) -> Result<Made, String> {
let book = ledger_store::root::BookId::parse(book)
.map_err(|e| e.to_string())?
.to_string();
if !documents.is_absolute() {
return Err("there is no documents folder to put the extension in".into());
}
let (command, args) = bridge
.split_first()
.ok_or("the bridge's command could not be worked out")?;
let as_text = |part: &std::ffi::OsStr| {
part.to_str()
.map(str::to_string)
.ok_or_else(|| "the program's path is not text Claude can be given".to_string())
};
let command = as_text(command)?;
let args = args
.iter()
.map(|a| as_text(a))
.collect::<Result<Vec<_>, _>>()?;
let bytes = package_bytes(&manifest(
&book,
company,
version,
&command,
&args,
platform_name(),
))?;
let folder = extensions_dir_in(documents);
std::fs::create_dir_all(&folder)
.map_err(|e| format!("can't make {}: {}", folder.display(), e.kind()))?;
let path = folder.join(file_name(&book));
let tmp = folder.join(format!(".{}.tmp{}", file_name(&book), std::process::id()));
std::fs::write(&tmp, &bytes).map_err(|e| format!("can't write the package: {}", e.kind()))?;
std::fs::rename(&tmp, &path).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("can't write the package: {}", e.kind())
})?;
Ok(Made { path, folder })
}
/// The Claude desktop extension for `book`, in the person's Documents:
/// the agent key made if there is none, then the package (the words
/// above). What was made.
pub fn claude_desktop_extension(
common: &Common,
book: &str,
company: &str,
) -> Result<Made, String> {
let documents = crate::commands::documents_dir()
.ok_or("there is no documents folder to put the extension in")?;
// The stable path first: a translocated copy refuses here, before a
// key is made or a file written.
let bridge = crate::commands::bridge_serve_args(common, book)?;
crate::commands::ensure_agent_key(common, book)?;
write_in(&documents, book, company, crate::program_version(), &bridge)
}
#[cfg(test)]
mod tests {
use super::*;
fn bridge() -> Vec<std::ffi::OsString> {
["/opt/Wanderbooks/wanderbooks", "mcp", "--book", "acme"]
.map(Into::into)
.to_vec()
}
#[test]
fn the_package_is_written_where_a_person_can_open_it() {
let dir = tempfile::tempdir().unwrap();
let made = write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap();
assert_eq!(
made.path,
dir.path()
.join("Wanderbooks/Extensions/wanderbooks-acme.mcpb")
);
assert_eq!(made.folder, dir.path().join("Wanderbooks/Extensions"));
let file = std::fs::File::open(&made.path).unwrap();
let mut zip = zip::ZipArchive::new(file).unwrap();
let mut names: Vec<String> = (0..zip.len())
.map(|i| zip.by_index(i).unwrap().name().unwrap().to_string())
.collect();
names.sort();
assert_eq!(names, ["icon.png", "manifest.json", "server/README.txt"]);
// Written again, it replaces itself; nothing is left beside it.
write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap();
let left: Vec<_> = std::fs::read_dir(&made.folder).unwrap().collect();
assert_eq!(left.len(), 1);
}
#[test]
fn a_name_is_text_and_bounded() {
let long = "x".repeat(500);
let m = manifest(
"acme",
&format!("A\"<b>\n{long}"),
"1.0.0",
"/p",
&[],
"linux",
);
let shown = m["display_name"].as_str().unwrap();
assert!(
shown.chars().count() <= "Wanderbooks: ".len() + LONGEST,
"{shown}"
);
assert!(!shown.contains('\n'));
let none = manifest("acme", " ", "1.0.0", "/p", &[], "linux");
assert_eq!(none["display_name"], "Wanderbooks: acme");
}
#[test]
fn no_secret_and_no_data_root_is_in_the_package() {
let dir = tempfile::tempdir().unwrap();
let made = write_in(dir.path(), "acme", "Acme", "0.1.0", &bridge()).unwrap();
let mut zip = zip::ZipArchive::new(std::fs::File::open(&made.path).unwrap()).unwrap();
let mut text = String::new();
std::io::Read::read_to_string(&mut zip.by_name("manifest.json").unwrap(), &mut text)
.unwrap();
for word in ["token", "passphrase", "secret", "password", "bearer"] {
assert!(!text.to_lowercase().contains(word), "{word} in {text}");
}
assert!(text.contains("\"mcp\""), "{text}");
}
#[test]
fn a_relative_documents_folder_is_refused() {
let err = write_in(Path::new("Documents"), "acme", "Acme", "0.1.0", &bridge()).unwrap_err();
assert!(err.contains("documents folder"), "{err}");
}
}
+20
View File
@@ -20,9 +20,11 @@ pub mod app_server;
pub mod bridge;
pub mod channel;
pub mod commands;
pub mod extension;
pub mod host;
pub mod knobs;
pub mod lease;
pub mod newer;
pub mod opener;
mod start;
pub mod tokens;
@@ -30,6 +32,24 @@ pub mod tokens;
pub mod update;
pub mod web;
/// The version of the program being run, set by its `main` (this crate's
/// own is the fallback: the packages rewrite only the program's, whose
/// `Cargo.toml` is the one source of the version, WB-pkg-6).
static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
/// Say which version this program is.
pub fn set_program_version(version: &'static str) {
let _ = PROGRAM_VERSION.set(version);
}
/// This program's version.
pub fn program_version() -> &'static str {
PROGRAM_VERSION
.get()
.copied()
.unwrap_or(env!("CARGO_PKG_VERSION"))
}
/// How a mode stops when it can't go on: the reason is already printed,
/// and the number is the process's exit code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+289
View File
@@ -0,0 +1,289 @@
//! "A newer version exists, and where to get it" (plan P15 unit C1, 3.1:
//! update is an ordinary app update).
//!
//! The installed program is replaced by installing the newer package over
//! it (the installer on Windows, the `.dmg` on macOS, the package manager
//! or a new AppImage on Linux). The program's part is to tell the person
//! that one exists. This module is that part, on every platform: a look at
//! one small file a release publishes, at most once a day, and a note of
//! what it found in the data root.
//!
//! ```text
//! GOAL: a person who installed Wanderbooks is told, in the window, when a
//! newer version is out, and where to get it; nothing is downloaded
//! or installed by the program.
//! SOURCE: WB-pkg-3; plan/p15-app-and-relay.md 3.1 ("Update becomes an
//! ordinary app update"), D-24 (anything the program installs by
//! itself must be verified against our own release keys: this
//! installs nothing, so it needs none).
//! INVARIANTS:
//! 1. Only a version number is read from the feed: the place to get the
//! update is a fixed address in this program ([`DOWNLOAD_PAGE`]),
//! never one the feed names. A feed that lies can at most say a
//! number.
//! 2. The feed is looked at at most once a day ([`EVERY`]); a failed look
//! counts as a look (no hammering) and is never an error the person
//! sees. The look is never in the window's own thread.
//! 3. A version is "newer" only when it is a higher `x.y.z` than this
//! program's; anything else is no version of ours.
//! 4. The note is a small file in the data root's `updates/` folder,
//! private to the account; the books are not read or changed.
//! 5. The look sends no version, company, key or identifier of the
//! person: a plain request for a public file.
//! SCENARIOS:
//! 1. IF the feed says 0.2.0 and this is 0.1.0: SHOULD say 0.2.0 is
//! newer, for a day.
//! 2. IF the feed says the same, an older, or a word: SHOULD say nothing.
//! 3. IF the feed can't be reached: SHOULD say nothing and look again
//! tomorrow.
//! ```
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
/// The small file a release publishes: `{"version": "x.y.z"}`.
pub const FEED: &str = "https://github.com/swaits/wanderbooks/releases/latest/download/latest.json";
/// Where a person gets the newest version (INVARIANT 1).
pub const DOWNLOAD_PAGE: &str = "https://github.com/swaits/wanderbooks/releases/latest";
/// How often the feed is looked at (INVARIANT 2).
pub const EVERY: Duration = Duration::from_secs(24 * 60 * 60);
/// The note's name in `<root>/updates/`.
const NOTE: &str = "newer.json";
/// The longest feed read, in bytes.
const MAX_FEED: usize = 4096;
/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version
/// of ours.
pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
let mut parts = text.split('.');
let mut next = || -> Option<u64> {
let p = parts.next()?;
(!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
.then(|| p.parse().ok())
.flatten()
};
let v = (next()?, next()?, next()?);
parts.next().is_none().then_some(v)
}
/// Whether `theirs` is a version higher than `mine` (INVARIANT 3).
pub fn is_newer(mine: &str, theirs: &str) -> bool {
parse_version(theirs)
.zip(parse_version(mine))
.is_some_and(|(theirs, mine)| theirs > mine)
}
/// The version the feed's text names (INVARIANT 1): nothing else of it is
/// read.
pub fn version_in_feed(text: &str) -> Option<String> {
#[derive(Deserialize)]
struct Feed {
version: String,
}
let feed: Feed = serde_json::from_str(text).ok()?;
parse_version(&feed.version).map(|_| feed.version)
}
/// What the last look found.
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
struct Note {
/// Seconds since 1970 when the look was made.
looked: u64,
/// The version the feed named, when it named one.
version: Option<String>,
}
fn note_path(root: &Path) -> PathBuf {
root.join("updates").join(NOTE)
}
fn read_note(root: &Path) -> Option<Note> {
let bytes = std::fs::read(note_path(root)).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// The newer version the last look found, if it found one newer than
/// `mine` (a note about a version this program already is, or is past, is
/// nothing).
pub fn found(root: &Path, mine: &str) -> Option<String> {
read_note(root)?
.version
.filter(|theirs| is_newer(mine, theirs))
}
/// Whether the feed is due to be looked at at `now` (INVARIANT 2).
pub fn due(root: &Path, now: u64) -> bool {
read_note(root)
.is_none_or(|n| now.saturating_sub(n.looked) >= EVERY.as_secs() || n.looked > now)
}
/// Look at the feed through `fetch` (its text) and note what it said, at
/// `now`. A feed that can't be read is noted as a look with nothing found
/// (INVARIANT 2). The newer version, if there is one.
pub fn look(
root: &Path,
mine: &str,
now: u64,
fetch: impl FnOnce() -> Result<String, String>,
) -> Result<Option<String>, String> {
let said = fetch();
let version = said.as_deref().ok().and_then(version_in_feed);
let note = Note {
looked: now,
version: version.clone(),
};
let dir = root.join("updates");
ledger_link::private::make_dir(&dir).map_err(|e| e.kind().to_string())?;
let bytes = serde_json::to_vec(&note).map_err(|e| e.to_string())?;
ledger_link::private::write(&note_path(root), &bytes).map_err(|e| e.kind().to_string())?;
match said {
Ok(_) => Ok(version.filter(|theirs| is_newer(mine, theirs))),
Err(why) => Err(why),
}
}
/// The feed, over https: a plain request for a public file (INVARIANT 5).
pub fn fetch_feed() -> Result<String, String> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(async {
let mut response = reqwest::Client::new()
.get(FEED)
.timeout(Duration::from_secs(20))
.send()
.await
.and_then(|r| r.error_for_status())
.map_err(|e| format!("can't look for a newer version: {}", e.without_url()))?;
let mut bytes = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| format!("can't look for a newer version: {}", e.without_url()))?
{
bytes.extend_from_slice(&chunk);
if bytes.len() > MAX_FEED {
return Err("the release note is larger than it can be".to_string());
}
}
String::from_utf8(bytes).map_err(|_| "the release note is not text".to_string())
})
}
/// "Check for updates", now: look whatever the last look was, and say
/// what came of it in plain words.
pub fn check_now(root: &Path, mine: &str) -> Result<String, String> {
match look(root, mine, now_secs(), fetch_feed)? {
Some(version) => Ok(format!(
"Version {version} of Wanderbooks is available (this is {mine}). Get it at {DOWNLOAD_PAGE} and install it over this one: your books, keys and connections stay as they are."
)),
None => Ok(format!("You have the newest version ({mine}).")),
}
}
/// Whether a background look is under way.
static LOOKING: AtomicBool = AtomicBool::new(false);
/// The newer version known, and, when a look is due, one begun on a thread
/// of its own (INVARIANT 2): cheap, for the window to call every few
/// seconds.
pub fn found_and_refresh(root: &Path, mine: &'static str) -> Option<String> {
if due(root, now_secs())
&& LOOKING
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
let root = root.to_path_buf();
let started = std::thread::Builder::new()
.name("wanderbooks-newer".into())
.spawn(move || {
// Whatever it came to, it was a look (noted), and the next
// is a day away.
let _ = look(&root, mine, now_secs(), fetch_feed);
LOOKING.store(false, Ordering::SeqCst);
});
if started.is_err() {
LOOKING.store(false, Ordering::SeqCst);
}
}
found(root, mine)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_higher_plain_version_is_newer() {
assert!(is_newer("0.1.0", "0.2.0"));
assert!(is_newer("0.1.9", "0.1.10"));
assert!(!is_newer("0.2.0", "0.2.0"));
assert!(!is_newer("0.2.0", "0.1.9"));
for odd in ["v0.3.0", "0.3", "0.3.0-rc1", "", "latest", "1.2.3.4"] {
assert!(!is_newer("0.1.0", odd), "{odd}");
}
}
#[test]
fn the_feed_gives_a_version_and_nothing_else() {
assert_eq!(
version_in_feed(r#"{"version":"0.2.0","url":"https://evil.example/x"}"#),
Some("0.2.0".into())
);
assert_eq!(version_in_feed(r#"{"version":"soon"}"#), None);
assert_eq!(version_in_feed("not json"), None);
// Where to get it is this program's, never the feed's.
assert!(DOWNLOAD_PAGE.starts_with("https://github.com/swaits/wanderbooks/"));
}
#[test]
fn a_look_is_noted_and_the_next_is_a_day_away() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
assert!(due(root, 1_000));
let said = look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap();
assert_eq!(said, Some("0.2.0".into()));
assert_eq!(found(root, "0.1.0"), Some("0.2.0".into()));
assert!(!due(root, 1_000 + EVERY.as_secs() - 1));
assert!(due(root, 1_000 + EVERY.as_secs()));
// A clock that went backwards is due, not stuck for years.
assert!(due(root, 10));
// Once this program is that version, nothing is newer.
assert_eq!(found(root, "0.2.0"), None);
}
#[test]
fn a_failed_look_says_nothing_and_still_counts() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap();
let err = look(root, "0.1.0", 2_000, || Err("offline".into())).unwrap_err();
assert_eq!(err, "offline");
assert_eq!(found(root, "0.1.0"), None, "what was found is forgotten");
assert!(!due(root, 2_001), "the failed look counts");
}
#[cfg(unix)]
#[test]
fn the_note_is_private() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
look(dir.path(), "0.1.0", 1, || Ok("{}".into())).unwrap();
let mode = |p: PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(dir.path().join("updates")), 0o700);
assert_eq!(mode(note_path(dir.path())), 0o600);
}
}
+45 -29
View File
@@ -90,22 +90,7 @@ const STAGED: &str = "staged";
const FEED_FILE: &str = "feed";
const CHECKED: &str = "checked";
/// The version of the program being run, set by its `main` (this crate's
/// own is the fallback: the packages rewrite only the program's).
static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
/// Say which version this program is.
pub fn set_program_version(version: &'static str) {
let _ = PROGRAM_VERSION.set(version);
}
/// This program's version.
pub fn program_version() -> &'static str {
PROGRAM_VERSION
.get()
.copied()
.unwrap_or(env!("CARGO_PKG_VERSION"))
}
pub use crate::{program_version, set_program_version};
const MAX_MANIFEST: usize = 1 << 20;
const MAX_PROGRAM: u64 = 1 << 30;
@@ -151,6 +136,17 @@ pub fn install_kind(exe: &Path, appimage: Option<&Path>) -> Install {
if let Some(image) = appimage.filter(|p| p.is_file()) {
return Install::SelfUpdating(image.to_path_buf());
}
// A macOS app is signed whole: one file replaced inside it breaks the
// signature, so it is only ever replaced whole, by the person (the
// newer .dmg), never by this program (WB-pkg-3).
if exe
.ancestors()
.skip(1)
.take(3)
.any(|dir| dir.extension().is_some_and(|e| e == "app") && dir.join("Contents").is_dir())
{
return Install::PackageManaged("app".to_string());
}
if let Some(prefix) = exe.parent().and_then(Path::parent)
&& let Ok(text) = std::fs::read_to_string(prefix.join("share/wanderbooks/install-method"))
{
@@ -168,25 +164,20 @@ pub fn this_install() -> Result<Install, String> {
}
fn refuse_package_managed(manager: &str, what: &str) -> Failure {
if manager == "app" {
return format!(
"this is the macOS app, which is replaced whole and never one file at a time: get the newer Wanderbooks at {} and drag it over this one",
crate::newer::DOWNLOAD_PAGE
)
.into();
}
format!(
"this install is managed by {manager}, which also {what} it: use the package manager (our apt and dnf repositories keep every release, and the AUR keeps old PKGBUILDs)"
)
.into()
}
/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version
/// of ours.
pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
let mut parts = text.split('.');
let mut next = || -> Option<u64> {
let p = parts.next()?;
(!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
.then(|| p.parse().ok())
.flatten()
};
let v = (next()?, next()?, next()?);
parts.next().is_none().then_some(v)
}
pub use crate::newer::parse_version;
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
@@ -981,6 +972,31 @@ mod tests {
);
}
/// WB-pkg-3: a macOS app is signed whole, so this program never
/// replaces a file inside one; the person replaces the whole app.
#[test]
fn a_macos_app_is_never_updated_in_place() {
let dir = tempfile::tempdir().unwrap();
let macos = dir.path().join("Wanderbooks.app/Contents/MacOS");
std::fs::create_dir_all(&macos).unwrap();
let exe = macos.join("wanderbooks");
std::fs::write(&exe, b"x").unwrap();
assert_eq!(
install_kind(&exe, None),
Install::PackageManaged("app".into())
);
let said = refuse_package_managed("app", "updates").to_string();
assert!(said.contains("replaced whole"), "{said}");
assert!(said.contains(crate::newer::DOWNLOAD_PAGE), "{said}");
// A folder that only happens to be called .app, with no bundle in
// it, is not one.
let plain = dir.path().join("tools.app/bin");
std::fs::create_dir_all(&plain).unwrap();
let exe = plain.join("wanderbooks");
std::fs::write(&exe, b"x").unwrap();
assert_eq!(install_kind(&exe, None), Install::SelfUpdating(exe));
}
#[test]
fn a_public_key_is_read_in_every_form_minisign_and_the_packager_write_it() {
let bare = "RWQdrs7W5/jf6drdD0G/ymxFmRWYAIOyggYlubz4NQzdQm5e/Fj0nrb0";
+94 -2
View File
@@ -156,12 +156,48 @@ pub const TERM_GRACE: Duration = Duration::from_secs(5);
/// younger one is left, and the next backup tries again.
pub const ARCHIVE_STALE: Duration = Duration::from_secs(600);
/// How to get git on this system, in plain words (P15 C1, WB-pkg-4). The
/// program does not carry a git of its own: git is a separate program under
/// the GPL, and shipping one is the owner's decision (`docs/install.md`).
/// Until a person installs it, backups are off and the books work as ever.
pub fn how_to_get_git() -> &'static str {
if cfg!(windows) {
"Install Git for Windows from https://git-scm.com/download/win (or, in a terminal, run: winget install --id Git.Git -e), then try again."
} else if cfg!(target_os = "macos") {
"Open Terminal and run: xcode-select --install (a window asks to install Apple's command line tools, which include git; or run: brew install git), then try again."
} else {
"Install git with your system's package manager (for example: sudo apt install git, or sudo dnf install git, or sudo pacman -S git), then try again."
}
}
/// Where Apple's developer tools keep a real git on a Mac: the command
/// line tools' folder and Xcode's.
const MAC_DEVELOPER_DIRS: [&str; 2] = [
"/Library/Developer/CommandLineTools",
"/Applications/Xcode.app/Contents/Developer",
];
/// Whether `exe` is the stub macOS ships at `/usr/bin/git`: with no
/// developer tools installed (none of `developer_dirs` holds a
/// `usr/bin/git`) it is not git but a program that opens Apple's installer
/// dialog and fails, so it is not a git to run (a backup would otherwise
/// pop that dialog and report a failure with a stranger's words).
fn macos_git_stub(exe: &Path, developer_dirs: &[&Path]) -> bool {
exe == Path::new("/usr/bin/git")
&& !developer_dirs
.iter()
.any(|dir| dir.join("usr/bin/git").is_file())
}
/// Why a backup couldn't be made, pushed or trusted. Never names a path of
/// the data root (INVARIANT 4).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum BackupError {
/// git isn't installed.
#[error("git isn't installed: backups need it (install git, then try again)")]
#[error(
"git isn't installed, so backups are off until it is. {}",
how_to_get_git()
)]
NoGit,
/// A git command failed; what it said, in whole lines (paths in it are
/// the caller's to hide, INVARIANT 4).
@@ -247,6 +283,17 @@ impl std::fmt::Debug for Watch {
}
}
/// Git for Windows' per-user install (no administrator needed): under the
/// account's local application data.
fn per_user_git_dirs() -> Vec<PathBuf> {
if cfg!(windows)
&& let Some(local) = std::env::var_os("LOCALAPPDATA")
{
return vec![Path::new(&local).join(r"Programs\Git\cmd")];
}
Vec::new()
}
/// The git program, found once.
#[derive(Debug, Clone)]
pub struct Git {
@@ -285,9 +332,14 @@ impl Git {
.collect::<Vec<_>>()
.iter(),
)
.chain(per_user_git_dirs().iter())
.filter(|d| d.is_absolute())
.map(|d| d.join(if cfg!(windows) { "git.exe" } else { "git" }))
.find(|p| p.is_file())
.find(|p| {
p.is_file()
&& !(cfg!(target_os = "macos")
&& macos_git_stub(p, &MAC_DEVELOPER_DIRS.map(Path::new)))
})
.map(|exe| Git {
exe,
quiet: GIT_TIMEOUT,
@@ -1844,6 +1896,46 @@ mod tests {
Money::new(s.parse().unwrap(), Currency::USD)
}
/// WB-pkg-4: with no git a backup says how to get one, in words for
/// this system, and names no path of the data root.
#[test]
fn a_missing_git_says_how_to_get_it() {
let said = BackupError::NoGit.to_string();
assert!(said.contains("git isn't installed"), "{said}");
assert!(said.contains("backups are off until it is"), "{said}");
assert!(said.ends_with(how_to_get_git()), "{said}");
let how = how_to_get_git();
if cfg!(windows) {
assert!(
how.contains("git-scm.com") && how.contains("winget"),
"{how}"
);
} else if cfg!(target_os = "macos") {
assert!(how.contains("xcode-select --install"), "{how}");
} else {
assert!(how.contains("package manager"), "{how}");
}
assert!(how.ends_with("try again."), "{how}");
}
/// macOS's `/usr/bin/git` is a stub until the developer tools are
/// installed: it is no git, and nothing else is taken for one.
#[test]
fn the_mac_stub_is_not_a_git_until_the_developer_tools_are_there() {
let dir = tempfile::tempdir().unwrap();
let tools = dir.path().join("CommandLineTools");
let stub = Path::new("/usr/bin/git");
assert!(macos_git_stub(stub, &[tools.as_path()]), "no tools yet");
std::fs::create_dir_all(tools.join("usr/bin")).unwrap();
std::fs::write(tools.join("usr/bin/git"), b"").unwrap();
assert!(!macos_git_stub(stub, &[tools.as_path()]), "tools installed");
// Any other git is never the stub.
assert!(!macos_git_stub(
Path::new("/opt/homebrew/bin/git"),
&[dir.path()]
));
}
/// A book with a few entries and a stored file.
fn book(dir: &Path) -> Store {
let mut s = Store::create(dir, Currency::USD).unwrap();
+14 -6
View File
@@ -357,12 +357,20 @@ pub fn platform_data_dir(home: &Path) -> PathBuf {
{
return local;
}
if cfg!(target_os = "macos") {
home.join("Library").join("Application Support")
} else if cfg!(windows) {
home.join("AppData").join("Local")
} else {
home.join(".local").join("share")
data_dir_for(std::env::consts::OS, home)
}
/// The data folder under `home` on the system called `os` (a
/// `std::env::consts::OS` name), as each system's conventions put an
/// installed app's own data (P15 C1, WB-pkg-8): `Library/Application
/// Support` on macOS, `AppData\Local` (not the roaming folder: the books
/// are big, hold locks and belong to this machine) on Windows, the XDG
/// default `.local/share` anywhere else. An uninstall never touches it.
pub fn data_dir_for(os: &str, home: &Path) -> PathBuf {
match os {
"macos" => home.join("Library").join("Application Support"),
"windows" => home.join("AppData").join("Local"),
_ => home.join(".local").join("share"),
}
}
@@ -0,0 +1,84 @@
//! Where an installed app's books live on each system (plan P15 unit C1,
//! WB-pkg-8).
//!
//! ```text
//! GOAL: the books, keys and settings sit where each system keeps an app's
//! own data, apart from the program, so installing a newer program
//! over the old one, or uninstalling it, leaves them as they are.
//! SOURCE: WB-pkg-8; each system's convention for per-user application data
//! (Apple's File System Programming Guide: Library/Application
//! Support; Microsoft's known folders: LocalAppData; the XDG base
//! directory specification: $XDG_DATA_HOME, default ~/.local/share).
//! INVARIANTS:
//! 1. macOS: <home>/Library/Application Support/wanderbooks.
//! 2. Windows: <home>\AppData\Local\wanderbooks (LocalAppData, the local
//! folder, never the roaming one).
//! 3. Anywhere else: <home>/.local/share/wanderbooks, where books have
//! always lived on Linux.
//! 4. No system's data folder is inside the folder its program installs
//! to (the install folders are in docs/install.md and the packaging
//! scripts), so removing the program cannot remove the books.
//! SCENARIOS:
//! 1. The three systems' folders, from one home.
//! ```
use ledger_store::root::{ROOT_NAME, data_dir_for, default_root};
use std::path::Path;
#[test]
fn each_system_keeps_its_data_where_it_keeps_an_apps_data() {
let home = Path::new("/home/someone");
assert_eq!(
data_dir_for("macos", home),
home.join("Library/Application Support")
);
assert_eq!(
data_dir_for("windows", home),
home.join("AppData").join("Local")
);
for other in ["linux", "freebsd", "openbsd"] {
assert_eq!(
data_dir_for(other, home),
home.join(".local/share"),
"{other}"
);
}
assert_eq!(ROOT_NAME, "wanderbooks");
}
#[test]
fn this_systems_default_root_is_its_data_folder_and_the_name() {
let home = Path::new("/home/someone");
assert_eq!(
default_root(home),
data_dir_for(std::env::consts::OS, home).join(ROOT_NAME)
);
}
/// The program's install folders (the Windows installer's, the macOS
/// bundle's, the Linux packages') are never above or below a data folder.
#[test]
fn no_data_folder_is_inside_an_install_folder() {
let home = Path::new("/home/someone");
let installs = [
// Windows: the installer's InstallDir (deploy/packaging/windows).
home.join("AppData/Local/Programs/Wanderbooks"),
// macOS: the app (drag-to-Applications), and the per-user folder.
Path::new("/Applications/Wanderbooks.app").to_path_buf(),
home.join("Applications/Wanderbooks.app"),
// Linux packages.
Path::new("/usr/bin").to_path_buf(),
Path::new("/usr/share/wanderbooks").to_path_buf(),
];
for os in ["macos", "windows", "linux"] {
let data = data_dir_for(os, home).join(ROOT_NAME);
for install in &installs {
assert!(
!data.starts_with(install) && !install.starts_with(&data),
"{os}: {} and {} overlap",
data.display(),
install.display()
);
}
}
}