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

+55
View File
@@ -0,0 +1,55 @@
# Add a PUBLISHED release's .deb and .rpm to the apt and dnf repositories on
# the gh-pages branch (plan P11a step 3, D-26; GitHub Pages serves them). By
# hand only, after the release was tried and published: the release workflow
# never touches these repositories (plan P15 unit C1). Unsigned until the
# owner's release key signs the indexes (Q-4).
name: publish-repos
on:
workflow_dispatch:
inputs:
tag:
description: "The published release's tag, e.g. v0.1.0"
required: true
permissions:
contents: write
jobs:
repos:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Repository tools
run: sudo apt-get update && sudo apt-get install -y apt-utils createrepo-c
- name: The release's .deb and .rpm (it must be published, not a draft)
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
run: |
draft=$(gh release view "$TAG" --json isDraft --jq .isDraft)
[ "$draft" = false ] || { echo "$TAG is a draft: publish the release first" >&2; exit 1; }
mkdir assets
gh release download "$TAG" --dir assets --pattern '*.deb' --pattern '*.rpm'
ls -l assets
- name: Add them to the apt and dnf repositories (gh-pages)
env:
TAG: ${{ inputs.tag }}
run: |
git fetch origin gh-pages || true
if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then
git worktree add repo origin/gh-pages
else
git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true
fi
mkdir -p repo/apt/pool repo/dnf
cp assets/*.deb repo/apt/pool/
cp assets/*.rpm repo/dnf/
deploy/packaging/repo-indexes.sh apt repo/apt
deploy/packaging/repo-indexes.sh dnf repo/dnf
cd repo || exit 1
git config user.name "wanderbooks release"
git config user.email "release@wanderbooks.ai"
git add -A
git commit -m "wanderbooks $TAG"
git push origin HEAD:gh-pages
+290 -85
View File
@@ -1,29 +1,67 @@
# Releases (plan P11a, D-24, D-26): on a version tag, build the Linux
# packages on the oldest system they claim (ubuntu-24.04, glibc 2.39; a
# program linked on a newer one does not start on an older one), attach
# them to the GitHub release, and add them to the apt and dnf repositories
# on the gh-pages branch (GitHub Pages serves them). Unsigned: step 5 of
# the unit (the release key, Q-4) signs the manifest and the indexes. The
# macOS job builds the .dmg UNSIGNED (no Developer ID, no notarization:
# step 5); the Windows job is unit P11c. The release holds no key today.
# To see the artifacts without a tag: Actions > release > Run workflow,
# pick the branch; each job uploads its files as a run artifact.
# The release (plan P15 unit C1; WB-pkg-7): packages for Linux, Windows and
# macOS, built from one version, tested on their own system, and attached with
# their SHA-256 sums to a DRAFT GitHub release. Nothing here publishes: the
# release stays a draft until the owner has tried the packages and presses
# Publish, and nothing here touches the apt or dnf repositories (that is
# publish-repos.yml, by hand, from a published release).
#
# Runs on a version tag (v0.1.0: the tag must equal the program's version) or
# by hand (Actions > release > Run workflow, on a branch: a draft for
# v<version> is made, nothing is tagged). It never runs on an ordinary push:
# the tests below take hours (the same ones the portable workflows run).
#
# Unsigned by default. With the owner's secrets it signs; without them each
# signing step says so in the run's notices and the package is unsigned:
# Windows: WINDOWS_CERTIFICATE_PFX_BASE64, WINDOWS_CERTIFICATE_PASSWORD
# macOS: APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD,
# APPLE_SIGNING_IDENTITY, and to notarize APPLE_ID, APPLE_TEAM_ID,
# APPLE_APP_SPECIFIC_PASSWORD
# (docs/install.md, "Signing", says how each is made.)
name: release
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
run_tests:
description: "Run each system's whole test suite before packaging (hours). Turn off only when this commit's tests already passed."
type: boolean
default: true
permissions:
contents: write
contents: read
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
env:
# Same disk discipline as check.yml: no incremental caches.
CARGO_INCREMENTAL: "0"
jobs:
version:
name: The version (one source)
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.version.outputs.version }}
steps:
- uses: actions/checkout@v4
- name: Read the version from crates/ledger-cli/Cargo.toml and check the tag against it
id: version
run: |
own=$(sh deploy/packaging/version.sh)
if [ "${GITHUB_REF_TYPE}" = tag ] && [ "${GITHUB_REF_NAME#v}" != "$own" ]; then
echo "the tag $GITHUB_REF_NAME is not the program's version $own (crates/ledger-cli/Cargo.toml)" >&2
exit 1
fi
echo "version=$own" >> "$GITHUB_OUTPUT"
linux:
name: Linux (AppImage, .deb, .rpm, pacman)
needs: version
runs-on: ubuntu-24.04
# Same disk discipline as check.yml: no incremental caches.
env:
CARGO_INCREMENTAL: "0"
steps:
- uses: actions/checkout@v4
- name: Room for the build (the image ships toolchains we never use)
@@ -34,90 +72,257 @@ jobs:
- uses: jdx/mise-action@v2
with:
# Only what packaging needs, not the proof and fuzz tools.
install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm"
install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm cargo:cargo-about"
- name: GUI build dependencies
run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev apt-utils createrepo-c
- name: The tag is the program's version
id: version
run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev
- name: THIRD-PARTY-NOTICES.txt is up to date with what the program links
run: scripts/notices.sh --check
- name: Tests (the workspace's whole suite on Linux)
if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }}
run: cargo test --workspace --no-fail-fast
- name: Build the release program and the four packages (on the oldest system they claim, glibc 2.39)
run: just package-linux ${{ needs.version.outputs.version }}
- name: Check each package holds the program, the entry, the icon and the licences
run: |
own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1)
tag="${GITHUB_REF_NAME#v}"
if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then
echo "tag $GITHUB_REF_NAME is not version $own" >&2
exit 1
fi
echo "version=$own" >> "$GITHUB_OUTPUT"
- name: Build the packages
run: just package-linux ${{ steps.version.outputs.version }}
- name: Attach them to the release
if: github.ref_type == 'tag'
env:
GH_TOKEN: ${{ github.token }}
run: |
v=${{ steps.version.outputs.version }}
gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v"
gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.AppImage target/packages/$v/*.deb target/packages/$v/*.rpm target/packages/$v/*.tar.gz
- name: Add them to the apt and dnf repositories (gh-pages)
if: github.ref_type == 'tag'
run: |
v=${{ steps.version.outputs.version }}
git fetch origin gh-pages || true
if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then
git worktree add repo origin/gh-pages
v=${{ needs.version.outputs.version }}
cd target/packages/$v || exit 1
ls -l
for need in *.AppImage *.deb *.rpm *.tar.gz; do
test -s "$need" || { echo "no $need was built" >&2; exit 1; }
done
mkdir deb && (cd deb && ar x ../*.deb && tar -xf data.tar.* && ls -R . | head -50)
for f in usr/bin/wanderbooks usr/share/applications/wanderbooks.desktop \
usr/share/icons/hicolor/512x512/apps/wanderbooks.png \
usr/share/doc/wanderbooks/LICENSE-MIT usr/share/doc/wanderbooks/LICENSE-APACHE \
usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do
test -e "deb/$f" || { echo "the .deb lacks $f" >&2; exit 1; }
done
rpm -qlp *.rpm > rpm.list 2>/dev/null || true
if [ -s rpm.list ]; then
for f in /usr/bin/wanderbooks /usr/share/applications/wanderbooks.desktop \
/usr/share/doc/wanderbooks/LICENSE-MIT /usr/share/doc/wanderbooks/LICENSE-APACHE \
/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do
grep -qx "$f" rpm.list || { echo "the .rpm lacks $f" >&2; exit 1; }
done
else
git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true
echo "::notice title=rpm not listed::rpm is not on this runner; the .rpm's files were not listed"
fi
mkdir -p repo/apt/pool repo/dnf
cp target/packages/$v/*.deb repo/apt/pool/
cp target/packages/$v/*.rpm repo/dnf/
deploy/packaging/repo-indexes.sh apt repo/apt
deploy/packaging/repo-indexes.sh dnf repo/dnf
cd repo
git config user.name "wanderbooks release"
git config user.email "release@wanderbooks.ai"
git add -A
git commit -m "wanderbooks $v"
git push origin HEAD:gh-pages
- name: Keep them with the run (a dispatch has no release)
rm -rf deb rpm.list
- name: Keep the packages with the run
uses: actions/upload-artifact@v4
with:
name: linux-packages
path: target/packages/${{ steps.version.outputs.version }}/
path: |
target/packages/${{ needs.version.outputs.version }}/*.AppImage
target/packages/${{ needs.version.outputs.version }}/*.deb
target/packages/${{ needs.version.outputs.version }}/*.rpm
target/packages/${{ needs.version.outputs.version }}/*.tar.gz
target/packages/${{ needs.version.outputs.version }}/PKGBUILD
if-no-files-found: error
macos:
# UNSIGNED: a .dmg that Gatekeeper refuses until step 5 signs and
# notarizes it. Apple silicon (macos-latest); an Intel build is not
# made yet.
runs-on: macos-latest
windows:
name: Windows (per-user installer)
needs: version
runs-on: windows-latest
defaults:
run:
shell: bash
env:
CARGO_INCREMENTAL: "0"
WINDOWS_CERTIFICATE_PFX_BASE64: ${{ secrets.WINDOWS_CERTIFICATE_PFX_BASE64 }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
CARGO_PROFILE_DEV_DEBUG: line-tables-only
CARGO_PROFILE_TEST_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
with:
install_args: "rust just cargo:cargo-packager"
- name: The tag is the program's version
id: version
- name: Rust (the version mise.toml pins)
run: rustup toolchain install 1.99 --profile minimal && rustup default 1.99
- name: Tests (the same ones the portable-windows workflow runs)
if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }}
run: |
own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1)
tag="${GITHUB_REF_NAME#v}"
if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then
echo "tag $GITHUB_REF_NAME is not version $own" >&2
exit 1
cargo build --workspace --all-targets
cargo test --workspace --no-fail-fast
- name: Build the release program
run: cargo build --release -p ledger-cli
- name: Check the program is a Windows GUI program (no console window) and still prints in a terminal
shell: pwsh
run: |
$exe = "target\release\wanderbooks.exe"
$bytes = [IO.File]::ReadAllBytes($exe)
$pe = [BitConverter]::ToInt32($bytes, 0x3C)
$subsystem = [BitConverter]::ToUInt16($bytes, $pe + 24 + 68)
if ($subsystem -ne 2) { throw "wanderbooks.exe has Windows subsystem $subsystem, not 2 (GUI): the app would open a console window" }
Write-Host "subsystem $subsystem (GUI)"
$said = (& $exe --help 2>&1 | Out-String)
if ($said -notmatch "usage") { throw "wanderbooks.exe --help printed no usage through a pipe: $said" }
- name: Sign the program (only when the certificate secrets exist; says so when not)
shell: pwsh
run: deploy\packaging\windows\sign-windows.ps1 target\release\wanderbooks.exe
- name: NSIS (the installer's compiler; free)
shell: pwsh
run: |
if (-not (Get-Command makensis -ErrorAction SilentlyContinue) -and -not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) {
choco install nsis -y --no-progress
}
if (-not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe") -and -not (Get-Command makensis -ErrorAction SilentlyContinue)) { throw "NSIS did not install" }
- name: Build the installer
run: deploy/packaging/windows/build-windows.sh ${{ needs.version.outputs.version }}
- name: Sign the installer (only when the certificate secrets exist; says so when not)
shell: pwsh
run: deploy\packaging\windows\sign-windows.ps1 (Get-ChildItem target\packages\${{ needs.version.outputs.version }}\*-setup.exe)
- name: Install it silently, check what it put where, then uninstall it and check the books are still there
shell: pwsh
run: |
$v = "${{ needs.version.outputs.version }}"
$setup = (Get-ChildItem "target\packages\$v\Wanderbooks-$v-windows-x64-setup.exe").FullName
$dir = Join-Path $env:LOCALAPPDATA "Programs\Wanderbooks"
$data = Join-Path $env:LOCALAPPDATA "wanderbooks"
New-Item -ItemType Directory -Force $data | Out-Null
Set-Content (Join-Path $data "sentinel.txt") "the person's books"
$p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "the installer exited $($p.ExitCode)" }
foreach ($f in "wanderbooks.exe", "wanderbooks.ico", "LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt", "Uninstall Wanderbooks.exe") {
if (-not (Test-Path (Join-Path $dir $f))) { throw "the installer did not put $f in $dir" }
}
$lnk = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Wanderbooks.lnk"
if (-not (Test-Path $lnk)) { throw "no Start Menu entry at $lnk" }
$shell = New-Object -ComObject WScript.Shell
$target = $shell.CreateShortcut($lnk).TargetPath
if ($target -ne (Join-Path $dir "wanderbooks.exe")) { throw "the Start Menu entry points at $target" }
$key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks"
$entry = Get-ItemProperty $key
if ($entry.DisplayName -ne "Wanderbooks" -or $entry.DisplayVersion -ne $v) { throw "the Settings > Apps entry is wrong: $($entry | Out-String)" }
# Installing a newer one over it keeps the same path (the bridge's).
$p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "installing over itself exited $($p.ExitCode)" }
if (-not (Test-Path (Join-Path $dir "wanderbooks.exe"))) { throw "the program is gone after installing over it" }
# Uninstall (in place, so this waits for it).
$p = Start-Process (Join-Path $dir "Uninstall Wanderbooks.exe") -ArgumentList "/S", "_?=$dir" -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "the uninstaller exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir "wanderbooks.exe")) { throw "the uninstaller left the program" }
if (Test-Path $lnk) { throw "the uninstaller left the Start Menu entry" }
if (Test-Path $key) { throw "the uninstaller left its Settings > Apps entry" }
if (-not (Test-Path (Join-Path $data "sentinel.txt"))) { throw "THE UNINSTALLER REMOVED THE BOOKS' FOLDER" }
Write-Host "installed, installed over itself, uninstalled; the books' folder was left alone"
- name: Keep the installer with the run
uses: actions/upload-artifact@v4
with:
name: windows-installer
path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-windows-x64-setup.exe
if-no-files-found: error
macos:
name: macOS (universal .app in a .dmg)
needs: version
runs-on: macos-latest
env:
# A Unix socket path holds 104 bytes on macOS, and the runner's default
# temp folder is longer than the tests' homes can afford (the same
# reason as in portable-macos.yml).
TMPDIR: /tmp
CARGO_PROFILE_DEV_DEBUG: line-tables-only
CARGO_PROFILE_TEST_DEBUG: line-tables-only
APPLE_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_CERTIFICATE_P12_BASE64 }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
steps:
- uses: actions/checkout@v4
- name: Rust (the version mise.toml pins), for both Macs
run: |
rustup toolchain install 1.99 --profile minimal && rustup default 1.99
rustup target add aarch64-apple-darwin x86_64-apple-darwin
- name: Tests (the same ones the portable-macos workflow runs)
if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }}
run: |
cargo build --workspace --all-targets
cargo test --workspace --no-fail-fast
- name: Build the release program for Apple silicon
run: cargo build --release -p ledger-cli --target aarch64-apple-darwin
- name: Build the release program for Intel
run: cargo build --release -p ledger-cli --target x86_64-apple-darwin
- name: Put the Developer ID certificate in a temporary keychain (only when the secrets exist)
run: |
if [ -n "$APPLE_CERTIFICATE_P12_BASE64" ] && [ -n "$APPLE_CERTIFICATE_PASSWORD" ] && [ -n "$APPLE_SIGNING_IDENTITY" ]; then
deploy/packaging/macos/import-certificate.sh
else
echo "::notice title=macOS signing skipped::no APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD and APPLE_SIGNING_IDENTITY secrets: the app is signed ad hoc and macOS Gatekeeper will refuse a download of it"
fi
echo "version=$own" >> "$GITHUB_OUTPUT"
- name: Build the unsigned .dmg
run: just package-macos ${{ steps.version.outputs.version }}
- name: Attach it to the release
if: github.ref_type == 'tag'
- name: Build, sign, notarize (each only when its secrets exist) and staple the .dmg
env:
WB_SIGN_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
WB_NOTARY_APPLE_ID: ${{ secrets.APPLE_ID }}
WB_NOTARY_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WB_NOTARY_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
run: deploy/packaging/macos/build-macos.sh ${{ needs.version.outputs.version }}
- name: Check the .dmg holds a universal, hardened, well-formed app (opened, not run)
run: |
v=${{ needs.version.outputs.version }}
dmg=$(ls target/packages/$v/Wanderbooks-$v-macos-universal.dmg)
mnt=$(mktemp -d /tmp/wbdmg.XXXXXX)
hdiutil attach "$dmg" -mountpoint "$mnt" -nobrowse -readonly
trap 'hdiutil detach "$mnt" -quiet || true' EXIT
app="$mnt/Wanderbooks.app"
test -d "$app" || { echo "no Wanderbooks.app in the .dmg" >&2; exit 1; }
test -L "$mnt/Applications" || { echo "no Applications shortcut in the .dmg" >&2; exit 1; }
lipo -archs "$app/Contents/MacOS/wanderbooks"
lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q arm64
lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q x86_64
plutil -lint "$app/Contents/Info.plist"
test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")" = ai.wanderbooks.app
test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")" = "$v"
test -f "$app/Contents/Resources/wanderbooks.icns"
for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt; do test -f "$app/Contents/Resources/$f"; done
codesign --verify --deep --strict --verbose=2 "$app"
codesign -dv --verbose=4 "$app" 2>&1 | grep -E "flags=|Authority|Signature|TeamIdentifier" || true
- name: Keep the .dmg with the run
uses: actions/upload-artifact@v4
with:
name: macos-dmg
path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-macos-universal.dmg
if-no-files-found: error
draft-release:
name: A draft release with the packages and their SHA-256 sums
needs: [version, linux, windows, macos]
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- name: Fetch the three platforms' packages
uses: actions/download-artifact@v4
with:
path: dist-parts
- name: Gather the files, the licences, the update note and the SHA-256 sums
run: |
v=${{ needs.version.outputs.version }}
mkdir dist
find dist-parts -type f -exec cp {} dist/ \;
cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt dist/
# The note the app's daily look reads (crates/ledger-host/src/newer.rs):
# a version number and nothing else it uses.
printf '{"version":"%s"}\n' "$v" > dist/latest.json
(cd dist && sha256sum -- * > SHA256SUMS.txt && cat SHA256SUMS.txt)
ls -l dist
- name: Make or refresh the DRAFT release (a published release is never touched)
env:
GH_TOKEN: ${{ github.token }}
run: |
v=${{ steps.version.outputs.version }}
gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v"
gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.dmg
- name: Keep it with the run (a dispatch has no release)
uses: actions/upload-artifact@v4
with:
name: macos-dmg-unsigned
path: target/packages/${{ steps.version.outputs.version }}/*.dmg
v=${{ needs.version.outputs.version }}
tag="v$v"
if gh release view "$tag" >/dev/null 2>&1; then
draft=$(gh release view "$tag" --json isDraft --jq .isDraft)
if [ "$draft" != true ]; then
echo "$tag is already published: this workflow never changes a published release" >&2
exit 1
fi
gh release upload "$tag" --clobber dist/*
else
gh release create "$tag" --draft --target "$GITHUB_SHA" \
--title "Wanderbooks $v" \
--notes "Wanderbooks $v. Unsigned builds warn on first run: see docs/install.md. Check the SHA-256 sums in SHA256SUMS.txt." \
dist/*
fi
echo "A draft release $tag holds the packages. Try them, then publish it by hand."
Generated
+2
View File
@@ -4039,6 +4039,7 @@ dependencies = [
"time",
"tokio",
"tokio-rustls",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
@@ -4132,6 +4133,7 @@ dependencies = [
"tokio",
"tokio-util",
"zeroize",
"zip",
]
[[package]]
+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()
);
}
}
}
+3
View File
@@ -6,6 +6,9 @@ account can read, and agents reach them through the server with a token.
Locally the books are `same_user (advisory)` — hidden from the agent, not
locked against it; here they are behind an account and a machine boundary.
This is the recipe for a machine with no window. To install the app on a
computer you sit at (Windows, macOS, Linux), see `docs/install.md`.
Nothing here needs the owner's books: every step works on a copy.
The pieces:
-12
View File
@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Merged by cargo-packager into the Info.plist it generates for the
.app (P11a step 6): the keys the generated one lacks. -->
<plist version="1.0">
<dict>
<key>LSMultipleInstancesProhibited</key>
<true/>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
</dict>
</plist>
+1 -1
View File
@@ -9,7 +9,7 @@ pkgdesc="Double-entry bookkeeping your agent keeps and you can read"
arch=('x86_64')
url="https://wanderbooks.ai"
license=('MIT' 'Apache-2.0')
depends=('gcc-libs' 'glibc')
depends=('gcc-libs' 'glibc' 'git')
provides=('wanderbooks')
conflicts=('wanderbooks')
options=('!lto' '!strip')
+4
View File
@@ -37,6 +37,7 @@ sed "s/^version = \".*\"/version = \"$version\"/
s#\"target/release\"#\"$PWD/$stage\"#
s#\"deploy/packaging/#\"$PWD/deploy/packaging/#
s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#
s#^\"LICENSE-APACHE\"#\"$PWD/LICENSE-APACHE\"#
s#^\"THIRD-PARTY-NOTICES.txt\"#\"$PWD/THIRD-PARTY-NOTICES.txt\"#" \
deploy/packaging/packager.toml >"$config"
# The AppImage tools are themselves AppImages; run them without FUSE.
@@ -46,6 +47,9 @@ assets='assets = [
{ source = "'$PWD/$stage'/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" },
]'
cargo generate-rpm -p crates/ledger-cli --set-metadata "version=\"$version\"" --set-metadata "$assets" -o "$out/"
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env bash
# The macOS bundle (P11a step 6), UNSIGNED, from the release program
# already built at target/release/wanderbooks (`cargo build --release -p
# ledger-cli`). Run on a Mac from the repository root:
#
# build-macos.sh [VERSION]
#
# Puts Wanderbooks_VERSION_<arch>.dmg into target/packages/VERSION/. It
# is not signed or notarized (step 5): Gatekeeper refuses it on a Mac
# that downloaded it, and the owner opens it with right-click > Open.
# Portable shell: macOS has BSD sed and no GNU mktemp options.
set -euo pipefail
own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1)
version=${1:-$own}
out="target/packages/$version"
program=${WB_PROGRAM:-target/release/wanderbooks}
test -x "$program" || { echo "build the release program first: cargo build --release -p ledger-cli" >&2; exit 1; }
rm -rf "$out"; mkdir -p "$out"
stage="target/packages/.stage-$version"
rm -rf "$stage"; mkdir -p "$stage"
cp "$program" "$stage/wanderbooks"
config="$stage/packager.toml"
# cargo-packager reads paths relative to the config file, which is in the
# stage folder here, so they are made absolute.
sed -e "s/^version = \".*\"/version = \"$version\"/" \
-e "s#^out-dir = .*#out-dir = \"$PWD/$out\"#" \
-e "s#\"target/release\"#\"$PWD/$stage\"#" \
-e "s#\"deploy/packaging/#\"$PWD/deploy/packaging/#" \
-e "s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#" \
deploy/packaging/packager-macos.toml >"$config"
cargo packager --config "$config" --formats dmg --release
rm -rf "$stage"
ls -l "$out"
Binary file not shown.

After

Width:  |  Height:  |  Size: 361 KiB

+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- The Info.plist of Wanderbooks.app (plan P15 unit C1; WB-pkg-1, WB-pkg-6).
build-macos.sh replaces @VERSION@ with the program's version
(deploy/packaging/version.sh) and @BUNDLE_ID@ with the bundle
identifier. -->
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>Wanderbooks</string>
<key>CFBundleDisplayName</key>
<string>Wanderbooks</string>
<key>CFBundleIdentifier</key>
<string>@BUNDLE_ID@</string>
<key>CFBundleExecutable</key>
<string>wanderbooks</string>
<key>CFBundleIconFile</key>
<string>wanderbooks</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleShortVersionString</key>
<string>@VERSION@</string>
<key>CFBundleVersion</key>
<string>@VERSION@</string>
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.finance</string>
<key>NSHighResolutionCapable</key>
<true/>
<!-- One Wanderbooks at a time: it holds the books open. -->
<key>LSMultipleInstancesProhibited</key>
<true/>
<!-- The discrete GPU is not woken for a ledger. -->
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>MIT OR Apache-2.0</string>
<!-- macOS asks the person once before an app reads their Documents folder,
and shows this sentence. Wanderbooks makes a folder there for each
company's assistant (Documents/Wanderbooks) and for the Claude
extension; it never reads anything else of theirs there. -->
<key>NSDocumentsFolderUsageDescription</key>
<string>Wanderbooks keeps a small folder in Documents for each company, where an assistant such as Claude Code works, and the extension file for the Claude app.</string>
</dict>
</plist>
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env bash
# The macOS app and its .dmg (plan P15 unit C1; WB-pkg-1). Run on a Mac from
# the repository root (CI: the `macos` job of .github/workflows/release.yml):
#
# build-macos.sh [VERSION]
#
# Puts Wanderbooks-VERSION-macos-universal.dmg into target/packages/VERSION/.
#
# One UNIVERSAL program (Apple silicon and Intel in one file, `lipo`ed from
# the two release builds): one download for everyone. The program is
# WB_PROGRAM if set (any program file), else the lipo of
# target/aarch64-apple-darwin/release/wanderbooks and
# target/x86_64-apple-darwin/release/wanderbooks.
#
# Signing and notarization need the owner's Apple Developer identity and run
# only when it is given, in the environment (the release workflow sets these
# from secrets; nothing here is a secret and nothing prints one):
# WB_SIGN_IDENTITY the signing identity, e.g.
# "Developer ID Application: Name (TEAMID)", already in
# the keychain (import-certificate.sh does that in CI)
# WB_NOTARY_APPLE_ID, WB_NOTARY_TEAM_ID, WB_NOTARY_PASSWORD
# for `xcrun notarytool` (an app-specific password)
# Without WB_SIGN_IDENTITY the app is signed ad hoc ("-"): Apple silicon
# will not start an unsigned program at all, so it runs, but Gatekeeper
# still refuses a download of it (right-click > Open once, docs/install.md).
# Without the notarization variables the .dmg is signed but not notarized.
#
# WB_NO_ICNS=1 skips the icon (no `iconutil` off a Mac): the structure
# tests build the bundle that way on Linux; a release never does.
# WB_BUNDLE_ONLY=1 stops after the .app (the structure tests).
set -euo pipefail
here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
root=$(CDPATH='' cd -- "$here/../../.." && pwd)
cd "$root"
fail() { echo "build-macos: $*" >&2; exit 1; }
notice() { echo "::notice title=$1::$2"; echo "build-macos: $2"; }
own=$(sh deploy/packaging/version.sh)
version=${1:-$own}
case "$version" in
[0-9]*.[0-9]*.[0-9]*) ;;
*) fail "'$version' is not an x.y.z version" ;;
esac
bundle_id=${WB_BUNDLE_ID:-ai.wanderbooks.app}
out="target/packages/$version"
stage="target/packages/.stage-macos-$version"
app="$stage/Wanderbooks.app"
dmg="Wanderbooks-$version-macos-universal.dmg"
for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/512x512.png \
deploy/packaging/macos/Info.plist.in deploy/packaging/macos/entitlements.plist; do
test -f "$f" || fail "$f is missing from the repository"
done
# 1. The program: universal, or the one given.
rm -rf "${stage:?}"
mkdir -p "$stage" "$out"
program=${WB_PROGRAM:-}
if [ -z "$program" ]; then
arm=target/aarch64-apple-darwin/release/wanderbooks
intel=target/x86_64-apple-darwin/release/wanderbooks
test -f "$arm" || fail "$arm is missing: cargo build --release -p ledger-cli --target aarch64-apple-darwin"
test -f "$intel" || fail "$intel is missing: cargo build --release -p ledger-cli --target x86_64-apple-darwin"
lipo -create -output "$stage/wanderbooks-universal" "$arm" "$intel"
archs=$(lipo -archs "$stage/wanderbooks-universal")
case "$archs" in
*arm64*x86_64*|*x86_64*arm64*) ;;
*) fail "the universal program holds '$archs', not both arm64 and x86_64" ;;
esac
program="$stage/wanderbooks-universal"
fi
test -f "$program" || fail "the program is not at $program"
# 2. The bundle. The program's path inside it,
# /Applications/Wanderbooks.app/Contents/MacOS/wanderbooks, is the one an
# assistant is registered with: it does not change when the app is
# replaced by a newer one dragged over it.
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
cp "$program" "$app/Contents/MacOS/wanderbooks"
chmod 755 "$app/Contents/MacOS/wanderbooks"
sed -e "s/@VERSION@/$version/g" -e "s/@BUNDLE_ID@/$bundle_id/g" \
deploy/packaging/macos/Info.plist.in > "$app/Contents/Info.plist"
printf 'APPL????' > "$app/Contents/PkgInfo"
cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt "$app/Contents/Resources/"
if [ "${WB_NO_ICNS:-}" = 1 ]; then
notice "no icon" "WB_NO_ICNS=1: the bundle has no icon (a test build, never a release)"
else
command -v iconutil >/dev/null || fail "iconutil is not here: build the icon on a Mac, or set WB_NO_ICNS=1 for a test bundle"
iconset="$stage/wanderbooks.iconset"
mkdir -p "$iconset"
src=deploy/packaging/icons/512x512.png
for size in 16 32 128 256 512; do
sips -z "$size" "$size" "$src" --out "$iconset/icon_${size}x${size}.png" >/dev/null
done
for size in 16 32 128 256; do
double=$((size * 2))
sips -z "$double" "$double" "$src" --out "$iconset/icon_${size}x${size}@2x.png" >/dev/null
done
iconutil -c icns "$iconset" -o "$app/Contents/Resources/wanderbooks.icns"
fi
if [ "${WB_BUNDLE_ONLY:-}" = 1 ]; then
echo "build-macos: bundle at $app (WB_BUNDLE_ONLY=1)"
exit 0
fi
# 3. Sign: hardened runtime, the entitlements, a secure timestamp.
identity=${WB_SIGN_IDENTITY:-}
if [ -z "$identity" ]; then
notice "macOS signing skipped" "no WB_SIGN_IDENTITY: the app is signed ad hoc, so it runs here, but macOS Gatekeeper will refuse a download of it until it is signed with a Developer ID and notarized"
identity=-
timestamp=--timestamp=none
else
timestamp=--timestamp
fi
codesign --force --options runtime "$timestamp" \
--entitlements deploy/packaging/macos/entitlements.plist \
--sign "$identity" "$app"
codesign --verify --deep --strict --verbose=2 "$app"
# 4. The .dmg: the app and a shortcut to Applications (drag to install).
mkdir -p "$stage/dmg"
cp -R "$app" "$stage/dmg/"
ln -s /Applications "$stage/dmg/Applications"
rm -f "${out:?}/${dmg:?}"
hdiutil create -volname "Wanderbooks" -srcfolder "$stage/dmg" -ov -format UDZO "$out/$dmg"
if [ "$identity" != "-" ]; then
codesign --force --timestamp --sign "$identity" "$out/$dmg"
fi
# 5. Notarize and staple (the Developer ID signature and Apple's ticket).
if [ "$identity" != "-" ] && [ -n "${WB_NOTARY_APPLE_ID:-}" ] && [ -n "${WB_NOTARY_TEAM_ID:-}" ] && [ -n "${WB_NOTARY_PASSWORD:-}" ]; then
xcrun notarytool submit "$out/$dmg" \
--apple-id "$WB_NOTARY_APPLE_ID" --team-id "$WB_NOTARY_TEAM_ID" \
--password "$WB_NOTARY_PASSWORD" --wait
xcrun stapler staple "$out/$dmg"
xcrun stapler validate "$out/$dmg"
spctl --assess --type open --context context:primary-signature --verbose=2 "$out/$dmg"
else
notice "macOS notarization skipped" "no signing identity or no WB_NOTARY_APPLE_ID / WB_NOTARY_TEAM_ID / WB_NOTARY_PASSWORD: the .dmg is not notarized, and macOS will warn on the first open"
fi
rm -rf "${stage:?}"
ls -l "$out"
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- The hardened-runtime entitlements of Wanderbooks.app (plan P15 unit C1).
The app is signed with the hardened runtime (codesign --options
runtime), which Apple's notarization requires. It is NOT sandboxed
(the App Sandbox would forbid what the product is: it starts a copy of
itself as the books server, runs the system's git for backups, and
reads and writes the person's data folder and the folders they pick
for backups). Outside the sandbox, none of that needs an entitlement:
* starting itself as a child process and git as another: none;
* outgoing network connections (the relay, the update look, a git
remote): none (com.apple.security.network.client is a SANDBOX
entitlement);
* reading and writing its data folder, Application Support/wanderbooks:
none (the Documents folder is a privacy prompt, answered by
NSDocumentsFolderUsageDescription in Info.plist, not an entitlement);
* the window's graphics (Metal through wgpu): none;
* no JIT, no unsigned executable memory, no DYLD variables, no
library validation exception: the program loads only system
frameworks and its own code.
So the set below is empty on purpose. If the first notarized build
fails to start, the log names the entitlement it needs; add exactly
that one here, with the reason, and not a broader exception. -->
<plist version="1.0">
<dict/>
</plist>
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Put the owner's Developer ID certificate into a temporary keychain on a CI
# macOS runner, so `codesign` can use it (plan P15 unit C1). Run by the
# release workflow only when the secrets exist. Takes the certificate (a .p12,
# base64) and its password from the environment, never the command line:
# APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD
# Prints no secret. The keychain lives in RUNNER_TEMP and goes with the
# runner.
set -euo pipefail
: "${APPLE_CERTIFICATE_P12_BASE64:?the certificate secret is empty}"
: "${APPLE_CERTIFICATE_PASSWORD:?the certificate password secret is empty}"
: "${RUNNER_TEMP:?not on a GitHub runner}"
keychain="$RUNNER_TEMP/wanderbooks-signing.keychain-db"
password=$(uuidgen)
p12="$RUNNER_TEMP/wanderbooks-signing.p12"
printf '%s' "$APPLE_CERTIFICATE_P12_BASE64" | base64 --decode > "$p12"
security create-keychain -p "$password" "$keychain"
security set-keychain-settings -lut 21600 "$keychain"
security unlock-keychain -p "$password" "$keychain"
security import "$p12" -k "$keychain" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain" >/dev/null
security list-keychains -d user -s "$keychain" login.keychain
rm -f "$p12"
security find-identity -v -p codesigning "$keychain"
-36
View File
@@ -1,36 +0,0 @@
# cargo-packager's description of the macOS bundle (P11a step 6; D-24,
# D-25): the .app and its .dmg, UNSIGNED. `deploy/packaging/build-macos.sh`
# runs it on a Mac (CI: the `macos` job of .github/workflows/release.yml).
# Developer ID signing and notarization are step 5 (the owner's Apple
# certificate, Q-4): they add `signing-identity` under [macos] and the
# certificate and notarization credentials as CI secrets.
# Paths are relative to this file's copy that build-macos.sh writes.
name = "wanderbooks"
product-name = "Wanderbooks"
version = "0.1.0"
identifier = "ai.wanderbooks.app"
description = "Double-entry bookkeeping your agent keeps and you can read."
homepage = "https://wanderbooks.ai"
authors = ["Stephen Waits"]
license-file = "LICENSE-MIT"
category = "Finance"
binaries-dir = "target/release"
out-dir = "target/packages"
# A png is made into the .icns (cargo-packager does it); the 512 px
# placeholder is the owner's to replace.
icons = ["deploy/packaging/icons/512x512.png"]
formats = ["dmg"]
binaries = [{ path = "wanderbooks", main = true }]
[macos]
# The oldest macOS Rust's tier-1 aarch64-apple-darwin and x86-64 targets
# run on; eframe's wgpu/Metal path needs 10.15 at least.
minimum-system-version = "11.0"
# Keys merged into the generated Info.plist: one viewer at a time, and the
# discrete GPU is not woken for a ledger.
info-plist-path = "deploy/packaging/Info.plist"
[dmg]
window-size = { width = 540, height = 380 }
app-position = { x = 140, y = 180 }
application-folder-position = { x = 400, y = 180 }
+13 -2
View File
@@ -24,17 +24,28 @@ section = "utils"
# A deb marks itself package-managed: `wanderbooks update` refuses on it
# and says to use apt (plan 3.9).
desktop-template = "deploy/packaging/wanderbooks.desktop"
depends = ["libc6", "libgcc-s1"]
# git: the backups run the system's git (WB-pkg-4); the package manager
# fetches it, so a Linux person never sees the missing-git words.
depends = ["libc6", "libgcc-s1", "git"]
[deb.files]
"deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method"
# The notices the third-party licences ask to travel with the program
# (`just notices`); `wanderbooks licenses` prints the same text.
"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt"
"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT"
"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE"
[appimage.files]
"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt"
"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT"
"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE"
[pacman]
depends = ["gcc-libs", "glibc"]
depends = ["gcc-libs", "glibc", "git"]
[pacman.files]
"deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method"
"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt"
"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT"
"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE"
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# The program's version: the one place it is written is `version = "..."`
# in crates/ledger-cli/Cargo.toml (plan P15 C1, WB-pkg-6). Every package, the
# release workflow and the installer take it from here; the program itself
# reports the same file's version through `CARGO_PKG_VERSION`.
#
# deploy/packaging/version.sh prints 0.1.0
#
# A version that is not three plain numbers is refused: the Windows
# installer's file-version fields and the macOS bundle's both need them.
set -eu
here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/../../crates/ledger-cli/Cargo.toml" | head -n1)
case "$version" in
[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "version.sh: no x.y.z version in crates/ledger-cli/Cargo.toml (found: '$version')" >&2; exit 1 ;;
esac
case "$version" in
*[!0-9.]*) echo "version.sh: '$version' is not three plain numbers" >&2; exit 1 ;;
esac
printf '%s\n' "$version"
+5 -3
View File
@@ -1,7 +1,9 @@
[Desktop Entry]
Categories=Office;Finance;
Type=Application
Name=Wanderbooks
Comment=Double-entry bookkeeping your agent keeps and you can read.
Exec=wanderbooks
Name=Wanderbooks
Icon=wanderbooks
Terminal=false
Type=Application
Categories=Office;Finance;
StartupWMClass=wanderbooks
+1
View File
@@ -8,3 +8,4 @@ Icon={{icon}}
Name={{name}}
Terminal=false
Type=Application
StartupWMClass=wanderbooks
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# The Windows installer (plan P15 unit C1), from the release program already
# built at target/release/wanderbooks.exe (`cargo build --release -p
# ledger-cli`). Run from the repository root, in Git Bash on Windows (CI:
# the `windows` job of .github/workflows/release.yml) or anywhere makensis
# is:
#
# build-windows.sh [VERSION]
#
# Puts Wanderbooks-VERSION-windows-x64-setup.exe into target/packages/VERSION/.
# VERSION defaults to the program's own (deploy/packaging/version.sh).
# WB_PROGRAM names another program file; WB_MAKENSIS another makensis.
#
# Unsigned: signing is a separate, optional step (sign-windows.ps1) that
# runs when the release workflow has the certificate's secrets.
set -euo pipefail
here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
root=$(CDPATH='' cd -- "$here/../../.." && pwd)
cd "$root"
own=$(sh deploy/packaging/version.sh)
version=${1:-$own}
case "$version" in
[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "build-windows: '$version' is not an x.y.z version" >&2; exit 1 ;;
esac
program=${WB_PROGRAM:-target/release/wanderbooks.exe}
out="target/packages/$version"
installer="Wanderbooks-$version-windows-x64-setup.exe"
fail() { echo "build-windows: $*" >&2; exit 1; }
test -f "$program" || fail "the release program is not at $program: run cargo build --release -p ledger-cli first"
for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/wanderbooks.ico deploy/packaging/windows/wanderbooks.nsi; do
test -f "$f" || fail "$f is missing from the repository"
done
makensis=${WB_MAKENSIS:-}
if [ -z "$makensis" ]; then
if command -v makensis >/dev/null 2>&1; then
makensis=makensis
elif [ -x "/c/Program Files (x86)/NSIS/makensis.exe" ]; then
makensis="/c/Program Files (x86)/NSIS/makensis.exe"
else
fail "makensis (NSIS) is not installed: choco install nsis, or apt install nsis"
fi
fi
# NSIS is a Windows program; Git Bash must neither rewrite its options
# (-D...) nor hand it a Unix path, so paths are made native here.
export MSYS2_ARG_CONV_EXCL='*'
native() { if command -v cygpath >/dev/null 2>&1; then cygpath -w "$1"; else printf '%s\n' "$1"; fi; }
rm -rf "${out:?}"
mkdir -p "$out"
"$makensis" -V2 \
"-DVERSION=$version" \
"-DPROGRAM=$(native "$program")" \
"-DICON=$(native deploy/packaging/icons/wanderbooks.ico)" \
"-DLICENSES=$(native "$root")" \
"-DOUTFILE=$(native "$out/$installer")" \
"$(native deploy/packaging/windows/wanderbooks.nsi)"
test -s "$out/$installer" || fail "makensis finished but $out/$installer is missing or empty"
ls -l "$out"
+36
View File
@@ -0,0 +1,36 @@
# Sign Windows files with an Authenticode code-signing certificate (plan P15
# unit C1). The release workflow runs this only when its secrets exist
# (WINDOWS_CERTIFICATE_PFX_BASE64 and WINDOWS_CERTIFICATE_PASSWORD); with none
# it prints a notice and the installer stays unsigned (SmartScreen warns).
#
# sign-windows.ps1 FILE [FILE...]
#
# The certificate is written to a temporary file for the signing and
# removed. Nothing here prints a secret. A failure is loud: a signature that
# was asked for and did not happen stops the release.
param([Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)][string[]]$Files)
$ErrorActionPreference = 'Stop'
if (-not $env:WINDOWS_CERTIFICATE_PFX_BASE64 -or -not $env:WINDOWS_CERTIFICATE_PASSWORD) {
Write-Host "::notice title=Windows signing skipped::no WINDOWS_CERTIFICATE_PFX_BASE64 / WINDOWS_CERTIFICATE_PASSWORD secret: the installer is unsigned and Windows SmartScreen will warn on the first run."
exit 0
}
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin" -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -match '\\x64\\' } |
Sort-Object FullName -Descending | Select-Object -First 1
if (-not $signtool) { throw "signtool.exe was not found in the Windows SDK on this runner" }
$pfx = Join-Path $env:RUNNER_TEMP 'wanderbooks-codesign.pfx'
[IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_PFX_BASE64))
try {
foreach ($file in $Files) {
& $signtool.FullName sign /fd sha256 /f $pfx /p $env:WINDOWS_CERTIFICATE_PASSWORD /tr http://timestamp.digicert.com /td sha256 $file
if ($LASTEXITCODE -ne 0) { throw "signtool failed on $file" }
& $signtool.FullName verify /pa $file
if ($LASTEXITCODE -ne 0) { throw "the signature on $file does not verify" }
Write-Host "signed $file"
}
} finally {
Remove-Item $pfx -Force -ErrorAction SilentlyContinue
}
+144
View File
@@ -0,0 +1,144 @@
; The Wanderbooks installer for Windows (plan P15 unit C1; WB-pkg-1, WB-pkg-2,
; WB-pkg-7). Built by deploy/packaging/windows/build-windows.sh with NSIS
; (https://nsis.sourceforge.io, free software, zlib licence).
;
; makensis -DVERSION=0.1.0 -DPROGRAM=...\wanderbooks.exe -DICON=...\wanderbooks.ico ^
; -DLICENSES=<folder> -DOUTFILE=...\Wanderbooks-0.1.0-windows-x64-setup.exe wanderbooks.nsi
;
; What it does, and the rules it keeps:
; * Per user: RequestExecutionLevel user, so double-clicking it shows no
; administrator prompt. Everything goes under the person's own profile
; and HKEY_CURRENT_USER.
; * One program file, wanderbooks.exe. It is the window, the books
; server's child and the assistants' bridge; an assistant is registered
; with this installed path, which an update keeps (the same folder, the
; same file name, replaced in place).
; * A Start Menu entry named Wanderbooks, with the icon, and an entry in
; Settings > Apps (the uninstaller).
; * The uninstaller removes the files this installer put in the install
; folder, the Start Menu entry and its two registry keys. It NEVER
; removes the person's books, keys, backups or settings: they live in
; the data folder (%LOCALAPPDATA%\wanderbooks), which this script
; names nowhere, and no command below deletes a folder's contents or
; uses a wildcard (a test, crates/ledger-cli/tests/packaging.rs, reads
; this file and fails if one appears).
; * It asks the person to quit Wanderbooks fully before it replaces or
; removes the program (a running program cannot be replaced).
; * Unsigned until the owner has a code-signing certificate: Windows
; SmartScreen says so on the first run (docs/install.md).
Unicode true
SetCompressor /SOLID lzma
!include "MUI2.nsh"
!include "LogicLib.nsh"
!ifndef VERSION
!error "pass -DVERSION=x.y.z (deploy/packaging/version.sh)"
!endif
!ifndef PROGRAM
!error "pass -DPROGRAM=<path to wanderbooks.exe>"
!endif
!ifndef ICON
!error "pass -DICON=<path to wanderbooks.ico>"
!endif
!ifndef LICENSES
!error "pass -DLICENSES=<folder with LICENSE-MIT, LICENSE-APACHE and THIRD-PARTY-NOTICES.txt>"
!endif
!ifndef OUTFILE
!error "pass -DOUTFILE=<the installer to write>"
!endif
!define NAME "Wanderbooks"
!define PUBLISHER "Wanderbooks"
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks"
!define APP_KEY "Software\Wanderbooks"
Name "${NAME}"
OutFile "${OUTFILE}"
RequestExecutionLevel user
InstallDir "$LOCALAPPDATA\Programs\Wanderbooks"
InstallDirRegKey HKCU "${APP_KEY}" "InstallDir"
BrandingText "${NAME} ${VERSION}"
ShowInstDetails nevershow
ShowUninstDetails nevershow
VIProductVersion "${VERSION}.0"
VIAddVersionKey "ProductName" "${NAME}"
VIAddVersionKey "FileDescription" "${NAME} installer"
VIAddVersionKey "FileVersion" "${VERSION}"
VIAddVersionKey "ProductVersion" "${VERSION}"
VIAddVersionKey "LegalCopyright" "MIT OR Apache-2.0"
!define MUI_ICON "${ICON}"
!define MUI_UNICON "${ICON}"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_RUN "$INSTDIR\wanderbooks.exe"
!define MUI_FINISHPAGE_RUN_TEXT "Start ${NAME}"
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
; A program that is running cannot be replaced or removed. Try to open the
; installed file for writing; if it is in use, ask the person to quit
; Wanderbooks (its window, which closes the books and the server) and retry.
!macro WaitUntilNotRunning
${Do}
ClearErrors
${If} ${FileExists} "$INSTDIR\wanderbooks.exe"
FileOpen $0 "$INSTDIR\wanderbooks.exe" a
${IfNot} ${Errors}
FileClose $0
${Break}
${EndIf}
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "${NAME} is open. Quit it fully (close its window), then choose Retry." IDRETRY +2
Abort "${NAME} is still open."
${Else}
${Break}
${EndIf}
${Loop}
!macroend
Section "Install"
SetOutPath "$INSTDIR"
!insertmacro WaitUntilNotRunning
File "/oname=wanderbooks.exe" "${PROGRAM}"
File "/oname=wanderbooks.ico" "${ICON}"
File "/oname=LICENSE-MIT" "${LICENSES}\LICENSE-MIT"
File "/oname=LICENSE-APACHE" "${LICENSES}\LICENSE-APACHE"
File "/oname=THIRD-PARTY-NOTICES.txt" "${LICENSES}\THIRD-PARTY-NOTICES.txt"
WriteUninstaller "$INSTDIR\Uninstall Wanderbooks.exe"
CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe" "" "$INSTDIR\wanderbooks.ico" 0
WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${NAME}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\wanderbooks.ico"
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "URLInfoAbout" "https://wanderbooks.ai"
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe"'
WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe" /S'
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
SectionEnd
Section "Uninstall"
!insertmacro WaitUntilNotRunning
Delete "$INSTDIR\wanderbooks.exe"
Delete "$INSTDIR\wanderbooks.ico"
Delete "$INSTDIR\LICENSE-MIT"
Delete "$INSTDIR\LICENSE-APACHE"
Delete "$INSTDIR\THIRD-PARTY-NOTICES.txt"
Delete "$INSTDIR\Uninstall Wanderbooks.exe"
; Only if empty: a folder the person put something in stays.
RMDir "$INSTDIR"
Delete "$SMPROGRAMS\${NAME}.lnk"
DeleteRegKey HKCU "${UNINSTALL_KEY}"
DeleteRegKey HKCU "${APP_KEY}"
; The person's books, keys, backups and settings are not here: they are
; in the data folder, which an uninstall leaves exactly as it is.
SectionEnd
+63
View File
@@ -0,0 +1,63 @@
# Installing Wanderbooks
For a person who wants to use it. Three short sections, one per system, then
what to do after. The release page has the files:
https://github.com/swaits/wanderbooks/releases/latest
Wanderbooks keeps your books on your own computer. An assistant (Claude,
ChatGPT, Codex and others) can reach them **only while Wanderbooks is open**,
and only the companies you have open in its tabs. When you are finished,
close the window: that quits Wanderbooks fully and closes your books.
## Windows
1. Download `Wanderbooks-…-windows-x64-setup.exe` and double-click it. It asks
for no administrator password: it installs for you alone.
2. Until the installer is signed, Windows shows "Windows protected your PC".
Choose **More info**, then **Run anyway**. (Unsigned software always does
this the first time.)
3. Open **Wanderbooks** from the Start Menu. The first time, it makes your
books' folder and helps you connect your assistant.
4. To update, run the newer installer over the old one. To remove it, use
Settings, Apps, Wanderbooks. Neither touches your books.
Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your
books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`.
Backups need Git for Windows (https://git-scm.com/download/win, or `winget
install --id Git.Git -e`); without it Wanderbooks works and says so.
## macOS
1. Download `Wanderbooks-…-macos-universal.dmg` (one file for Apple silicon and
Intel), open it, and drag **Wanderbooks** onto **Applications**.
2. Open it from Applications, not from the disk image or your Downloads folder
(an assistant needs the program to stay in one place). Until the app is
notarized by Apple, the first time: right-click it, choose **Open**, then
**Open** again.
3. To update, quit Wanderbooks and drag the newer app over the old one. To
remove it, drag it to the Trash. Neither touches your books.
Your books, keys and backups are in `~/Library/Application Support/wanderbooks`.
Backups need git: run `xcode-select --install` in Terminal (or `brew install
git`).
## Linux
Use the package for your system from the release page: the `.deb` (Debian,
Ubuntu), the `.rpm` (Fedora), the Arch package, or the AppImage (one file: mark
it executable, keep it where you put it, and run it). Open **Wanderbooks** from
the menu. To update, install the newer package, or replace the AppImage. Your
books are in `~/.local/share/wanderbooks` and are never touched by a package.
Backups need git (`sudo apt install git`, `sudo dnf install git`,
`sudo pacman -S git`).
## After it is installed
Open the **Assistants** page of a company. Pick the assistant you use: Claude
Code and Codex have a button; **Claude desktop app** has a button that makes one
extension file to open in Claude (Settings, Extensions, Advanced settings,
Install Extension); web assistants have an address and the steps. Wanderbooks
tells you in the window when a newer version is out.
`wanderbooks serve` (a server with no window, for another computer) is for
people who run it themselves: see `deploy/README.md`.
+90 -3
View File
@@ -16,8 +16,8 @@ not a tool, so there is nothing for a recipe to call.
| `.rpm` | `cargo-generate-rpm` (table in `crates/ledger-cli/Cargo.toml`) | same paths, marker `rpm`; 36 MB | dnf repository (`repo-indexes.sh dnf`) | unsigned until step 5 (`--signing-key` takes the PGP key then) |
| AUR `PKGBUILD` | `cargo packager` makes the tarball (`pacman` format) and a PKGBUILD for it; ours is `deploy/packaging/aur/PKGBUILD`, which repacks the release's tarball (package `wanderbooks-bin`) | same paths, marker `aur`; built with `makepkg` | pacman (the AUR keeps old PKGBUILDs) | n/a (pacman trusts the AUR's checksums) |
| AppImage | `cargo packager` (`appimage`); 44 MB | one file the owner puts anywhere and runs; needs no admin password | `wanderbooks update` (`$APPIMAGE` is the file replaced) against the manifest; minisign | minisign by the release key (step 5) |
| `.dmg` | `cargo packager` (`dmg`), `deploy/packaging/build-macos.sh`; **built in CI, unsigned; the trial on a Mac is the owner's** | `Wanderbooks.app` dragged to Applications; no admin password (the trial will say) | `wanderbooks update` (it replaces the program inside the `.app`: see the note below) | **unsigned**; Developer ID and notarization are step 5 |
| NSIS `.exe` | `cargo packager` (`nsis`) | **not built**: native Windows is unit P11c (D-62) | `wanderbooks update` | the Windows identity (step 5) |
| `.dmg` | `deploy/packaging/macos/build-macos.sh` (P15 C1; it replaced the cargo-packager `dmg` config, unrun) | `Wanderbooks.app` dragged to Applications; one universal program at `Contents/MacOS/wanderbooks`; no admin password | the newer app dragged over the old (the program tells the person one exists) | hardened runtime; Developer ID and notarization when the owner's secrets are in the release workflow, else ad hoc |
| Windows `.exe` | `deploy/packaging/windows/build-windows.sh` with NSIS (P15 C1; not cargo-packager's `nsis`) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe`, Start Menu entry, Settings > Apps uninstaller; per user, no admin | the newer installer run over the old one (the program tells the person one exists) | Authenticode when the owner's certificate secrets are in the release workflow, else unsigned |
`just package-linux` builds the first four (`deploy/packaging/build-linux.sh`,
about a minute after the release build, itself 8 to 12 minutes on a
@@ -130,7 +130,7 @@ package manager. Not tested: Ubuntu, openSUSE, a package-manager
*downgrade* (the repositories keep every release by construction), and the
`.rpm` and `.deb` under their real signatures (step 5).
## The macOS bundle (step 6, built in CI, unsigned)
## The macOS bundle (step 6; REPLACED by P15 unit C1, see "P15 unit C1" below)
`deploy/packaging/packager-macos.toml` (cargo-packager: the `dmg` format,
which makes the `.app` first; the icon is the 512 px PNG, made into an
@@ -260,3 +260,90 @@ not a `cfg` gap. Today Unix-only, found by grep (2026-10-29):
file with read, write and delete sharing, so a rename never meets an
open handle of ours.
- The `portable` job runs Windows as a gate (`experimental: false`), since the port landed (P11c).
## P15 unit C1: the installed app on the new shape (2026-11-21)
Written on Linux. **Nothing here has been run on Windows or macOS**: the
`release` workflow's first run on GitHub is the evidence, and it is built to
fail loudly at each step. What Linux checked: `crates/ledger-cli/tests/packaging.rs`
reads the installer script, the plist, the entitlements, the desktop entries and
the workflow; builds the macOS bundle with a stand-in program; compiles the
installer with `makensis` when it is installed; and a real `.deb` and `.rpm`
were built with a stand-in program and their file lists read (program, desktop
entry, icon, licences).
| | Windows | macOS | Linux |
|---|---|---|---|
| Package | NSIS installer, per user | `.app` in a `.dmg`, one universal program | `.deb`, `.rpm`, pacman tarball, AppImage (unchanged tools) |
| Program path (the bridge's) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` | `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks` | `/usr/bin/wanderbooks`; the AppImage's own file |
| Books | `%LOCALAPPDATA%\wanderbooks` | `~/Library/Application Support/wanderbooks` | `~/.local/share/wanderbooks` (unchanged) |
| Removal leaves the books | the uninstaller names no data folder | dragging to Trash runs nothing | no package script runs |
| No console window | built for the GUI subsystem; attaches to a terminal for commands | n/a | n/a |
| Without git | says how to get Git for Windows | says `xcode-select --install`; the system's stub is not taken for git | says the package manager's command |
**Why NSIS written by hand, not cargo-packager's.** The installer's rules
(per user, one program, an uninstaller that can never reach the books) are
short and exact; a script of our own states them in a file a test can read, and
needs only `makensis` (free, zlib-licensed, `choco install nsis`). cargo-packager's
NSIS template downloads helper plugins at build time and ships an uninstaller
option that removes application data. **Why the macOS bundle is assembled by a
script:** signing order (inside out, hardened runtime, then the disk image, then
notarization) and the entitlements are exact, and the secrets contract is ours.
cargo-packager stays for Linux.
**Updating** is installing the newer package over the old one; the program says
when one exists (`ledger_host::newer`: a version number from `latest.json`,
once a day, a fixed download address) and never installs anything. The earlier
staged self-update (`update`, `update.lock`, the daily staged download) still
exists for an AppImage or a program put somewhere by hand and needs a release
key that does not exist yet; on the desktop the detached host it restarted
through is gone (P15 A5). A macOS `.app` is never updated one file at a time.
**Signing.** Windows (secrets `WINDOWS_CERTIFICATE_PFX_BASE64`,
`WINDOWS_CERTIFICATE_PASSWORD`): `sign-windows.ps1` signs the program, then the
installer. macOS (`APPLE_CERTIFICATE_P12_BASE64`, `APPLE_CERTIFICATE_PASSWORD`,
`APPLE_SIGNING_IDENTITY`; to notarize `APPLE_ID`, `APPLE_TEAM_ID`,
`APPLE_APP_SPECIFIC_PASSWORD`): `import-certificate.sh` puts the certificate in
a temporary keychain, `build-macos.sh` signs with the hardened runtime,
notarizes and staples. With none, each step prints a notice and the package is
unsigned (macOS: ad hoc, so it runs, but Gatekeeper refuses a download).
**The Claude desktop extension** (`ledger_host::extension`): an MCP Bundle
(`.mcpb`, the renamed `.dxt`; manifest version 0.3), one per company, made by the
Connect page's button; it runs the installed program as `mcp --book <id>`.
**Left out, on purpose:** an auto-installer; a Windows executable icon resource
(the shortcut and the uninstaller entry carry the icon, and the running window
sets its own from the 512 px PNG; Explorer shows the `.exe` with the default
icon);
`wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a
GUI-subsystem program returns the prompt at once); a macOS refusal for a program
run from a mounted disk image (a path under `/Volumes` may be a real install on
another disk); bundling git on Windows and macOS (the owner's decision, below); the signed `manifest.json` of the earlier self-update
(needs the release key, Q-4).
### Bundling git (an owner decision, not made here)
Backups run the system's git. **Linux:** the packages now depend on git, so the
package manager fetches it (nothing is bundled). **Windows and macOS:** the app
detects a missing git and says how to get it (WB-pkg-4); nothing is bundled.
What bundling would mean. Git is GPL-2.0-only free software. Shipping an
unmodified git as a separate file that our program starts as its own process
(never linked) is what the GPL calls aggregation: our MIT OR Apache-2.0 code is
unaffected, and AGENTS.md's clean-room rule (never copy GnuCash's code) is not
touched, since nothing of git is copied into ours; `deny.toml` governs Rust
crates only and does not see it. It still requires, for each release that
carries git: git's GPL text and copyright notices beside it (Git for Windows'
MinGit adds the notices of the components it carries: OpenSSL/curl, the MSYS2
runtime); the corresponding source of exactly that git, or a written offer for it
valid three years (GPLv2 section 3), most simply the git version's source
archive attached to the same release; no term of ours that forbids the
recipient what the GPL permits; and a note of any change if git were modified.
`THIRD-PARTY-NOTICES.txt` (cargo-about) covers Rust crates only, so it would
need an addition. On Windows the candidate is MinGit from Git for Windows
(about 40 MB, unpacked beside the program; `Git::find` would look there first);
on macOS Apple's command line tools' git is Apple's and cannot be bundled, so
it would be a build of our own (Homebrew's, or from source), universal, signed
inside the app, with the same obligations.
+175
View File
@@ -0,0 +1,175 @@
# Claims: packaging
Wanderbooks' own product rules for how the program is installed, named,
updated and removed on Windows, macOS and Linux (plan P15 unit C1,
`plan/p15-app-and-relay.md`). No authority outside this product states them.
They are `WB-pkg-<n>`.
Rules: none from bookspec's list; these are product rules only.
---
### Product rules
**WB-pkg-1 It installs like a normal program, and taking it away never takes
the books.** A person downloads one file and opens it. On Windows that is an
installer that asks for no administrator password, installs under their own
profile, adds a Start Menu entry named Wanderbooks with the icon, and lists
an uninstaller in Settings. On macOS it is a disk image holding the app and a
shortcut to Applications to drag it onto. On Linux it is the package manager's
package, or one AppImage file. The Windows uninstaller removes exactly the
files the installer put in its own folder, the Start Menu entry and two
registry keys of its own: it uses no recursive removal and no wildcard and
names the data folder nowhere, and it asks the person to quit the app first
rather than fail on a program that is running. Moving the macOS app to the
Trash, or removing a Linux package, never runs a script. Each leaves the
person's books, keys, backups and settings where they are (WB-pkg-8).
*Enforced:* `deploy/packaging/windows/wanderbooks.nsi`,
`deploy/packaging/macos/build-macos.sh`, `deploy/packaging/packager.toml`.
*Checked:* `ledger-cli` `tests/packaging.rs`
(`the_windows_installer_is_per_user_and_installs_one_program`,
`the_uninstaller_never_removes_the_books`,
`no_package_runs_a_script_that_could_touch_the_books`,
`the_installer_script_compiles_when_nsis_is_here`,
`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`);
the release workflow's Windows job installs the installer, installs it over
itself and uninstalls it with a marker in the data folder that must survive.
**WB-pkg-2 One executable is the window, the books server and the
assistants' bridge, and the path an assistant is given does not change.** The
installed program is one file, `wanderbooks`, started three ways: with
nothing to say, as the window; by the window with `server`, as its child; and
by an assistant with `mcp --book`, as the bridge. No second program is
installed. The path an assistant is registered with is the installed file's own:
`%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` on Windows, which the
installer replaces in place; `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks`
on macOS, which dragging a newer app over the old one replaces; `/usr/bin/wanderbooks`
for a Linux package, replaced by the package manager; and the AppImage's own
file, which the person keeps where they put it. On macOS a program running from
the temporary copy the system makes of a quarantined download still refuses to
register an assistant, in words, since that path goes away. On Windows the file
is built for the GUI subsystem, so starting it from the Start Menu opens no
console window; run from a terminal it attaches to that terminal so a
command's words appear there, and it never replaces a pipe an assistant gave
it. The two console programs the window starts (the assistant's own list and
the system's opener) are started without a console window.
*Enforced:* `ledger_host::start::translocation_refusal`,
`ledger_host::start::this_executable`, `crates/ledger-cli/src/console.rs` (the Windows
console), `ledger_host::app_server` (the server child).
*Checked:* `ledger-cli` `tests/one_executable.rs`
(`each_mode_names_itself_in_its_usage`), `tests/translocation.rs`
(`translocated_app_refuses_to_connect`),
`tests/packaging.rs` (`the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal`,
`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`);
the release workflow's Windows job checks the built file's subsystem is the GUI one
and that it still prints through a pipe.
**WB-pkg-3 An update is the newer package installed over the old one, and the
app says when one exists.** The program installs nothing by itself. Once a day
at most, on a thread of its own, it reads one small public file a release
publishes and takes the version number from it and nothing else: where to get
the update is an address fixed in the program, never one the file names. A
higher version shows a notice in the window with a button to the download page,
and says the books, keys and connections stay as they are, because they live in
the data folder and the bridge's path is the same (WB-pkg-2). "Check for
updates" looks at once. The look sends no version, company or identifier and
a failed look is silent. A macOS app is never updated one file at a time
(that would break its signature): the program treats it as managed and says to
drag the newer app over the old one. Where the program may replace itself with
a release signed by our key (an AppImage, a program put somewhere by hand), the
earlier staged update still works; no release key exists yet, so today none does.
*Enforced:* `ledger_host::newer`, `ledger_host::update::install_kind`,
`ledger_host::commands::check_for_updates`, `ledger_gui::owner::NewerVersion`.
*Checked:* `ledger-host` unit tests in `newer.rs`
(`only_a_higher_plain_version_is_newer`,
`the_feed_gives_a_version_and_nothing_else`,
`a_look_is_noted_and_the_next_is_a_day_away`,
`a_failed_look_says_nothing_and_still_counts`, `the_note_is_private`) and
`update.rs` (`a_macos_app_is_never_updated_in_place`); `ledger-gui`
`tests/update_notice.rs` (`a_newer_version_is_told_with_where_to_get_it`).
**WB-pkg-4 Without git, backups are off and the person is told how to get
it.** Backups run the system's git; the program carries none. With no git found, a
backup says so in plain words for the system it runs on (Git for Windows or winget; Apple's
command line tools or Homebrew; the package manager) and the books work as
ever; the next backup looks again, so installing git needs no restart. On a Mac
without the developer tools, the stub at the system's git path is not taken for a
git. Whether to ship a git with the app is the owner's decision, since git is
GPL-2.0-only free software and shipping it carries a source offer and notices.
*Enforced:* `ledger_store::backup::how_to_get_git`,
`ledger_store::backup::Git::find`.
*Checked:* `ledger-store` unit tests in `backup.rs`
(`a_missing_git_says_how_to_get_it`,
`the_mac_stub_is_not_a_git_until_the_developer_tools_are_there`);
`ledger-cli` `tests/packaging.rs`
(`the_linux_packages_depend_on_git_and_none_carries_one`).
**WB-pkg-5 The Connect page can write a one-click Claude desktop extension
for a company.** The "Claude desktop app" row has one button. It makes the
company's assistant key if there is none and writes
`wanderbooks-<id>.mcpb` in a folder named Extensions in Documents/Wanderbooks: an
MCP Bundle (Anthropic's extension format, a zip file with a manifest, manifest
version 0.3) whose server is a binary that runs this program's installed path
as `mcp --book <id>` (WB-pkg-2). The package carries no program, no key, no
passphrase and no path of the data root. The page then says in words where in Claude's
settings to pick the file (Settings, Extensions, Advanced settings, Install
Extension), to keep Wanderbooks open, and offers to show the file. A program
running from a translocated copy writes nothing and says to move it first.
*Enforced:* `ledger_host::extension::claude_desktop_extension`,
`ledger_host::extension::manifest`.
*Checked:* `ledger-cli` `tests/extension.rs`
(`the_manifest_is_one_the_published_schema_accepts`,
`every_file_the_manifest_names_is_in_the_package`,
`the_server_runs_this_programs_bridge_for_the_company`); `ledger-host` unit
tests in `extension.rs`
(`no_secret_and_no_data_root_is_in_the_package`); `ledger-gui`
`tests/assistants.rs`
(`the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next`).
**WB-pkg-6 One version, and the product is named Wanderbooks wherever a
person sees it.** The version is written once, in the program's own manifest
(`crates/ledger-cli/Cargo.toml`); every package script and the release workflow read it
through `deploy/packaging/version.sh`, which refuses anything that is not three
numbers, and the program reports it to the window, the update look and the
extension. The window's title, the Start Menu entry, the app bundle's name,
the uninstaller's entry and the installer are all "Wanderbooks". The
lower-case `wanderbooks` stays where it is an identifier a person does not
read: the program's file name, the window's app id, the data folder.
*Enforced:* `deploy/packaging/version.sh`, `ledger_host::program_version`.
*Checked:* `ledger-cli` `tests/packaging.rs`
(`the_version_is_written_once_and_every_script_reads_it_from_there`,
`a_version_that_is_not_three_numbers_is_refused`,
`the_desktop_entries_launch_plain_wanderbooks_with_the_icon_and_the_window_id`);
`ledger-gui` `tests/tabs.rs` (the window title tests).
**WB-pkg-7 A release is a draft that carries the licences and the sums.**
The release workflow runs on a version tag or by hand and never on an
ordinary push. It builds all three packages, runs each system's tests on that
system, and attaches the packages, the licence files, the third-party
notices (every package also carries them), the update note and a file of
SHA-256 sums to a draft release. It never publishes a release, never changes
one already published, and never pushes the apt or dnf repositories (a
separate workflow, by hand, from a published release does). Signing runs only
when the owner's secrets are present and says so in the run's notices when not.
*Enforced:* `.github/workflows/release.yml`,
`.github/workflows/publish-repos.yml`.
*Checked:* `ledger-cli` `tests/packaging.rs`
(`the_release_workflow_makes_a_draft_of_all_three_packages_and_publishes_nothing`,
`only_a_person_runs_the_workflow_that_publishes_the_repositories`,
`every_package_carries_the_licences_and_the_icon`).
**WB-pkg-8 The books live where each system keeps an app's own data, apart
from the program.** macOS: Library/Application Support/wanderbooks in the person's
home. Windows: the local application data folder, `wanderbooks` (never the
roaming one: the books are large, hold locks and belong to one machine).
Linux: the XDG data folder, `wanderbooks`, where the books have always been
(unchanged). The folder with the private keys and certificate for the web
address is owner-only on each system, as the data root is. No data folder is
inside any folder a program is installed to.
*Enforced:* `ledger_store::root::data_dir_for`,
`ledger_store::root::default_root`, `ledger_link::private::make_dir`.
*Checked:* `ledger-store` `tests/data_locations.rs`
(`each_system_keeps_its_data_where_it_keeps_an_apps_data`,
`no_data_folder_is_inside_an_install_folder`); `ledger-link` unit tests in
`private.rs` (`a_private_file_reads_back_and_is_mode_0600`,
`a_private_file_and_its_folder_are_owner_only_on_windows`).
+15 -2
View File
@@ -591,10 +591,23 @@ package-linux version="" formats="deb,appimage,pacman":
cargo build --release -p ledger-cli
deploy/packaging/build-linux.sh {{version}} {{formats}}
# Build the unsigned macOS .dmg (on a Mac; CI does it on a tag or dispatch)
# The macOS app and its universal .dmg (on a Mac; CI does it on a tag or
# dispatch). Signs and notarizes only with WB_SIGN_IDENTITY and WB_NOTARY_*
# in the environment (deploy/packaging/macos/build-macos.sh says which).
# Build the universal macOS .dmg
package-macos version="":
rustup target add aarch64-apple-darwin x86_64-apple-darwin
cargo build --release -p ledger-cli --target aarch64-apple-darwin
cargo build --release -p ledger-cli --target x86_64-apple-darwin
deploy/packaging/macos/build-macos.sh {{version}}
# The per-user Windows installer (in Git Bash on Windows, with NSIS: choco
# install nsis; CI does it on a tag or dispatch). Unsigned unless the
# release workflow signs it.
# Build the Windows installer
package-windows version="":
cargo build --release -p ledger-cli
deploy/packaging/build-macos.sh {{version}}
deploy/packaging/windows/build-windows.sh {{version}}
# A release folder on this machine signed with a throwaway key; then
# `wanderbooks update --feed file://DIR/manifest.json --trusted-key DIR/release.pub`
+29
View File
@@ -1,5 +1,34 @@
# STATUS — 2026-11-10: the evaluation batch: no money arithmetic outside the kernel in any crate, exact Decimal sums, four gates the build did not have
## 2026-11-21: P15 unit C1, the installed app (branch `t3/p15-c1-desktop-packages`)
Written on Linux; **nothing of it has run on Windows or macOS**, and no
package has been installed anywhere. The `release` workflow's first run is the
evidence. What is there (`docs/packaging.md`, "P15 unit C1"; `docs/install.md`;
claims `WB-pkg-1` to `WB-pkg-8` in `docs/spec/claims/packaging.md`):
- **Windows**: a per-user NSIS installer (no administrator prompt), one
program, a Start Menu entry named Wanderbooks, a Settings > Apps
uninstaller that cannot reach the books. The program is built for the GUI
subsystem, so no console window; a terminal still gets a command's words.
- **macOS**: a universal `.app` in a `.dmg` (hardened runtime, an empty
entitlements file with the reasons, a Documents-folder purpose string);
signing and notarization run only with the owner's Apple secrets.
- **Linux**: the tools are unchanged; the desktop entries carry the icon and
the window's app id, every package carries the licences, and the packages
depend on git.
- **The Claude desktop extension**: the Connect page's last row writes a
`.mcpb` (Anthropic's MCP Bundle, manifest 0.3) per company.
- **Update**: the window says when a newer version exists and where to get it
(a daily look at one small file; only a version number is read); the update
is the newer package installed over the old.
- **Release**: a draft only, tests on each system, SHA-256 sums, licences;
the apt/dnf publish moved to a by-hand workflow.
- **Owner's, open**: signing identities and their secrets; whether to bundle
git on Windows and macOS (a GPL-2.0 consequence, `docs/packaging.md`);
the first run of the release workflow on GitHub and the first install on a
clean Windows and macOS machine.
## 2026-11-10: the evaluation batch (plan/2026-11-09_TRIAGE.md)
A full evaluation of the project on 2026-11-09 found nothing wrong in the