Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

In-app updates for the Mac app

Lin (kwant bot)b13a11b77fa2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ba979b78..55516eda 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -54,6 +54,9 @@ jobs:
- uses: actions/checkout@v4
- name: check_site.py
run: python3 scripts/check_site.py
+ # latest.json for in-app Mac updates
+ - name: Script tests
+ run: python3 -m unittest discover -s scripts -p 'test_*.py'
rust:
name: rust
diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml
index 0c2f1709..8e572cd5 100644
--- a/.github/workflows/mac.yml
+++ b/.github/workflows/mac.yml
@@ -5,12 +5,21 @@ name: mac
# Pushing a mac-v* tag (mac-v0.1.0, or mac-v0.2.0-rc.1 for a prerelease) also publishes a GitHub
# release with the .dmg as kwant_universal.dmg, which the site's "Download for Mac" links to via
# releases/latest/download/kwant_universal.dmg. The tag must match apps/mac's version.
+#
+# In-app updates: every build also makes the updater bundle (kwant.app.tar.gz + .sig). Tag builds
+# sign it with the release key (secrets TAURI_SIGNING_PRIVATE_KEY / _PASSWORD) and a full release
+# publishes it with latest.json, which installed apps read from releases/latest/download/latest.json.
+# Pull requests and manual runs never see the release key: they sign with a throwaway key, so the
+# same steps run without the secret. A full release needs a "## [Mac x.y.z]" CHANGELOG section,
+# which becomes the update's notes.
on:
workflow_dispatch:
pull_request:
paths:
- "apps/mac/**"
- ".github/workflows/mac.yml"
+ - "scripts/mac_latest_json.py"
+ - "scripts/minisign_verify.py"
push:
tags:
- "mac-v*"
@@ -56,6 +65,11 @@ jobs:
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
if [ "$version" != "$base" ]; then echo "prerelease=true"; else echo "prerelease=false"; fi >> "$GITHUB_OUTPUT"
+ # a full release's update notes are its CHANGELOG section
+ if [ "$version" = "$base" ]; then
+ python3 -c 'import sys; sys.path.insert(0, "scripts"); import mac_latest_json as m; m.changelog_section(open("CHANGELOG.md").read(), sys.argv[1])' "$version" \
+ || { echo "::error::CHANGELOG.md has no \"## [Mac $version]\" section for the update notes"; exit 1; }
+ fi
dmg:
name: dmg
@@ -96,6 +110,18 @@ jobs:
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder || true
sleep 3
+ # Pull requests and manual runs sign the updater bundle with a throwaway key; only tag builds
+ # get the release key, so no PR code ever runs with it.
+ - name: Throwaway updater key
+ if: ${{ !startsWith(github.ref, 'refs/tags/mac-v') }}
+ run: |
+ set -euo pipefail
+ openssl rand -hex 16 > "$RUNNER_TEMP/ci-updater.password"
+ npx --yes @tauri-apps/cli@2 signer generate --ci -w "$RUNNER_TEMP/ci-updater.key" -p "$(cat "$RUNNER_TEMP/ci-updater.password")" > /dev/null
+ cp "$RUNNER_TEMP/ci-updater.key.pub" "$RUNNER_TEMP/updater.pub"
+ - name: Release updater key
+ if: startsWith(github.ref, 'refs/tags/mac-v')
+ run: python3 -c 'import json; print(json.load(open("apps/mac/tauri.conf.json"))["plugins"]["updater"]["pubkey"])' > "$RUNNER_TEMP/updater.pub"
- name: Build the universal app and .dmg
working-directory: apps/mac
timeout-minutes: 30
@@ -103,7 +129,58 @@ jobs:
# Tauri skips the Finder AppleScript that lays out the install window (background,
# icon positions, hidden files moved out of view) when CI=true; run it anyway
TAURI_BUNDLER_DMG_IGNORE_CI: "true"
- run: npx --yes @tauri-apps/cli@2 build --ci --target universal-apple-darwin --bundles app,dmg -- --locked
+ IS_TAG: ${{ startsWith(github.ref, 'refs/tags/mac-v') }}
+ TAURI_SIGNING_PRIVATE_KEY: ${{ startsWith(github.ref, 'refs/tags/mac-v') && secrets.TAURI_SIGNING_PRIVATE_KEY || '' }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ startsWith(github.ref, 'refs/tags/mac-v') && secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD || '' }}
+ run: |
+ set -euo pipefail
+ if [ "$IS_TAG" = "true" ]; then
+ if [ -z "$TAURI_SIGNING_PRIVATE_KEY" ]; then
+ echo "::error::the repository secret TAURI_SIGNING_PRIVATE_KEY is missing, so installed apps couldn't verify this release"
+ exit 1
+ fi
+ else
+ TAURI_SIGNING_PRIVATE_KEY=$(cat "$RUNNER_TEMP/ci-updater.key")
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD=$(cat "$RUNNER_TEMP/ci-updater.password")
+ export TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD
+ fi
+ npx --yes @tauri-apps/cli@2 build --ci --target universal-apple-darwin --bundles app,dmg \
+ --config '{"bundle":{"createUpdaterArtifacts":true}}' -- --locked
+ # The installed app only accepts an update whose signature matches the key built into it and
+ # whose signed version matches latest.json (requireSignedVersion). Checked here with the same
+ # rules, so a bad bundle fails this job instead of every installed app.
+ - name: Updater bundle and latest.json
+ id: updater
+ working-directory: apps/mac/target/universal-apple-darwin/release/bundle
+ run: |
+ set -euo pipefail
+ tarball=macos/kwant.app.tar.gz
+ ls -l "$tarball" "$tarball.sig"
+ version=$(python3 -c 'import json; print(json.load(open("'"$GITHUB_WORKSPACE"'/apps/mac/tauri.conf.json"))["version"])')
+ python3 -m venv "$RUNNER_TEMP/sigvenv"
+ "$RUNNER_TEMP/sigvenv/bin/pip" install --quiet pynacl
+ "$RUNNER_TEMP/sigvenv/bin/python" -I "$GITHUB_WORKSPACE/scripts/minisign_verify.py" \
+ --pubkey "$RUNNER_TEMP/updater.pub" --file "$tarball" --signature "$tarball.sig" --version "$version"
+ # the archive holds kwant.app and nothing else
+ tar -tzf "$tarball" | cut -d/ -f1 | sort -u | tee "$RUNNER_TEMP/tar-top.txt"
+ test "$(cat "$RUNNER_TEMP/tar-top.txt")" = "kwant.app"
+ if grep -q "^## \[Mac $version\]" "$GITHUB_WORKSPACE/CHANGELOG.md"; then
+ python3 "$GITHUB_WORKSPACE/scripts/mac_latest_json.py" --version "$version" --signature "$tarball.sig" \
+ --changelog "$GITHUB_WORKSPACE/CHANGELOG.md" \
+ --url "https://github.com/$GITHUB_REPOSITORY/releases/download/mac-v$version/kwant_universal.app.tar.gz" \
+ > "$RUNNER_TEMP/latest.json"
+ cat "$RUNNER_TEMP/latest.json"
+ else
+ echo "::notice::no CHANGELOG section for Mac $version yet, so no sample latest.json"
+ fi
+ mkdir -p "$RUNNER_TEMP/updater"
+ cp "$tarball" "$tarball.sig" "$RUNNER_TEMP/updater/"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: updater
+ path: ${{ runner.temp }}/updater
+ if-no-files-found: error
+ retention-days: 14
- name: Inspect the bundle
id: bundle
working-directory: apps/mac/target/universal-apple-darwin/release/bundle
@@ -268,6 +345,8 @@ jobs:
permissions:
contents: write
steps:
+ # for scripts/mac_latest_json.py and the CHANGELOG section it reads
+ - uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: dist
@@ -283,6 +362,19 @@ jobs:
test -n "$dmg"
cp "$dmg" kwant_universal.dmg
sha256sum kwant_universal.dmg > kwant_universal.dmg.sha256
+ tarball=$(find dist -type f -name 'kwant.app.tar.gz' | head -1)
+ test -n "$tarball" && test -f "$tarball.sig"
+ cp "$tarball" kwant_universal.app.tar.gz
+ cp "$tarball.sig" kwant_universal.app.tar.gz.sig
+ assets=(kwant_universal.dmg kwant_universal.dmg.sha256 kwant_universal.app.tar.gz kwant_universal.app.tar.gz.sig)
+ # Installed apps read releases/latest/download/latest.json, which only ever resolves to the
+ # newest full release; a prerelease gets no latest.json, so it's never offered as an update
+ if [ "$PRERELEASE" != "true" ]; then
+ python3 scripts/mac_latest_json.py --version "$VERSION" --signature kwant_universal.app.tar.gz.sig \
+ --url "https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/kwant_universal.app.tar.gz" > latest.json
+ cat latest.json
+ assets+=(latest.json)
+ fi
cat > notes.md <<NOTES
kwant for Mac $VERSION: one universal app for Apple silicon and Intel Macs (macOS 11 or later).
@@ -304,4 +396,4 @@ jobs:
if [ "$PRERELEASE" = "true" ]; then flags+=(--prerelease); else flags+=(--latest); fi
gh release create "$TAG" -R "$GITHUB_REPOSITORY" --verify-tag \
--title "kwant for Mac $VERSION" --notes-file notes.md "${flags[@]}" \
- kwant_universal.dmg kwant_universal.dmg.sha256
+ "${assets[@]}"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 394dade9..d1adf991 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **Token budget per request.** When bots handing work to each other go over it (200k fresh tokens
by default, 0 turns it off) for one of your messages, they pause with one notice in the chat;
press **Continue** or say "continue" to let them go on.
+- **Updates inside the Mac app.** kwant bots for Mac checks for a new version on start and every 6 hours
+ and tells you once per version. **Update to x.y.z…** in the menu bar (or in the web app) downloads
+ it, checks its signature, replaces the app and restarts it. If anything goes wrong, the running
+ version keeps working. Versions before this one need one last download by hand.
### Changed
- A bot reply that ends with a closing line such as "Anything else?", "Should I continue?" or
@@ -50,6 +54,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- A CAPTCHA step now holds the browser before the step appears, so a bot can't act on the page in between.
### Security
+- Only the person can check for or install a Mac app update: `POST /api/app/update/check` and
+ `/install` refuse a bot's turn token. Bots can still read `GET /api/app/update`.
- Only the person can switch which computer the bots run on (Settings → Computer) or open their
browser as a window: `PUT /api/settings/computer` and `/api/settings/computer/window` now refuse
a bot's turn token, like `POST /api/settings`.
diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lock
index 446f0cf2..35c6679e 100644
--- a/apps/mac/Cargo.lock
+++ b/apps/mac/Cargo.lock
@@ -123,6 +123,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "arbitrary"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
+dependencies = [
+ "derive_arbitrary",
+]
+
[[package]]
name = "argon2"
version = "0.5.3"
@@ -1022,6 +1031,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "derive_arbitrary"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -1361,6 +1381,16 @@ dependencies = [
"rustc_version",
]
+[[package]]
+name = "filetime"
+version = "0.2.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+dependencies = [
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@@ -2427,6 +2457,36 @@ dependencies = [
"windows-sys 0.45.0",
]
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys 0.4.1",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.21",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -2507,6 +2567,7 @@ dependencies = [
"serde_json",
"tauri",
"tauri-build",
+ "tauri-plugin-updater",
"tokio",
"tracing",
"tracing-subscriber",
@@ -2557,7 +2618,7 @@ dependencies = [
"uuid",
"webpki-roots 1.0.9",
"zeroize",
- "zip",
+ "zip 9.0.5",
]
[[package]]
@@ -2777,6 +2838,12 @@ dependencies = [
"unicase",
]
+[[package]]
+name = "minisign-verify"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -3125,6 +3192,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.13.2",
"block2",
+ "libc",
"objc2",
"objc2-core-foundation",
]
@@ -3140,6 +3208,18 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-osa-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+]
+
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
@@ -3258,6 +3338,20 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "osakit"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+ "objc2-osa-kit",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "pango"
version = "0.18.3"
@@ -3863,15 +3957,20 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
+ "tokio-rustls",
"tokio-util",
"tower 0.5.3",
"tower-http 0.6.11",
@@ -3995,6 +4094,18 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
@@ -4004,6 +4115,33 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni 0.22.4",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
+
[[package]]
name = "rustls-webpki"
version = "0.103.15"
@@ -4429,6 +4567,16 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -4913,7 +5061,7 @@ dependencies = [
"gdkwayland-sys",
"gdkx11-sys",
"gtk",
- "jni",
+ "jni 0.21.1",
"libc",
"log",
"ndk",
@@ -4946,6 +5094,17 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "tar"
+version = "0.4.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
[[package]]
name = "target-lexicon"
version = "0.12.16"
@@ -4970,7 +5129,7 @@ dependencies = [
"heck 0.5.0",
"http",
"image",
- "jni",
+ "jni 0.21.1",
"libc",
"log",
"mime",
@@ -5068,6 +5227,56 @@ dependencies = [
"tauri-utils",
]
+[[package]]
+name = "tauri-plugin"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291"
+dependencies = [
+ "anyhow",
+ "glob",
+ "plist",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-plugin-updater"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7259989d4fe11b2bf51f7d671642249b1837c4ae2da1430dc713ae38f98ceeec"
+dependencies = [
+ "base64 0.22.1",
+ "dirs 7.0.0",
+ "flate2",
+ "futures-util",
+ "http",
+ "infer",
+ "libc",
+ "log",
+ "minisign-verify",
+ "osakit",
+ "percent-encoding",
+ "reqwest 0.13.5",
+ "rustls",
+ "semver",
+ "serde",
+ "serde_json",
+ "tar",
+ "tauri",
+ "tauri-plugin",
+ "tempfile",
+ "thiserror 2.0.21",
+ "time",
+ "tokio",
+ "url",
+ "windows-sys 0.61.2",
+ "zip 4.6.1",
+]
+
[[package]]
name = "tauri-runtime"
version = "2.12.2"
@@ -5078,7 +5287,7 @@ dependencies = [
"dpi",
"gtk",
"http",
- "jni",
+ "jni 0.21.1",
"objc2",
"objc2-ui-kit",
"objc2-web-kit",
@@ -5101,7 +5310,7 @@ checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
dependencies = [
"gtk",
"http",
- "jni",
+ "jni 0.21.1",
"log",
"objc2",
"objc2-app-kit",
@@ -6065,6 +6274,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webpki-roots"
version = "0.26.11"
@@ -6591,7 +6809,7 @@ dependencies = [
"gtk",
"http",
"javascriptcore-rs",
- "jni",
+ "jni 0.21.1",
"libc",
"ndk",
"objc2",
@@ -6638,6 +6856,16 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "xattr"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
+dependencies = [
+ "libc",
+ "rustix",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -6741,6 +6969,18 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "zip"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "indexmap 2.14.2",
+ "memchr",
+]
+
[[package]]
name = "zip"
version = "9.0.5"
diff --git a/apps/mac/Cargo.toml b/apps/mac/Cargo.toml
index 21455f5f..3d6bed5b 100644
--- a/apps/mac/Cargo.toml
+++ b/apps/mac/Cargo.toml
@@ -16,7 +16,8 @@ tauri-build = { version = "2", features = [] }
[dependencies]
kwnt = { path = "../.." }
tauri = { version = "2", features = ["tray-icon", "image-png"] }
-tokio = { version = "1.40", features = ["rt-multi-thread", "sync", "macros"] }
+tauri-plugin-updater = "2"
+tokio = { version = "1.40", features = ["rt-multi-thread", "sync", "macros", "time"] }
serde_json = "1.0"
dirs = "5.0"
tracing = "0.1"
diff --git a/apps/mac/README.md b/apps/mac/README.md
index c59a6162..cbc13b06 100644
--- a/apps/mac/README.md
+++ b/apps/mac/README.md
@@ -10,6 +10,12 @@ A Tauri v2 shell around kwant. The app links the `kwnt` crate and runs the same
`/opt/homebrew/bin`, `/usr/local/bin` and `~/.local/bin` to find `claude`, `codex` and `grok`.
- **Menu bar:** Open kwant, a status line (approvals waiting), Quit. Closing the window keeps kwant
running; Quit stops it.
+- **Updates:** 15 seconds after start and then every 6 hours the app reads
+ `releases/latest/download/latest.json` (prereleases are never offered). A newer version shows in
+ the web app (`GET /api/app/update`), as one notification per version and as **Update to x.y.z…**
+ at the top of the menu-bar menu. Installing downloads `kwant_universal.app.tar.gz`, checks its
+ signature against `plugins.updater.pubkey` in `tauri.conf.json`, replaces the app, stops kwant and
+ relaunches. If anything fails, the running app stays as it was. See `src/update.rs`.
- `kwant --check` starts kwant headless on a free port with a throwaway data dir, waits for
`/api/health` and exits 0. CI runs it on the built app.
@@ -35,3 +41,16 @@ into the image's `.DS_Store` through AppleScript, which Tauri skips when `CI=tru
files (`.VolumeIcon.icns`, `.background`, …) outside the window, so they stay out of view even
with hidden files shown. The art is drawn by `dmg/make-background.py`; `background.tiff` is built
from the two PNGs and not committed.
+
+## Releases and the updater key
+
+`mac.yml` signs the updater bundle on `mac-v*` tags with the repository secrets
+`TAURI_SIGNING_PRIVATE_KEY` and `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`, checks the signature
+(`scripts/minisign_verify.py`) and, for a full release, publishes `latest.json` built by
+`scripts/mac_latest_json.py` from the version's `## [Mac x.y.z]` CHANGELOG section. Pull requests
+sign with a throwaway key, so they never see the secret.
+
+The public half of the key is built into every app. If the private key is lost, installed apps can
+never update themselves again and everyone has to download the next version by hand, so keep a
+backup of the key and its password outside GitHub. Replacing the key works the same way: ship one
+release signed with the old key that carries the new public key.
diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rs
index fe73ef50..c2089280 100644
--- a/apps/mac/src/main.rs
+++ b/apps/mac/src/main.rs
@@ -2,6 +2,7 @@
//! Closing the window keeps kwant running; Quit in the menu stops it.
mod startup;
+mod update;
use startup::PortChoice;
use std::sync::{mpsc, Mutex};
@@ -68,10 +69,12 @@ fn main() {
};
let app = tauri::Builder::default()
+ .plugin(tauri_plugin_updater::Builder::new().build())
.manage(Target { port })
.setup(move |app| {
if let Some(server) = server {
app.manage(server);
+ update::start(app.handle());
}
build_tray(app.handle())?;
open_window(app.handle());
@@ -174,7 +177,10 @@ fn open_window(handle: &tauri::AppHandle) {
}
/// The menu-bar icon: Open kwant, a status line, Quit. The status counts approvals waiting.
+/// "Update to x.y.z…" appears at the top while a newer version is on offer.
fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {
+ let update = MenuItem::with_id(handle, "update", "Update kwant bots…", true, None::<&str>)?;
+ let update_separator = PredefinedMenuItem::separator(handle)?;
let open = MenuItem::with_id(handle, "open", "Open kwant", true, None::<&str>)?;
let status = MenuItem::with_id(handle, "status", "Starting…", false, None::<&str>)?;
let quit = MenuItem::with_id(handle, "quit", "Quit kwant", true, Some("CmdOrCtrl+Q"))?;
@@ -189,17 +195,43 @@ fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {
.show_menu_on_left_click(true)
.on_menu_event(|app, event| match event.id.as_ref() {
"open" => open_window(app),
+ "update" => {
+ // The window shows the download and the relaunch
+ if let Err(e) = kwnt::app_update::UpdateHub::shared().install() {
+ tracing::info!(reason = e.message(), "update from the menu not started");
+ }
+ open_window(app);
+ }
"quit" => app.exit(0),
_ => {}
})
.build(handle)?;
let port = handle.state::<Target>().port;
- std::thread::spawn(move || loop {
- let (line, badge) = status_line(port);
- let _ = status.set_text(line);
- let _ = tray.set_title(badge.as_deref());
- std::thread::sleep(Duration::from_secs(5));
+ let hub = kwnt::app_update::UpdateHub::shared();
+ std::thread::spawn(move || {
+ let mut shown = false;
+ loop {
+ let (line, badge) = status_line(port);
+ let _ = status.set_text(line);
+ let _ = tray.set_title(badge.as_deref());
+ match update::menu_item(&hub.status()) {
+ Some((text, enabled)) => {
+ if !shown {
+ shown = menu.insert_items(&[&update, &update_separator], 0).is_ok();
+ }
+ let _ = update.set_text(text);
+ let _ = update.set_enabled(enabled);
+ }
+ None if shown => {
+ let _ = menu.remove(&update);
+ let _ = menu.remove(&update_separator);
+ shown = false;
+ }
+ None => {}
+ }
+ std::thread::sleep(Duration::from_secs(5));
+ }
});
Ok(())
}
diff --git a/apps/mac/src/update.rs b/apps/mac/src/update.rs
new file mode 100644
index 00000000..873c4224
--- /dev/null
+++ b/apps/mac/src/update.rs
@@ -0,0 +1,188 @@
+//! In-app updates. The app asks GitHub's latest Mac release (`latest.json`, see `plugins.updater`
+//! in tauri.conf.json) on start and every 6 hours. The state lives on kwant's
+//! [`UpdateHub`](kwnt::app_update::UpdateHub), so the web app shows it through `/api/app/update`
+//! and the person starts the install there or from the menu-bar icon.
+//!
+//! Installing downloads the signed `kwant.app.tar.gz`, checks its signature against the public key
+//! built into this app, swaps the app bundle, stops the server (so nothing is half-written) and
+//! relaunches. Any failure before the swap leaves this app running as it was.
+
+use kwnt::app_update::{Available, State, Status, UpdateHub, Updater};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tauri::{AppHandle, Manager};
+use tauri_plugin_updater::{Update, UpdaterExt};
+
+const RELEASES: &str = "https://github.com/alexsergivan/kwant/releases";
+/// After start, so the check doesn't compete with kwant starting up.
+const FIRST_CHECK_AFTER: Duration = Duration::from_secs(15);
+const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
+/// Long enough for the web app to show "Restarting…" before the window goes away.
+const RELAUNCH_AFTER: Duration = Duration::from_millis(1500);
+
+/// The GitHub release page of `version`: "What's new" and "Download manually".
+pub fn release_page(version: &str) -> String {
+ format!("{RELEASES}/tag/mac-v{version}")
+}
+
+/// The menu-bar item for an update: its text and whether it can be clicked. `None`: no item.
+pub fn menu_item(status: &Status) -> Option<(String, bool)> {
+ let version = &status.available.as_ref()?.version;
+ match status.state {
+ State::Available | State::Error => Some((format!("Update to {version}…"), true)),
+ State::Downloading => Some(match status.progress {
+ Some(p) if p > 0.0 => (format!("Downloading kwant bots {version}… {}%", (p * 100.0).round() as u32), false),
+ _ => (format!("Downloading kwant bots {version}…"), false),
+ }),
+ State::Ready => Some(("Restarting kwant bots…".to_string(), false)),
+ State::Idle | State::Checking => None,
+ }
+}
+
+/// Registers the updater on kwant's hub and starts the checks. Only when this app runs the
+/// server: an attached kwant serves its own `/api/app/update`.
+pub fn start(app: &AppHandle) {
+ let hub = UpdateHub::shared();
+ let current = app.package_info().version.to_string();
+ let updater = Arc::new(MacUpdater {
+ app: app.clone(),
+ hub: hub.clone(),
+ found: Arc::new(Mutex::new(None)),
+ });
+ hub.register(&current, updater);
+ tracing::info!(current, "in-app updates on");
+ std::thread::Builder::new()
+ .name("kwant-update-check".into())
+ .spawn(move || {
+ std::thread::sleep(FIRST_CHECK_AFTER);
+ loop {
+ // Busy (downloading, relaunching) means there's nothing to check
+ let _ = hub.check();
+ std::thread::sleep(CHECK_EVERY);
+ }
+ })
+ .ok();
+}
+
+struct MacUpdater {
+ app: AppHandle,
+ hub: Arc<UpdateHub>,
+ /// The last check's release, which install downloads.
+ found: Arc<Mutex<Option<Update>>>,
+}
+
+impl Updater for MacUpdater {
+ fn check(&self) {
+ let (app, hub, found) = (self.app.clone(), self.hub.clone(), self.found.clone());
+ tauri::async_runtime::spawn(async move {
+ let result = match app.updater() {
+ Ok(updater) => updater.check().await,
+ Err(e) => Err(e),
+ };
+ match result {
+ Ok(Some(update)) => {
+ let release = Available {
+ version: update.version.clone(),
+ notes: update.body.clone().unwrap_or_default(),
+ date: update.raw_json["pub_date"].as_str().map(str::to_string),
+ url: release_page(&update.version),
+ };
+ tracing::info!(version = %update.version, "kwant update available");
+ *found.lock().unwrap() = Some(update);
+ hub.found(Some(release));
+ }
+ Ok(None) => {
+ *found.lock().unwrap() = None;
+ hub.found(None);
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "update check failed");
+ hub.failed(&format!("Couldn't check for updates: {e}"));
+ }
+ }
+ });
+ }
+
+ fn install(&self, version: &str) {
+ let update = self.found.lock().unwrap().clone().filter(|u| u.version == version);
+ let Some(update) = update else {
+ self.hub.failed("That update is no longer on offer. Check for updates again.");
+ return;
+ };
+ let (app, hub) = (self.app.clone(), self.hub.clone());
+ tauri::async_runtime::spawn(async move {
+ let mut received = 0u64;
+ let progress_hub = hub.clone();
+ // download() also checks the signature against the key built into this app
+ let bytes = update
+ .download(
+ |chunk, total| {
+ received += chunk as u64;
+ progress_hub.progress(total.filter(|t| *t > 0).map(|t| received as f64 / t as f64));
+ },
+ || {},
+ )
+ .await;
+ let bytes = match bytes {
+ Ok(b) => b,
+ Err(e) => {
+ tracing::warn!(error = %e, version = %update.version, "update download failed");
+ return hub.failed(&format!("The download failed: {e}"));
+ }
+ };
+ if let Err(e) = update.install(&bytes) {
+ tracing::warn!(error = %e, version = %update.version, "update install failed");
+ return hub.failed(&format!("Couldn't install the update: {e}"));
+ }
+ tracing::info!(version = %update.version, "update installed; relaunching");
+ hub.ready();
+ tokio::time::sleep(RELAUNCH_AFTER).await;
+ crate::stop_server(&app);
+ app.restart();
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn status(state: State, version: Option<&str>, progress: Option<f64>) -> Status {
+ Status {
+ supported: true,
+ current: "0.1.1".into(),
+ state,
+ available: version.map(|v| Available {
+ version: v.into(),
+ notes: String::new(),
+ date: None,
+ url: release_page(v),
+ }),
+ progress,
+ error: None,
+ }
+ }
+
+ #[test]
+ fn release_pages() {
+ assert_eq!(release_page("0.1.2"), "https://github.com/alexsergivan/kwant/releases/tag/mac-v0.1.2");
+ }
+
+ #[test]
+ fn menu_items() {
+ assert_eq!(menu_item(&status(State::Idle, None, None)), None);
+ assert_eq!(menu_item(&status(State::Checking, None, None)), None);
+ assert_eq!(menu_item(&status(State::Error, None, None)), None, "a failed check offers nothing");
+ assert_eq!(menu_item(&status(State::Available, Some("0.1.2"), None)), Some(("Update to 0.1.2…".into(), true)));
+ assert_eq!(menu_item(&status(State::Error, Some("0.1.2"), None)), Some(("Update to 0.1.2…".into(), true)), "retry");
+ assert_eq!(
+ menu_item(&status(State::Downloading, Some("0.1.2"), Some(0.0))),
+ Some(("Downloading kwant bots 0.1.2…".into(), false))
+ );
+ assert_eq!(
+ menu_item(&status(State::Downloading, Some("0.1.2"), Some(0.426))),
+ Some(("Downloading kwant bots 0.1.2… 43%".into(), false))
+ );
+ assert_eq!(menu_item(&status(State::Ready, Some("0.1.2"), Some(1.0))), Some(("Restarting kwant bots…".into(), false)));
+ }
+}
diff --git a/apps/mac/tauri.conf.json b/apps/mac/tauri.conf.json
index 0a4fac65..48598df9 100644
--- a/apps/mac/tauri.conf.json
+++ b/apps/mac/tauri.conf.json
@@ -16,6 +16,7 @@
"bundle": {
"active": true,
"targets": ["app", "dmg"],
+ "createUpdaterArtifacts": false,
"category": "DeveloperTool",
"shortDescription": "Your team of AI bots",
"copyright": "© 2026 the kwant maintainer. AGPL-3.0-only",
@@ -36,5 +37,12 @@
"applicationFolderPosition": { "x": 480, "y": 170 }
}
}
+ },
+ "plugins": {
+ "updater": {
+ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEE3OTFDNEY5QTBGRTEzMUYKUldRZkUvNmcrY1NScDlyak1rQWU0L1N3NHBXc2JhNnVzbk9MN2h3RksybmJleHRYbk9yZ0s5bHgK",
+ "endpoints": ["https://github.com/alexsergivan/kwant/releases/latest/download/latest.json"],
+ "requireSignedVersion": true
+ }
}
}
diff --git a/scripts/mac_latest_json.py b/scripts/mac_latest_json.py
new file mode 100644
index 00000000..faa8097a
--- /dev/null
+++ b/scripts/mac_latest_json.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python3
+"""Writes latest.json, the feed the Mac app's updater reads, for one Mac release.
+
+The app asks https://github.com/alexsergivan/kwant/releases/latest/download/latest.json, so only
+the newest non-prerelease release's file counts. The release notes are that version's CHANGELOG
+section ("## [Mac 0.1.2] - 2026-10-27"); a release without one fails here, before anything is
+published. Both Mac architectures point at the same universal app.
+
+ python3 scripts/mac_latest_json.py --version 0.1.2 --signature kwant.app.tar.gz.sig \\
+ --url https://github.com/alexsergivan/kwant/releases/download/mac-v0.1.2/kwant_universal.app.tar.gz \\
+ > latest.json
+"""
+
+import argparse
+import datetime
+import json
+import re
+import sys
+
+PLATFORMS = ("darwin-aarch64", "darwin-x86_64")
+VERSION = re.compile(r"^\d+\.\d+\.\d+$")
+
+
+def changelog_section(changelog: str, version: str) -> str:
+ """The body of `## [Mac <version>]`, up to the next `## ` heading, trimmed."""
+ heading = re.compile(r"^## \[Mac " + re.escape(version) + r"\](?:\s|$)")
+ lines = changelog.splitlines()
+ for i, line in enumerate(lines):
+ if heading.match(line):
+ body = []
+ for rest in lines[i + 1:]:
+ if rest.startswith("## "):
+ break
+ body.append(rest)
+ return "\n".join(body).strip()
+ raise ValueError(f"CHANGELOG.md has no '## [Mac {version}]' section")
+
+
+def latest_json(version: str, signature: str, url: str, notes: str, pub_date: str) -> dict:
+ if not VERSION.match(version):
+ raise ValueError(f"'{version}' is not a release version (x.y.z); prereleases get no latest.json")
+ signature = signature.strip()
+ if not signature:
+ raise ValueError("the signature is empty")
+ if not url.startswith("https://"):
+ raise ValueError("the download URL must be https")
+ if not notes:
+ raise ValueError(f"the CHANGELOG section for {version} is empty")
+ entry = {"signature": signature, "url": url}
+ return {
+ "version": version,
+ "notes": notes,
+ "pub_date": pub_date,
+ "platforms": {p: dict(entry) for p in PLATFORMS},
+ }
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--version", required=True)
+ ap.add_argument("--signature", required=True, help="the .sig file the Tauri build wrote")
+ ap.add_argument("--url", required=True, help="where the release serves the .app.tar.gz")
+ ap.add_argument("--changelog", default="CHANGELOG.md")
+ ap.add_argument("--pub-date", help="RFC 3339; default now (UTC)")
+ args = ap.parse_args(argv)
+ pub_date = args.pub_date or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ try:
+ with open(args.changelog, encoding="utf-8") as f:
+ notes = changelog_section(f.read(), args.version)
+ with open(args.signature, encoding="utf-8") as f:
+ signature = f.read()
+ doc = latest_json(args.version, signature, args.url, notes, pub_date)
+ except (OSError, ValueError) as e:
+ print(f"mac_latest_json: {e}", file=sys.stderr)
+ return 1
+ json.dump(doc, sys.stdout, indent=2, ensure_ascii=False)
+ sys.stdout.write("\n")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/minisign_verify.py b/scripts/minisign_verify.py
new file mode 100644
index 00000000..ec345948
--- /dev/null
+++ b/scripts/minisign_verify.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Checks a Tauri updater signature (minisign, base64-wrapped) the way the Mac app will.
+
+ python3 scripts/minisign_verify.py --pubkey <base64 pubkey | file> --file kwant.app.tar.gz \\
+ --signature kwant.app.tar.gz.sig [--version 0.1.2]
+
+Verifies the file signature (Ed25519 over the file's BLAKE2b-512 for prehashed "ED" signatures),
+the global signature over the trusted comment, that both keys match, and with --version that the
+trusted comment carries `version:<version>`, which the app requires (requireSignedVersion), so a
+release signed with the wrong key or without the version fails CI instead of every installed app.
+Needs PyNaCl (pip install pynacl).
+"""
+
+import argparse
+import base64
+import hashlib
+import os
+import sys
+
+from nacl.exceptions import BadSignatureError
+from nacl.signing import VerifyKey
+
+
+def _unwrap(text: str) -> list:
+ """Tauri stores minisign files base64-encoded; returns their lines."""
+ text = text.strip()
+ if not text.startswith("untrusted comment:"):
+ text = base64.b64decode(text).decode("utf-8")
+ return [line for line in text.splitlines() if line.strip()]
+
+
+def parse_pubkey(text: str):
+ raw = base64.b64decode(_unwrap(text)[1])
+ if len(raw) != 42 or raw[:2] != b"Ed":
+ raise ValueError("not a minisign Ed25519 public key")
+ return raw[2:10], raw[10:]
+
+
+def verify(pubkey_text: str, data: bytes, sig_text: str, version=None) -> str:
+ """Raises ValueError unless the signature is good; returns the trusted comment."""
+ key_id, pk = parse_pubkey(pubkey_text)
+ lines = _unwrap(sig_text)
+ if len(lines) < 4 or not lines[2].startswith("trusted comment: "):
+ raise ValueError("malformed signature file")
+ sig = base64.b64decode(lines[1])
+ if len(sig) != 74 or sig[:2] not in (b"Ed", b"ED"):
+ raise ValueError("not a minisign Ed25519 signature")
+ if sig[2:10] != key_id:
+ raise ValueError(
+ f"signed with key {sig[2:10][::-1].hex().upper()}, the app trusts {key_id[::-1].hex().upper()}"
+ )
+ message = hashlib.blake2b(data, digest_size=64).digest() if sig[:2] == b"ED" else data
+ trusted = lines[2][len("trusted comment: "):]
+ key = VerifyKey(pk)
+ try:
+ key.verify(message, sig[10:])
+ except BadSignatureError:
+ raise ValueError("the file doesn't match its signature")
+ try:
+ key.verify(sig[10:] + trusted.encode("utf-8"), base64.b64decode(lines[3]))
+ except BadSignatureError:
+ raise ValueError("the trusted comment doesn't match its signature")
+ if version is not None:
+ signed = [f[len("version:"):] for f in trusted.split("\t") if f.startswith("version:")]
+ if signed != [version]:
+ raise ValueError(f"trusted comment carries version {signed or 'none'}, expected {version}: {trusted}")
+ return trusted
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--pubkey", required=True, help="base64 public key, or a file holding it")
+ ap.add_argument("--file", required=True)
+ ap.add_argument("--signature", required=True)
+ ap.add_argument("--version")
+ args = ap.parse_args(argv)
+ pubkey = open(args.pubkey).read() if os.path.isfile(args.pubkey) else args.pubkey
+ with open(args.file, "rb") as f:
+ data = f.read()
+ try:
+ trusted = verify(pubkey, data, open(args.signature).read(), args.version)
+ except (ValueError, IndexError) as e:
+ print(f"minisign_verify: {e}", file=sys.stderr)
+ return 1
+ print(f"minisign_verify: good signature; trusted comment: {trusted}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/test_mac_latest_json.py b/scripts/test_mac_latest_json.py
new file mode 100644
index 00000000..c8e942ba
--- /dev/null
+++ b/scripts/test_mac_latest_json.py
@@ -0,0 +1,116 @@
+"""Tests for mac_latest_json.py: python3 -m unittest discover -s scripts -p 'test_*.py'"""
+
+import contextlib
+import io
+import json
+import os
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import mac_latest_json as m # noqa: E402
+
+CHANGELOG = """# Changelog
+
+## Unreleased
+
+### Added
+- Not released yet.
+
+## [Mac 0.1.2] - 2026-10-27
+
+### Added
+- **In-app updates.** kwant tells you when a new version is out.
+
+### Fixed
+- Something.
+
+## [Mac 0.1.1] - 2026-10-26
+
+### Added
+- Older things.
+
+## [Mac 0.1.10] - 2026-12-01
+
+- Not 0.1.1.
+"""
+
+URL = "https://github.com/alexsergivan/kwant/releases/download/mac-v0.1.2/kwant_universal.app.tar.gz"
+
+
+class ChangelogSection(unittest.TestCase):
+ def test_section_up_to_the_next_heading(self):
+ notes = m.changelog_section(CHANGELOG, "0.1.2")
+ self.assertTrue(notes.startswith("### Added\n- **In-app updates.**"))
+ self.assertTrue(notes.endswith("- Something."))
+ self.assertNotIn("Older things", notes)
+ self.assertNotIn("Not released yet", notes)
+
+ def test_exact_version_only(self):
+ self.assertEqual(m.changelog_section(CHANGELOG, "0.1.1"), "### Added\n- Older things.")
+ self.assertEqual(m.changelog_section(CHANGELOG, "0.1.10"), "- Not 0.1.1.")
+
+ def test_missing_section_fails(self):
+ with self.assertRaises(ValueError):
+ m.changelog_section(CHANGELOG, "0.1.3")
+ with self.assertRaises(ValueError):
+ m.changelog_section(CHANGELOG, "0.1")
+
+
+class LatestJson(unittest.TestCase):
+ def test_shape(self):
+ doc = m.latest_json("0.1.2", "c2lnbmF0dXJl\n", URL, "### Added\n- x", "2026-10-27T10:00:00Z")
+ self.assertEqual(doc["version"], "0.1.2")
+ self.assertEqual(doc["notes"], "### Added\n- x")
+ self.assertEqual(doc["pub_date"], "2026-10-27T10:00:00Z")
+ self.assertEqual(set(doc["platforms"]), {"darwin-aarch64", "darwin-x86_64"})
+ for p in doc["platforms"].values():
+ self.assertEqual(p, {"signature": "c2lnbmF0dXJl", "url": URL})
+
+ def test_refuses_bad_input(self):
+ for version, sig, url, notes in [
+ ("0.2.0-rc.1", "s", URL, "n"),
+ ("v0.1.2", "s", URL, "n"),
+ ("0.1", "s", URL, "n"),
+ ("0.1.2", " \n", URL, "n"),
+ ("0.1.2", "s", "http://example.com/a.tar.gz", "n"),
+ ("0.1.2", "s", URL, ""),
+ ]:
+ with self.subTest(version=version, sig=sig, url=url, notes=notes):
+ with self.assertRaises(ValueError):
+ m.latest_json(version, sig, url, notes, "2026-10-27T10:00:00Z")
+
+
+class Cli(unittest.TestCase):
+ def run_main(self, *args):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = m.main(list(args))
+ return code, out.getvalue(), err.getvalue()
+
+ def test_writes_the_feed(self):
+ with tempfile.TemporaryDirectory() as d:
+ cl, sig = os.path.join(d, "CHANGELOG.md"), os.path.join(d, "a.sig")
+ open(cl, "w").write(CHANGELOG)
+ open(sig, "w").write("c2lnbmF0dXJl")
+ code, out, err = self.run_main("--version", "0.1.2", "--signature", sig, "--url", URL, "--changelog", cl)
+ self.assertEqual(code, 0, err)
+ doc = json.loads(out)
+ self.assertEqual(doc["version"], "0.1.2")
+ self.assertRegex(doc["pub_date"], r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$")
+ self.assertIn("In-app updates", doc["notes"])
+
+ code, out, err = self.run_main("--version", "0.1.3", "--signature", sig, "--url", URL, "--changelog", cl)
+ self.assertEqual(code, 1)
+ self.assertEqual(out, "")
+ self.assertIn("no '## [Mac 0.1.3]' section", err)
+
+ def test_real_changelog_has_released_sections(self):
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ text = open(os.path.join(root, "CHANGELOG.md"), encoding="utf-8").read()
+ self.assertTrue(m.changelog_section(text, "0.1.1"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/app_update.rs b/src/app_update.rs
new file mode 100644
index 00000000..b52e71d7
--- /dev/null
+++ b/src/app_update.rs
@@ -0,0 +1,415 @@
+//! In-app updates for the Mac app. The Mac shell (apps/mac) links this crate, runs the server in its
+//! own process and registers an [`Updater`] on the shared [`UpdateHub`]; the server's
+//! `/api/app/update` routes read and drive the hub. Anywhere else (`kwnt serve`, Docker, a VPS)
+//! nothing registers, so the routes report `supported: false` and the web app shows no update UI.
+//!
+//! The hub owns the state machine: idle → checking → available → downloading → ready, with error
+//! from checking or downloading. The updater only does the work (fetch, verify, install, relaunch)
+//! and reports back through [`UpdateHub::found`], [`UpdateHub::progress`], [`UpdateHub::ready`] and
+//! [`UpdateHub::failed`].
+
+use serde::Serialize;
+use std::sync::{Arc, Mutex, OnceLock};
+use tokio::sync::watch;
+
+/// What the updater is doing.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum State {
+ Idle,
+ Checking,
+ Available,
+ Downloading,
+ /// Installed; the app is relaunching on the new version.
+ Ready,
+ Error,
+}
+
+/// A newer release than the running app.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct Available {
+ pub version: String,
+ /// That version's CHANGELOG section (markdown).
+ pub notes: String,
+ /// RFC 3339 publish date, when the release says.
+ pub date: Option<String>,
+ /// The release page, for "What's new" and "Download manually".
+ pub url: String,
+}
+
+/// `GET /api/app/update`.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Status {
+ /// Whether this process is the Mac app and can update itself.
+ pub supported: bool,
+ /// The running app's version (the kwnt crate's version off-Mac).
+ pub current: String,
+ pub state: State,
+ pub available: Option<Available>,
+ /// Download progress 0–1, while downloading and the size is known.
+ pub progress: Option<f64>,
+ pub error: Option<String>,
+}
+
+/// The Mac shell's side: does the work, reports back through the hub. Both calls return at once.
+pub trait Updater: Send + Sync + 'static {
+ /// Asks the release feed for a newer version; ends in [`UpdateHub::found`] or
+ /// [`UpdateHub::failed`].
+ fn check(&self);
+ /// Downloads `version`, verifies its signature, swaps the app and relaunches; reports
+ /// [`UpdateHub::progress`], then [`UpdateHub::ready`] or [`UpdateHub::failed`]. On failure the
+ /// running app is untouched.
+ fn install(&self, version: &str);
+}
+
+/// Why a check or install can't start now.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Refused {
+ /// Not the Mac app.
+ Unsupported,
+ /// Already checking, downloading or relaunching.
+ Busy,
+ /// Install without a newer version found.
+ NothingToInstall,
+}
+
+impl Refused {
+ pub fn message(&self) -> &'static str {
+ match self {
+ Refused::Unsupported => "updates are only available in the kwant bots Mac app",
+ Refused::Busy => "an update check or install is already running",
+ Refused::NothingToInstall => "no newer version is available",
+ }
+ }
+}
+
+pub struct UpdateHub {
+ updater: Mutex<Option<Arc<dyn Updater>>>,
+ status: watch::Sender<Status>,
+}
+
+impl Default for UpdateHub {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl UpdateHub {
+ pub fn new() -> Self {
+ let (status, _) = watch::channel(Status {
+ supported: false,
+ current: env!("CARGO_PKG_VERSION").to_string(),
+ state: State::Idle,
+ available: None,
+ progress: None,
+ error: None,
+ });
+ Self { updater: Mutex::new(None), status }
+ }
+
+ /// The hub of this process: the Mac shell registers on it, the server reads it.
+ pub fn shared() -> Arc<UpdateHub> {
+ static SHARED: OnceLock<Arc<UpdateHub>> = OnceLock::new();
+ SHARED.get_or_init(|| Arc::new(UpdateHub::new())).clone()
+ }
+
+ /// Makes updates supported, running `current` (the app's version, not the crate's).
+ pub fn register(&self, current: &str, updater: Arc<dyn Updater>) {
+ *self.updater.lock().unwrap() = Some(updater);
+ self.status.send_modify(|s| {
+ s.supported = true;
+ s.current = current.to_string();
+ });
+ }
+
+ pub fn status(&self) -> Status {
+ self.status.borrow().clone()
+ }
+
+ /// Follows every change, for the "new version" notification.
+ pub fn subscribe(&self) -> watch::Receiver<Status> {
+ self.status.subscribe()
+ }
+
+ fn updater(&self) -> Option<Arc<dyn Updater>> {
+ self.updater.lock().unwrap().clone()
+ }
+
+ /// Starts a check, unless one is running or an install is under way.
+ pub fn check(&self) -> Result<Status, Refused> {
+ let updater = self.updater().ok_or(Refused::Unsupported)?;
+ let mut refused = None;
+ self.status.send_if_modified(|s| match s.state {
+ State::Checking | State::Downloading | State::Ready => {
+ refused = Some(Refused::Busy);
+ false
+ }
+ _ => {
+ s.state = State::Checking;
+ s.error = None;
+ true
+ }
+ });
+ if let Some(r) = refused {
+ return Err(r);
+ }
+ updater.check();
+ Ok(self.status())
+ }
+
+ /// Starts installing the version found, also after a failed attempt.
+ pub fn install(&self) -> Result<Status, Refused> {
+ let updater = self.updater().ok_or(Refused::Unsupported)?;
+ let mut result = Err(Refused::NothingToInstall);
+ self.status.send_if_modified(|s| match (s.state, &s.available) {
+ (State::Checking | State::Downloading | State::Ready, _) => {
+ result = Err(Refused::Busy);
+ false
+ }
+ (_, Some(a)) => {
+ result = Ok(a.version.clone());
+ s.state = State::Downloading;
+ s.progress = Some(0.0);
+ s.error = None;
+ true
+ }
+ (_, None) => false,
+ });
+ let version = result?;
+ updater.install(&version);
+ Ok(self.status())
+ }
+
+ /// The check's answer. A release that isn't newer, or is a prerelease, counts as none.
+ pub fn found(&self, release: Option<Available>) {
+ self.status.send_modify(|s| {
+ let release = release.filter(|r| is_newer(&r.version, &s.current));
+ s.state = if release.is_some() { State::Available } else { State::Idle };
+ s.available = release;
+ s.progress = None;
+ s.error = None;
+ });
+ }
+
+ /// Download progress, 0–1 (`None`: size unknown). Called per chunk; followers hear of it in
+ /// steps of 1%.
+ pub fn progress(&self, fraction: Option<f64>) {
+ let next = fraction.map(|f| f.clamp(0.0, 1.0));
+ self.status.send_if_modified(|s| {
+ let moved = match (s.progress, next) {
+ (Some(was), Some(now)) => (now - was).abs() >= 0.01 || (now == 1.0 && was < 1.0),
+ (was, now) => was != now,
+ };
+ if s.state != State::Downloading || !moved {
+ return false;
+ }
+ s.progress = next;
+ true
+ });
+ }
+
+ /// Installed; the app relaunches next.
+ pub fn ready(&self) {
+ self.status.send_modify(|s| {
+ s.state = State::Ready;
+ s.progress = Some(1.0);
+ s.error = None;
+ });
+ }
+
+ /// A check or install failed. A version already found stays, so the person can retry or
+ /// download it by hand.
+ pub fn failed(&self, error: &str) {
+ let error: String = error.chars().take(300).collect();
+ self.status.send_modify(|s| {
+ s.state = State::Error;
+ s.progress = None;
+ s.error = Some(error);
+ });
+ }
+}
+
+/// `x.y.z` as numbers; `None` for anything else, including prereleases (`0.2.0-rc.1`).
+fn release_parts(version: &str) -> Option<[u64; 3]> {
+ let mut parts = version.trim().trim_start_matches('v').split('.');
+ let mut out = [0u64; 3];
+ for slot in &mut out {
+ *slot = parts.next()?.parse().ok()?;
+ }
+ parts.next().is_none().then_some(out)
+}
+
+/// Whether `candidate` is a release (not a prerelease) newer than `current`.
+pub fn is_newer(candidate: &str, current: &str) -> bool {
+ let Some(candidate) = release_parts(candidate) else {
+ return false;
+ };
+ // A running prerelease (0.2.0-rc.1) is older than its release 0.2.0
+ let current = current.trim().trim_start_matches('v');
+ match release_parts(current) {
+ Some(current) => candidate > current,
+ None => release_parts(current.split('-').next().unwrap_or("")).is_some_and(|base| candidate >= base),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[derive(Default)]
+ struct Fake {
+ calls: Mutex<Vec<String>>,
+ }
+
+ impl Updater for Fake {
+ fn check(&self) {
+ self.calls.lock().unwrap().push("check".into());
+ }
+ fn install(&self, version: &str) {
+ self.calls.lock().unwrap().push(format!("install {version}"));
+ }
+ }
+
+ fn release(version: &str) -> Available {
+ Available {
+ version: version.into(),
+ notes: "### Added\n- things".into(),
+ date: Some("2026-10-27T10:00:00Z".into()),
+ url: format!("https://github.com/alexsergivan/kwant/releases/tag/mac-v{version}"),
+ }
+ }
+
+ fn hub() -> (UpdateHub, Arc<Fake>) {
+ let hub = UpdateHub::new();
+ let fake = Arc::new(Fake::default());
+ hub.register("0.1.1", fake.clone());
+ (hub, fake)
+ }
+
+ #[test]
+ fn versions() {
+ assert!(is_newer("0.1.2", "0.1.1"));
+ assert!(is_newer("0.2.0", "0.1.9"));
+ assert!(is_newer("1.0.0", "0.10.10"));
+ assert!(is_newer("0.10.0", "0.9.0"), "numeric, not string, order");
+ assert!(is_newer("v0.1.2", "0.1.1"));
+ assert!(!is_newer("0.1.1", "0.1.1"));
+ assert!(!is_newer("0.1.0", "0.1.1"));
+ assert!(!is_newer("0.2.0-rc.1", "0.1.1"), "prereleases are never offered");
+ assert!(!is_newer("0.2", "0.1.1"));
+ assert!(!is_newer("0.2.0.1", "0.1.1"));
+ assert!(!is_newer("latest", "0.1.1"));
+ assert!(is_newer("0.2.0", "0.2.0-rc.1"), "a release replaces its own rc");
+ assert!(!is_newer("0.1.9", "0.2.0-rc.1"));
+ }
+
+ #[test]
+ fn unsupported_until_registered() {
+ let hub = UpdateHub::new();
+ let s = hub.status();
+ assert!(!s.supported);
+ assert_eq!(s.current, env!("CARGO_PKG_VERSION"));
+ assert_eq!(s.state, State::Idle);
+ assert_eq!(hub.check(), Err(Refused::Unsupported));
+ assert_eq!(hub.install(), Err(Refused::Unsupported));
+ }
+
+ #[test]
+ fn check_finds_a_newer_version_then_installs() {
+ let (hub, fake) = hub();
+ assert!(hub.status().supported);
+ assert_eq!(hub.status().current, "0.1.1");
+ assert_eq!(hub.install(), Err(Refused::NothingToInstall));
+
+ assert_eq!(hub.check().unwrap().state, State::Checking);
+ assert_eq!(hub.check(), Err(Refused::Busy), "one check at a time");
+ hub.found(Some(release("0.1.2")));
+ let s = hub.status();
+ assert_eq!(s.state, State::Available);
+ assert_eq!(s.available.as_ref().unwrap().version, "0.1.2");
+
+ let s = hub.install().unwrap();
+ assert_eq!(s.state, State::Downloading);
+ assert_eq!(s.progress, Some(0.0));
+ assert_eq!(hub.install(), Err(Refused::Busy));
+ assert_eq!(hub.check(), Err(Refused::Busy), "no check while downloading");
+ hub.progress(Some(0.5));
+ assert_eq!(hub.status().progress, Some(0.5));
+ let mut rx = hub.subscribe();
+ rx.borrow_and_update();
+ hub.progress(Some(0.503));
+ assert!(!rx.has_changed().unwrap(), "under 1%: no wake-up");
+ assert_eq!(hub.status().progress, Some(0.5));
+ hub.progress(Some(7.0));
+ assert_eq!(hub.status().progress, Some(1.0), "clamped");
+ hub.ready();
+ assert_eq!(hub.status().state, State::Ready);
+ assert_eq!(hub.check(), Err(Refused::Busy), "relaunching");
+
+ assert_eq!(*fake.calls.lock().unwrap(), vec!["check", "install 0.1.2"]);
+ }
+
+ #[test]
+ fn older_same_or_prerelease_counts_as_none() {
+ let (hub, _) = hub();
+ for v in ["0.1.1", "0.1.0", "0.2.0-rc.1"] {
+ hub.check().unwrap();
+ hub.found(Some(release(v)));
+ let s = hub.status();
+ assert_eq!(s.state, State::Idle, "{v}");
+ assert_eq!(s.available, None, "{v}");
+ }
+ hub.check().unwrap();
+ hub.found(None);
+ assert_eq!(hub.status().state, State::Idle);
+ }
+
+ #[test]
+ fn failed_install_keeps_the_version_and_can_retry() {
+ let (hub, fake) = hub();
+ hub.check().unwrap();
+ hub.found(Some(release("0.2.0")));
+ hub.install().unwrap();
+ hub.failed("signature didn't match");
+ let s = hub.status();
+ assert_eq!(s.state, State::Error);
+ assert_eq!(s.error.as_deref(), Some("signature didn't match"));
+ assert_eq!(s.available.as_ref().unwrap().version, "0.2.0", "manual download link stays");
+ assert_eq!(s.progress, None);
+ hub.progress(Some(0.3));
+ assert_eq!(hub.status().progress, None, "progress only while downloading");
+
+ assert_eq!(hub.install().unwrap().state, State::Downloading);
+ assert_eq!(hub.status().error, None);
+ assert_eq!(fake.calls.lock().unwrap().len(), 3);
+ }
+
+ #[test]
+ fn failed_check_without_a_version() {
+ let (hub, _) = hub();
+ hub.check().unwrap();
+ hub.failed(&"x".repeat(1000));
+ let s = hub.status();
+ assert_eq!(s.state, State::Error);
+ assert_eq!(s.error.unwrap().len(), 300, "clipped");
+ assert_eq!(hub.install(), Err(Refused::NothingToInstall));
+ assert_eq!(hub.check().unwrap().state, State::Checking, "a new check clears the error");
+ assert_eq!(hub.status().error, None);
+ }
+
+ #[test]
+ fn status_json_shape() {
+ let (hub, _) = hub();
+ hub.check().unwrap();
+ hub.found(Some(release("0.1.2")));
+ let v = serde_json::to_value(hub.status()).unwrap();
+ assert_eq!(v["supported"], true);
+ assert_eq!(v["current"], "0.1.1");
+ assert_eq!(v["state"], "available");
+ assert_eq!(v["available"]["version"], "0.1.2");
+ assert_eq!(v["available"]["date"], "2026-10-27T10:00:00Z");
+ assert!(v["available"]["url"].as_str().unwrap().ends_with("/mac-v0.1.2"));
+ assert!(v["progress"].is_null());
+ assert!(v["error"].is_null());
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index cd8f0591..3bc4745d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod app_update;
pub mod broker;
pub mod config;
pub mod db;
diff --git a/src/serve.rs b/src/serve.rs
index d19fdbeb..9f619865 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -55,6 +55,7 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
crate::server::scheduler::spawn_background(state.clone(), cancel.clone());
crate::server::engine_routes::spawn_startup_check(state.clone());
crate::server::parallel_routes::spawn_startup_sweep(state.clone());
+ crate::server::app_update_routes::spawn_notifier(state.clone());
let api_token = state.api_token.clone();
let app = create_router(state);
diff --git a/src/server/app_update_routes.rs b/src/server/app_update_routes.rs
new file mode 100644
index 00000000..34354dd5
--- /dev/null
+++ b/src/server/app_update_routes.rs
@@ -0,0 +1,80 @@
+//! `/api/app/update`: the Mac app's in-app update (see [`crate::app_update`]). GET is open to
+//! bots like other status reads; check and install are person-only (`auth::person_only`).
+
+use super::continuity::{notify, Notification};
+use super::AppState;
+use crate::app_update::{Refused, State, Status};
+use axum::extract::State as AxState;
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::Json;
+
+/// The setting that remembers which version the person was already told about.
+pub const NOTIFIED_SETTING: &str = "app_update_notified_version";
+
+/// `GET /api/app/update`: `{supported, current, state, available, progress, error}`.
+pub async fn get_status(AxState(state): AxState<AppState>) -> Json<Status> {
+ Json(state.app_update.status())
+}
+
+/// `POST /api/app/update/check`: 202 with the status; 409 off the Mac app or while busy.
+pub async fn check(AxState(state): AxState<AppState>) -> Response {
+ reply(state.app_update.check())
+}
+
+/// `POST /api/app/update/install`: 202 with the status; 409 off the Mac app, while busy, or with
+/// no newer version found. The app relaunches by itself once the new version is in place.
+pub async fn install(AxState(state): AxState<AppState>) -> Response {
+ reply(state.app_update.install())
+}
+
+fn reply(result: Result<Status, Refused>) -> Response {
+ match result {
+ Ok(status) => (StatusCode::ACCEPTED, Json(status)).into_response(),
+ Err(r) => (StatusCode::CONFLICT, Json(serde_json::json!({ "error": r.message() }))).into_response(),
+ }
+}
+
+/// Tells the person once per version that an update is out, through the usual notifications.
+/// Runs for the life of the server; does nothing off the Mac app, where the state never changes.
+pub fn spawn_notifier(state: AppState) {
+ let mut rx = state.app_update.subscribe();
+ tokio::spawn(async move {
+ loop {
+ let available = {
+ let s = rx.borrow_and_update();
+ (s.state == State::Available).then(|| s.available.clone()).flatten()
+ };
+ if let Some(a) = available {
+ notify_once(&state, &a.version).await;
+ }
+ if rx.changed().await.is_err() {
+ return;
+ }
+ }
+ });
+}
+
+/// Sends the "new version" notification unless this version was already announced.
+pub async fn notify_once(state: &AppState, version: &str) -> bool {
+ let told = state.db.get_setting(NOTIFIED_SETTING).await.ok().flatten();
+ if told.as_deref() == Some(version) {
+ return false;
+ }
+ if state.db.set_setting(NOTIFIED_SETTING, version).await.is_err() {
+ return false;
+ }
+ notify(
+ state,
+ Notification {
+ kind: "app_update",
+ kwant_id: String::new(),
+ kwant_name: "kwant".into(),
+ channel_id: None,
+ title: format!("kwant bots {version} is ready"),
+ body: "Open kwant bots to update and restart.".into(),
+ },
+ )
+ .await;
+ true
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index b2468736..73786ee7 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -338,6 +338,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "settings", ..] => *method != Method::GET && *method != Method::HEAD,
// Carrying on a chain that went over its token budget is the person's call
["", "api", "chains", _, "continue"] => *method == Method::POST,
+ // The Mac app's update: check and install (which swaps and relaunches the app) are the
+ // person's; the status stays readable
+ ["", "api", "app", "update", ..] => *method != Method::GET && *method != Method::HEAD,
["", "api", "approvals", _, "resolve"] => *method == Method::POST,
["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,
["", "api", "kwants" | "teams", _] => *method == Method::DELETE,
@@ -859,6 +862,11 @@ mod tests {
assert!(person_only(&put, "/api/settings/computer/"));
assert!(person_only(&put, "/api/settings/computer/window"));
assert!(!person_only(&get, "/api/settings/computer"));
+ assert!(person_only(&post, "/api/app/update/check"));
+ assert!(person_only(&post, "/api/app/update/install"));
+ assert!(person_only(&post, "/api/app/update/install/"));
+ assert!(!person_only(&get, "/api/app/update"));
+ assert!(!person_only(&Method::HEAD, "/api/app/update"));
assert!(!person_only(&get, "/api/approvals"));
assert!(!person_only(&get, "/api/sandbox/t1/status"));
assert!(!person_only(&get, "/api/kwants"));
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index c8979e84..3b5f5564 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;
/// Longest notification body.
pub const NOTIFY_BODY_CHARS: usize = 200;
const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);
-pub const NOTIFY_KINDS: [&str; 9] = [
+pub const NOTIFY_KINDS: [&str; 10] = [
"turn_finished",
"approval_needed",
"routine_failed",
@@ -44,6 +44,7 @@ pub const NOTIFY_KINDS: [&str; 9] = [
"question_asked",
"loose_ends",
"human_step",
+ "app_update",
];
const MASK: &str = "••••••••";
diff --git a/src/server/mod.rs b/src/server/mod.rs
index edfaa4b2..ebfe4559 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -41,6 +41,7 @@ pub mod connections;
pub mod setup_routes;
pub mod push;
pub mod waiting;
+pub mod app_update_routes;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -107,6 +108,8 @@ pub struct AppState {
pub setup: Arc<setup_routes::SetupJobs>,
/// Web Push to the person's installed app: the VAPID key and subscriptions.
pub push: Arc<push::Push>,
+ /// The Mac app's in-app update; unsupported (and never changing) anywhere else.
+ pub app_update: Arc<crate::app_update::UpdateHub>,
}
impl AppState {
@@ -154,6 +157,7 @@ impl AppState {
documents: Default::default(),
setup: Default::default(),
push: Arc::new(push::Push::load(&config_data_dir)),
+ app_update: crate::app_update::UpdateHub::shared(),
}
}
@@ -182,6 +186,9 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/push/key", get(push::key))
.route("/api/push/subscribe", post(push::subscribe))
.route("/api/push/unsubscribe", post(push::unsubscribe))
+ .route("/api/app/update", get(app_update_routes::get_status))
+ .route("/api/app/update/check", post(app_update_routes::check))
+ .route("/api/app/update/install", post(app_update_routes::install))
.route("/api/profiles", get(profile_routes::list).post(profile_routes::create))
.route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove))
.route("/api/profiles/:id/key", put(profile_routes::set_key).delete(profile_routes::delete_key))
diff --git a/tests/app_update_test.rs b/tests/app_update_test.rs
new file mode 100644
index 00000000..e4ad3a6e
--- /dev/null
+++ b/tests/app_update_test.rs
@@ -0,0 +1,242 @@
+//! The Mac app's in-app update routes: `/api/app/update` reads the state for anyone, check and
+//! install are the person's, and off the Mac app (nothing registered) updates are unsupported.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ app_update::{Available, State, UpdateHub, Updater},
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ drivers::RuntimeEvent,
+ router::LayaRouter,
+ server::{
+ app_update_routes,
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+#[derive(Default)]
+struct FakeUpdater {
+ calls: Mutex<Vec<String>>,
+}
+
+impl Updater for FakeUpdater {
+ fn check(&self) {
+ self.calls.lock().unwrap().push("check".into());
+ }
+ fn install(&self, version: &str) {
+ self.calls.lock().unwrap().push(format!("install {version}"));
+ }
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ _tmp: TempDir,
+}
+
+/// A server with its own hub (not the process-wide one), with or without the Mac updater.
+async fn setup(updater: Option<Arc<FakeUpdater>>) -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let hub = Arc::new(UpdateHub::new());
+ if let Some(u) = updater {
+ hub.register("0.1.1", u);
+ }
+ state.app_update = hub;
+ Env { app: create_router(state.clone()), state, _tmp: tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri);
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let resp = app.clone().oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+/// A bot's turn token in #general.
+async fn bot_token(e: &Env) -> String {
+ let space = SpaceId::default_space();
+ let bot = e.state.db.list_kwants(&space).await.unwrap().remove(0);
+ let general = e.state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(general.id.clone()), ..Default::default() }),
+ turn_id: Some("t-update".into()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(&e.state, &bot, Some("t-update".into()), None, Some(scope)).await.unwrap().1
+}
+
+fn release(version: &str) -> Available {
+ Available {
+ version: version.into(),
+ notes: "### Added\n- In-app updates".into(),
+ date: Some("2026-10-27T10:00:00Z".into()),
+ url: format!("https://github.com/alexsergivan/kwant/releases/tag/mac-v{version}"),
+ }
+}
+
+#[tokio::test]
+async fn unsupported_off_the_mac_app() {
+ let e = setup(None).await;
+ let (status, v) = call(&e.app, "GET", "/api/app/update", None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["supported"], false);
+ assert_eq!(v["current"], env!("CARGO_PKG_VERSION"));
+ assert_eq!(v["state"], "idle");
+ assert!(v["available"].is_null());
+ assert!(v["progress"].is_null());
+ assert!(v["error"].is_null());
+ for uri in ["/api/app/update/check", "/api/app/update/install"] {
+ let (status, v) = call(&e.app, "POST", uri, None).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{uri}: {v}");
+ assert!(v["error"].as_str().unwrap().contains("Mac app"), "{v}");
+ }
+}
+
+#[tokio::test]
+async fn bots_read_but_never_check_or_install() {
+ let fake = Arc::new(FakeUpdater::default());
+ let e = setup(Some(fake.clone())).await;
+ e.state.app_update.check().unwrap();
+ e.state.app_update.found(Some(release("0.1.2")));
+ let token = bot_token(&e).await;
+
+ let (status, v) = call(&e.app, "GET", "/api/app/update", Some(&token)).await;
+ assert_eq!(status, StatusCode::OK, "a bot reads the state: {v}");
+ assert_eq!(v["state"], "available");
+ for uri in ["/api/app/update/check", "/api/app/update/install"] {
+ let (status, v) = call(&e.app, "POST", uri, Some(&token)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri} with a bot's turn token: {v}");
+ }
+ assert_eq!(*fake.calls.lock().unwrap(), vec!["check"], "only the direct check above ran");
+ assert_eq!(e.state.app_update.status().state, State::Available, "nothing changed");
+
+ // From another machine with no token: 401
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/app/update/install")
+ .header("host", "kwnt.example.com")
+ .body(Body::empty())
+ .unwrap();
+ assert_eq!(e.app.clone().oneshot(req).await.unwrap().status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn person_checks_and_installs() {
+ let fake = Arc::new(FakeUpdater::default());
+ let e = setup(Some(fake.clone())).await;
+ let person = e.state.api_token.reveal().to_string();
+
+ let (status, v) = call(&e.app, "POST", "/api/app/update/install", Some(&person)).await;
+ assert_eq!(status, StatusCode::CONFLICT, "nothing found yet: {v}");
+
+ let (status, v) = call(&e.app, "POST", "/api/app/update/check", Some(&person)).await;
+ assert_eq!(status, StatusCode::ACCEPTED, "{v}");
+ assert_eq!(v["state"], "checking");
+ assert_eq!(v["supported"], true);
+ assert_eq!(v["current"], "0.1.1");
+ let (status, _) = call(&e.app, "POST", "/api/app/update/check", Some(&person)).await;
+ assert_eq!(status, StatusCode::CONFLICT, "one check at a time");
+
+ e.state.app_update.found(Some(release("0.2.0")));
+ let (_, v) = call(&e.app, "GET", "/api/app/update", None).await;
+ assert_eq!(v["state"], "available");
+ assert_eq!(v["available"]["version"], "0.2.0");
+ assert_eq!(v["available"]["notes"], "### Added\n- In-app updates");
+
+ // The person's cookie from another machine works too
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/app/update/install")
+ .header("host", "kwnt.example.com")
+ .header("cookie", format!("kwnt_token={person}"))
+ .body(Body::empty())
+ .unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::ACCEPTED);
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ assert_eq!(v["state"], "downloading");
+ assert_eq!(v["progress"], json!(0.0));
+ assert_eq!(*fake.calls.lock().unwrap(), vec!["check", "install 0.2.0"]);
+
+ // A failed download leaves the old app running and the version on offer
+ e.state.app_update.failed("signature check failed");
+ let (_, v) = call(&e.app, "GET", "/api/app/update", None).await;
+ assert_eq!(v["state"], "error");
+ assert_eq!(v["error"], "signature check failed");
+ assert_eq!(v["available"]["version"], "0.2.0");
+}
+
+#[tokio::test]
+async fn notifies_once_per_version() {
+ let e = setup(Some(Arc::new(FakeUpdater::default()))).await;
+ let mut events = e.state.event_sender.subscribe();
+ app_update_routes::spawn_notifier(e.state.clone());
+
+ // Everything sent within `wait` (the notifier writes a setting first, which is slow under load)
+ async fn notifications(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>, wait: Duration) -> Vec<(String, String, String)> {
+ let mut out = Vec::new();
+ let deadline = tokio::time::Instant::now() + wait;
+ while let Ok(Ok(ev)) = tokio::time::timeout_at(deadline, events.recv()).await {
+ if let RuntimeEvent::Notify { kind, title, body, .. } = ev {
+ out.push((kind, title, body));
+ break;
+ }
+ }
+ out
+ }
+ let hub = e.state.app_update.clone();
+ let (quiet, wait) = (Duration::from_millis(500), Duration::from_secs(10));
+
+ hub.check().unwrap();
+ hub.found(None);
+ assert!(notifications(&mut events, quiet).await.is_empty(), "nothing new, nothing sent");
+
+ hub.check().unwrap();
+ hub.found(Some(release("0.1.2")));
+ let sent = notifications(&mut events, wait).await;
+ assert_eq!(sent.len(), 1, "{sent:?}");
+ assert_eq!(sent[0].0, "app_update");
+ assert_eq!(sent[0].1, "kwant bots 0.1.2 is ready");
+ assert_eq!(sent[0].2, "Open kwant bots to update and restart.");
+
+ // The 6-hourly check finds the same version again: no second notification
+ hub.check().unwrap();
+ hub.found(Some(release("0.1.2")));
+ assert!(notifications(&mut events, quiet).await.is_empty());
+ assert!(!app_update_routes::notify_once(&e.state, "0.1.2").await, "remembered in settings");
+
+ hub.check().unwrap();
+ hub.found(Some(release("0.1.3")));
+ assert_eq!(notifications(&mut events, wait).await.len(), 1, "a newer version is announced");
+ assert_eq!(
+ e.state.db.get_setting(app_update_routes::NOTIFIED_SETTING).await.unwrap().as_deref(),
+ Some("0.1.3")
+ );
+}
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 3cab995a..2572ea32 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1564,7 +1564,7 @@ async fn webhook_setting_is_https_only_and_masked() {
assert_eq!(s["notify_webhook_url"], "");
assert_eq!(
s["notify_on"],
- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step"])
+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update"])
);
let (status, _) = req(