Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): add signed app and host updates
leepokaia0a05cd32770
diff --git a/.github/workflows/host.yml b/.github/workflows/host.ymlindex f0cc7dc8..21161ebe 100644--- a/.github/workflows/host.yml+++ b/.github/workflows/host.yml@@ -3,10 +3,10 @@ name: codync-hoston:push:branches: [main, v2]- paths: ["host/**", "apps/linux/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/host.yml"]+ paths: ["host/**", "apps/linux/**", "packaging/updates/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/host.yml"]tags: ["v*"] # one version tag ships the Mac app, the host and the Linux apppull_request:- paths: ["host/**", "apps/linux/**", "docs/reference/fixtures/remote-relay-vectors.json"]+ paths: ["host/**", "apps/linux/**", "packaging/updates/**", "docs/reference/fixtures/remote-relay-vectors.json"]jobs:test:@@ -97,7 +97,10 @@ jobs:# Vendored C (dbus) would call libgcc's outline atomics, which a static musl link lacks.env:CFLAGS_aarch64_unknown_linux_musl: -mno-outline-atomics- run: cargo build --release --target ${{ matrix.target }}+ run: |+ VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["package"]["version"])')+ test "v$VERSION" = "$GITHUB_REF_NAME" || { echo 'Host version must match release tag'; exit 1; }+ cargo build --release --target ${{ matrix.target }}- name: Packagerun: |NAME=codync-host-${{ matrix.name }}@@ -106,11 +109,22 @@ jobs:cp LICENSE $NAME/tar czf $NAME.tar.gz $NAMEshasum -a 256 $NAME.tar.gz > $NAME.tar.gz.sha256+ - name: Sign host update manifest+ env:+ HOST_UPDATE_SIGNING_KEY: ${{ secrets.HOST_UPDATE_SIGNING_KEY }}+ run: |+ python3 -m venv "$RUNNER_TEMP/update-signing"+ "$RUNNER_TEMP/update-signing/bin/pip" install 'cryptography>=44,<47'+ "$RUNNER_TEMP/update-signing/bin/python" packaging/updates/sign-host-release.py \+ "codync-host-${{ matrix.name }}.tar.gz" \+ --version "$GITHUB_REF_NAME" --platform "${{ matrix.name }}"- uses: softprops/action-gh-release@v2with:files: |codync-host-*.tar.gzcodync-host-*.tar.gz.sha256+ codync-host-*.update.json+ codync-host-*.update.json.sighomebrew:# Keeps `brew install leepokai/codync/codync-host` (Linux, headless Macs) in step with releases.diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.ymlindex 0fe931b1..a20ee938 100644--- a/.github/workflows/release-macos.yml+++ b/.github/workflows/release-macos.yml@@ -68,20 +68,20 @@ jobs:CODE_SIGNING_REQUIRED=NO \CODE_SIGNING_ALLOWED=NO \MARKETING_VERSION=${{ env.VERSION }} \- CURRENT_PROJECT_VERSION=${{ github.run_number }}+ CURRENT_PROJECT_VERSION=${{ env.VERSION }}- name: Sign app with Developer IDrun: |APP_PATH=$(find build/derived -name "Codync.app" -path "*/Release/*" | head -1)# Sign-in and the cloud relay read their settings from here.test -f "$APP_PATH/Contents/Resources/AccountConfig.plist" || { echo "AccountConfig.plist missing"; exit 1; }- sign() { codesign --force --options runtime --timestamp --sign "Developer ID Application" "$1"; }- # Inside out: frameworks, the Screen helper, the bundled Rust host, then the app itself.- SCREEN="$APP_PATH/Contents/Library/LoginItems/CodyncScreen.app"- find "$APP_PATH" -name "*.framework" -prune -print0 | while IFS= read -r -d '' f; do sign "$f"; done- sign "$SCREEN"+ sign() { codesign --force --options runtime --timestamp --preserve-metadata=entitlements --sign "Developer ID Application" "$1"; }+ # Sparkle's XPC services and updater must share our signing identity.+ # Preserve the framework helpers' sandbox entitlements while resigning.+ find "$APP_PATH" -type f -name Autoupdate -print0 | while IFS= read -r -d '' f; do sign "$f"; donesign "$APP_PATH/Contents/MacOS/codync-host"- sign "$APP_PATH"+ find "$APP_PATH" -depth \( -name '*.xpc' -o -name '*.app' -o -name '*.framework' \) -print0 |+ while IFS= read -r -d '' f; do sign "$f"; donecodesign --verify --deep --strict --verbose=2 "$APP_PATH"cp -R "$APP_PATH" "$RUNNER_TEMP/Codync.app"@@ -113,12 +113,33 @@ jobs:-ov -format UDZO build/codync-macos.dmgspctl --assess --type execute -v "$RUNNER_TEMP/Codync.app"+ - name: Generate signed Sparkle appcast+ env:+ SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}+ run: |+ test -n "$SPARKLE_PRIVATE_KEY" || { echo 'SPARKLE_PRIVATE_KEY is required'; exit 1; }+ SPARKLE_BIN=build/derived/SourcePackages/artifacts/sparkle/Sparkle/bin+ test -x "$SPARKLE_BIN/generate_appcast"+ mkdir -p build/updates+ cp build/codync-macos.dmg build/updates/+ printf '%s' "$SPARKLE_PRIVATE_KEY" | "$SPARKLE_BIN/generate_appcast" \+ --ed-key-file - --maximum-deltas 0 \+ --download-url-prefix "https://github.com/leepokai/Codync/releases/download/v${VERSION}/" \+ --link https://www.codync.dev/ \+ -o build/appcast.xml build/updates+ python3 -m venv "$RUNNER_TEMP/update-verification"+ "$RUNNER_TEMP/update-verification/bin/pip" install 'cryptography>=44,<47'+ "$RUNNER_TEMP/update-verification/bin/python" packaging/updates/verify-appcast.py \+ build/appcast.xml "$RUNNER_TEMP/Codync.app" build/codync-macos.dmg+- name: Keep the dry run's DMGif: "!startsWith(github.ref, 'refs/tags/')"uses: actions/upload-artifact@v4with:name: codync-macos- path: build/codync-macos.dmg+ path: |+ build/codync-macos.dmg+ build/appcast.xml- name: Create GitHub Releaseif: startsWith(github.ref, 'refs/tags/')@@ -126,10 +147,10 @@ jobs:# The host workflow may have created this release already (same tag).(cd build && shasum -a 256 codync-macos.dmg > codync-macos.dmg.sha256)gh release create ${{ github.ref_name }} \- build/codync-macos.dmg build/codync-macos.dmg.sha256 \+ build/codync-macos.dmg build/codync-macos.dmg.sha256 build/appcast.xml \--title "Codync ${{ github.ref_name }}" \--generate-notes \- || gh release upload ${{ github.ref_name }} build/codync-macos.dmg build/codync-macos.dmg.sha256 --clobber+ || gh release upload ${{ github.ref_name }} build/codync-macos.dmg build/codync-macos.dmg.sha256 build/appcast.xml --clobberenv:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}@@ -147,6 +168,7 @@ jobs:name "Codync"desc "Message your coding agents as bots from your phone, desktop or terminal"homepage "https://www.codync.dev/"+ auto_updates truedepends_on macos: :sonomadiff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxprojindex 88140806..130f9fee 100644--- a/apps/Codync.xcodeproj/project.pbxproj+++ b/apps/Codync.xcodeproj/project.pbxproj@@ -14,7 +14,7 @@17DD96A91B1EC2AE699F4A2F /* ViewingBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0E04490F5C56FD070539E6 /* ViewingBadge.swift */; };2244021EF712DF568374AB04 /* HostController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14B7967A8F027FF28EAEA893 /* HostController.swift */; };2299EC1A2CE18A03C8AF9A0A /* ComputerStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 772D2E6B5C5157077E504B35 /* ComputerStatus.swift */; };- 24DF3CB466CC877FCB8BAED6 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 80868F96B9905FF52DCDFAE2 /* CodyncKit */; };+ 24DF3CB466CC877FCB8BAED6 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = 7D524C19E9D41C0CF635A619 /* ClerkKit */; };25667EBFCCC64B96FDCE95A9 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 59F5D19A417A7A50596902FA /* CodyncKit */; };2CC074683AE086D6C77CC1E8 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B274A0195CB3B2409EA4C194 /* WidgetKit.framework */; };2CDF3DF16A13DAF83CA42168 /* CodyncWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAB9BDB52C3A9F7B2568A750 /* CodyncWidgets.swift */; };@@ -44,10 +44,12 @@9BBB2FAEDBD35A83EAB02981 /* AccountSwitcherView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */; };A81CCD9288B1F54D9BB145EC /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DF2F130F22D2672B7747474 /* AccountSession.swift */; };AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };+ ADA06AC9F6CD98F58F77D364 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };+ AF21AAA6549D150D18C8927F /* UpdatesManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B08914B44558AFBF93C2E671 /* UpdatesManager.swift */; };B3554D38F39916698E961A37 /* WidgetGalleryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B22589689593E0089118FDB /* WidgetGalleryView.swift */; };B4373612F918A3158E69A8E3 /* SSHTunnel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */; };B7306D54C75E4A20E61142D0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */; };- B8B86B2B7F8D9EE8639A9E09 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };+ B8B86B2B7F8D9EE8639A9E09 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 80868F96B9905FF52DCDFAE2 /* CodyncKit */; };BA978F06CB1E58511FFB541B /* WidgetSetupDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D8961FADA8810B6CC479705 /* WidgetSetupDemo.swift */; };BF77DD7946621D8818EDAB9B /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A87B0091DAF0E4807D62017 /* SettingsView.swift */; };C263D5693212EB0812A232D9 /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */; };@@ -56,7 +58,7 @@EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 741B706007BA1B91CB853699 /* Screen.app */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };F171F16563D1FF6308697173 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };F842AE1C5ED96AF9A7F5D16C /* Widgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 6D734BEE7CD3F84677B0218B /* Widgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };- F93D9960F7C20B2E629C1736 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = 7D524C19E9D41C0CF635A619 /* ClerkKit */; };+ F93D9960F7C20B2E629C1736 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = AF460014351882D22C34DAA7 /* Sparkle */; };F97C489DDB806224CEFCEB57 /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28B2CB561A43ED9F2F1A4391 /* ScreenHelper.swift */; };/* End PBXBuildFile section */@@ -137,6 +139,7 @@52A96030D47F1B9678095909 /* iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iOS.entitlements; sourceTree = "<group>"; };5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };5B22589689593E0089118FDB /* WidgetGalleryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetGalleryView.swift; sourceTree = "<group>"; };+ 5D8E24CB8B64ED897CAEC580 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };60422D3CA8FEBCDC5AC465E0 /* iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; };64888B10E98F19723500FBCA /* NotificationService.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = "<group>"; };6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };@@ -152,6 +155,7 @@9F70117FA3097C5A6F28C89B /* ComputersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputersView.swift; sourceTree = "<group>"; };A65FE0504B741D0B44DB2516 /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };AD18A04CD014230F1B7B0535 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };+ B08914B44558AFBF93C2E671 /* UpdatesManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdatesManager.swift; sourceTree = "<group>"; };B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHTunnel.swift; sourceTree = "<group>"; };B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };B6E13F8EA6C7B0DA4D899FEE /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };@@ -177,9 +181,10 @@isa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;files = (- F93D9960F7C20B2E629C1736 /* ClerkKit in Frameworks */,- 24DF3CB466CC877FCB8BAED6 /* CodyncKit in Frameworks */,- B8B86B2B7F8D9EE8639A9E09 /* CodyncUI in Frameworks */,+ F93D9960F7C20B2E629C1736 /* Sparkle in Frameworks */,+ 24DF3CB466CC877FCB8BAED6 /* ClerkKit in Frameworks */,+ B8B86B2B7F8D9EE8639A9E09 /* CodyncKit in Frameworks */,+ ADA06AC9F6CD98F58F77D364 /* CodyncUI in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -226,6 +231,7 @@isa = PBXGroup;children = (5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */,+ 5D8E24CB8B64ED897CAEC580 /* Info.plist */,);path = Resources;sourceTree = "<group>";@@ -236,6 +242,7 @@7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */,14B7967A8F027FF28EAEA893 /* HostController.swift */,B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */,+ B08914B44558AFBF93C2E671 /* UpdatesManager.swift */,);path = App;sourceTree = "<group>";@@ -435,6 +442,7 @@);name = macOS;packageProductDependencies = (+ AF460014351882D22C34DAA7 /* Sparkle */,7D524C19E9D41C0CF635A619 /* ClerkKit */,80868F96B9905FF52DCDFAE2 /* CodyncKit */,BEE30A9D5C73E5A151F34180 /* CodyncUI */,@@ -570,6 +578,7 @@minimizedProjectReferenceProxies = 1;packageReferences = (2C830647014432C6F20C557C /* XCRemoteSwiftPackageReference "clerk-ios" */,+ 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */,979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */,4821371032224740E592D19C /* XCLocalSwiftPackageReference "../kit" */,);@@ -742,6 +751,7 @@8D83C54A832018932F7261DE /* ComputersView.swift in Sources */,2244021EF712DF568374AB04 /* HostController.swift in Sources */,B4373612F918A3158E69A8E3 /* SSHTunnel.swift in Sources */,+ AF21AAA6549D150D18C8927F /* UpdatesManager.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -802,7 +812,7 @@CODE_SIGN_STYLE = Automatic;CODYNC_ENV = main;COPY_PHASE_STRIP = NO;- CURRENT_PROJECT_VERSION = 21;+ CURRENT_PROJECT_VERSION = 22;DEAD_CODE_STRIPPING = YES;DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";DEVELOPMENT_TEAM = 7FUM8A8H72;@@ -836,9 +846,11 @@ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;COMBINE_HIDPI_IMAGES = YES;+ CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = macos/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = Codync;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_LSUIElement = YES;@@ -973,7 +985,7 @@CODE_SIGN_STYLE = Automatic;CODYNC_ENV = dev;COPY_PHASE_STRIP = NO;- CURRENT_PROJECT_VERSION = 21;+ CURRENT_PROJECT_VERSION = 22;DEAD_CODE_STRIPPING = YES;DEBUG_INFORMATION_FORMAT = dwarf;DEVELOPMENT_TEAM = 7FUM8A8H72;@@ -1118,9 +1130,11 @@ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;COMBINE_HIDPI_IMAGES = YES;+ CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = macos/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = Codync;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_LSUIElement = YES;@@ -1210,6 +1224,14 @@version = 1.5.6;};};+ 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/sparkle-project/Sparkle";+ requirement = {+ kind = exactVersion;+ version = 2.10.0;+ };+ };979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/stasel/WebRTC";@@ -1251,6 +1273,11 @@isa = XCSwiftPackageProductDependency;productName = CodyncKit;};+ AF460014351882D22C34DAA7 /* Sparkle */ = {+ isa = XCSwiftPackageProductDependency;+ package = 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */;+ productName = Sparkle;+ };BEE30A9D5C73E5A151F34180 /* CodyncUI */ = {isa = XCSwiftPackageProductDependency;productName = CodyncUI;diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rsindex 79e79521..48730c8e 100644--- a/apps/linux/src/dialogs.rs+++ b/apps/linux/src/dialogs.rs@@ -1310,6 +1310,166 @@ fn remote_screen_group() -> adw::PreferencesGroup {group}+fn host_updates_group(ui: &App) -> adw::PreferencesGroup {+ let group = adw::PreferencesGroup::builder()+ .title("Host updates")+ .description("Automatic updates wait until this computer's bots are idle.")+ .build();+ let status = adw::ActionRow::builder()+ .title("Checking update settings…")+ .build();+ let check = gtk::Button::builder()+ .label("Check for updates")+ .valign(gtk::Align::Center)+ .build();+ let install = gtk::Button::builder()+ .label("Install update")+ .valign(gtk::Align::Center)+ .sensitive(false)+ .build();+ let automatic = adw::SwitchRow::builder()+ .title("Automatically update the host")+ .sensitive(false)+ .build();+ status.add_suffix(&check);+ status.add_suffix(&install);+ group.add(&status);+ group.add(&automatic);+ let syncing = std::rc::Rc::new(std::cell::Cell::new(false));+ let render = {+ let (status, install, automatic, syncing) = (+ status.clone(),+ install.clone(),+ automatic.clone(),+ syncing.clone(),+ );+ move |value: &Value| {+ let standalone = value["method"] == "standalone";+ let version = value["state"]["availableVersion"].as_str();+ status.set_title(+ &version.map_or_else(|| "Host updates".to_owned(), |v| format!("Version {v}")),+ );+ let description =+ match value["method"].as_str() {+ Some("homebrew") => "Update with brew upgrade leepokai/codync/codync-host",+ Some("development") => "Rebuild this development installation to update it.",+ Some("appBundle") => "Update the Codync Mac app to update its bundled host.",+ _ => value["state"]["error"].as_str().unwrap_or_else(|| {+ match value["state"]["phase"].as_str() {+ Some("complete") => "Update installed and host restarted.",+ Some("installing" | "checking" | "scheduled") => "Updating the host…",+ Some("upToDate") => "The host is up to date.",+ _ => "Checks signed releases for this computer.",+ }+ }),+ };+ status.set_subtitle(description);+ install.set_sensitive(+ standalone+ && version.is_some()+ && !matches!(+ value["state"]["phase"].as_str(),+ Some("installing" | "checking" | "scheduled" | "complete")+ ),+ );+ syncing.set(true);+ automatic.set_active(value["automatic"] == true);+ automatic.set_sensitive(standalone);+ syncing.set(false);+ }+ };+ {+ let (render, status) = (render.clone(), status.clone());+ client::call(+ "hostUpdateStatus",+ client::empty(),+ move |result| match result {+ Ok(value) => render(&value),+ Err(error) => status.set_subtitle(&error),+ },+ );+ }+ {+ let (render, ui) = (render.clone(), ui.clone());+ check.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (button, render, ui) = (button.clone(), render.clone(), ui.clone());+ client::call("checkHostUpdate", client::empty(), move |result| {+ button.set_sensitive(true);+ match result {+ Ok(value) => render(&value),+ Err(error) => ui::toast(&ui, &error),+ }+ });+ });+ }+ {+ let (render, ui) = (render.clone(), ui.clone());+ automatic.connect_active_notify(move |row| {+ if syncing.get() {+ return;+ }+ let (row, render, ui, syncing) =+ (row.clone(), render.clone(), ui.clone(), syncing.clone());+ let enabled = row.is_active();+ client::call(+ "setHostAutomaticUpdates",+ json!({"enabled": enabled}),+ move |result| match result {+ Ok(value) => render(&value),+ Err(error) => {+ syncing.set(true);+ row.set_active(!enabled);+ syncing.set(false);+ ui::toast(&ui, &error);+ }+ },+ );+ });+ }+ {+ let (ui, status, group) = (ui.clone(), status.clone(), group.downgrade());+ install.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (ui, status, button, render, group) = (+ ui.clone(),+ status.clone(),+ button.clone(),+ render.clone(),+ group.clone(),+ );+ client::call(+ "installHostUpdate",+ json!({"force": false}),+ move |result| match result {+ Ok(_) => {+ status.set_subtitle("Updating the host; reconnecting when it is ready…");+ let mut attempts = 0;+ gtk::glib::timeout_add_seconds_local(3, move || {+ attempts += 1;+ if group.upgrade().is_none() || attempts > 120 {+ return gtk::glib::ControlFlow::Break;+ }+ let render = render.clone();+ client::call("hostUpdateStatus", client::empty(), move |result| {+ if let Ok(value) = result {+ render(&value);+ }+ });+ gtk::glib::ControlFlow::Continue+ });+ }+ Err(error) => {+ button.set_sensitive(true);+ ui::toast(&ui, &error);+ }+ },+ );+ });+ }+ group+}+pub fn settings(ui: &App) {let (dialog, view, _) = header_dialog("Computers & devices", 520, 720);let page = adw::PreferencesPage::new();@@ -1419,6 +1579,7 @@ pub fn settings(ui: &App) {}page.add(&agents);+ page.add(&host_updates_group(ui));let about = adw::PreferencesGroup::new();about.add(&adw::ActionRow::builder()diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swiftindex e647d364..11cf8570 100644--- a/apps/macos/App/CodyncMacApp.swift+++ b/apps/macos/App/CodyncMacApp.swift@@ -5,6 +5,8 @@ import SwiftUI@mainstruct CodyncMacApp: App {+ @NSApplicationDelegateAdaptor(CodyncAppDelegate.self) private var appDelegate+ @State private var updates = UpdatesManager()@State private var host: HostController@State private var account: AccountSession@Environment(\.openWindow) private var openWindow@@ -22,11 +24,14 @@ struct CodyncMacApp: App {.labelStyle(.titleAndIcon).environment(host).environment(account)+ .environment(updates)} label: {// The Codync mark; a dot joins it when a bot needs you.Image(host.needsAttention ? "MenuBarIconAlert" : "MenuBarIcon").task {host.start()+ appDelegate.updates = updates+ updates.start(host: host)openWindow(id: "chat")}.onChange(of: account.userID) { _, userID in host.switchAccount(to: userID) }@@ -67,6 +72,7 @@ struct CodyncMacApp: App {/// A system menu: macOS owns layout, selection, keyboard navigation and submenus.struct MenuView: View {+ @Environment(UpdatesManager.self) private var updates@Environment(HostController.self) private var host@Environment(\.openWindow) private var openWindow@AppStorage(SharedStore.usageIconStyleKey, store: UserDefaults(suiteName: SharedStore.appGroup))@@ -96,6 +102,30 @@ struct MenuView: View {set: { host.setLaunchAtLogin($0) }))Divider()+ Menu("Updates") {+ Button(updates.availableVersion.map { "Update to \($0)…" } ?? "Check for Updates…") {+ updates.checkForUpdates()+ }+ .disabled(!updates.canCheckForUpdates && !updates.hasStagedUpdate)+ Toggle("Automatically check for updates", isOn: Binding(+ get: { updates.automaticallyChecksForUpdates },+ set: { updates.automaticallyChecksForUpdates = $0 }+ ))+ .disabled(!updates.isSupported)+ Toggle("Automatically download and install", isOn: Binding(+ get: { updates.automaticallyDownloadsUpdates },+ set: { updates.automaticallyDownloadsUpdates = $0 }+ ))+ .disabled(!updates.isSupported)+ if !updates.isSupported { Text("Updates are available in release builds.") }+ if let date = updates.lastUpdateCheckDate { Text("Last checked: \(date.formatted())") }+ if let error = updates.errorMessage {+ Text(error)+ Button("Retry installing update") { updates.retryInstallation() }+ .disabled(updates.preparingInstallation)+ }+ }+ Divider()Button("Restart host") { host.restart() }Button("Open log") { NSWorkspace.shared.open(host.logURL) }Divider()diff --git a/apps/macos/App/HostController.swift b/apps/macos/App/HostController.swiftindex 585a5071..3d542542 100644--- a/apps/macos/App/HostController.swift+++ b/apps/macos/App/HostController.swift@@ -1,6 +1,7 @@import AppKitimport CodyncKitimport CodyncUI+import CryptoKitimport Foundationimport Observationimport os@@ -66,6 +67,9 @@ final class HostController {private var streamTask: Task<Void, Never>?/// Set once the service was moved onto this app's host because it ran another version.private var replacedStaleHost = false+ private var expectedBinaryHash: String?+ private var installingHost = false+ private var preparingForUpdate = falseinit(account: AccountSession) {#if DEBUG@@ -205,10 +209,16 @@ final class HostController {}func refresh() {+ guard !preparingForUpdate else { return }guard binaryURL != nil else {state = .missingBinaryreturn}+ if Self.devPort == nil, UserDefaults.standard.bool(forKey: Self.updateRestartKey),+ FileManager.default.fileExists(atPath: plistURL.path) {+ install()+ return+ }guard Self.devPort != nil || FileManager.default.fileExists(atPath: plistURL.path) else {// The app is the way to run the host on a Mac: set it up right away, unless the user took it out.if UserDefaults.standard.bool(forKey: Self.uninstalledKey) { state = .notInstalled } else { install() }@@ -219,13 +229,17 @@ final class HostController {/// Set by "Uninstall host service", so the next launch doesn't put the host back.private static let uninstalledKey = "hostUninstalled"+ private static let updateRestartKey = "hostRestartAfterAppUpdate"/// `codync-host install` also routes Claude Code's status line through the host.func install() {- guard let bin = binaryURL else { return }+ guard !preparingForUpdate, !installingHost, let bin = binaryURL else { return }+ installingHost = true+ streamTask?.cancel()UserDefaults.standard.set(false, forKey: Self.uninstalledKey)state = .startingTask {+ defer { installingHost = false }let result = await Self.run(bin, ["install", "--port", "\(Self.port)"])if result.status != 0 {state = .failed(result.output.isEmpty ? "Install failed" : result.output)@@ -237,14 +251,14 @@ final class HostController {}func restart() {- // Nothing to restart when the service was never set up (a failed install).- guard Self.devPort != nil || FileManager.default.fileExists(atPath: plistURL.path) else { return install() }- let uid = getuid()- Task {- _ = await Self.run(URL(filePath: "/bin/launchctl"), ["kickstart", "-k", "gui/\(uid)/com.pokai.codync.host"])- try? await Task.sleep(for: .seconds(1))- connect()+ guard Self.devPort == nil else {+ state = .failed("Restart the manually started development host in its terminal.")+ return}+ // Reinstall also updates the executable path and waits for the old host+ // to release its data lock. A kickstart could restart another app's copy.+ replacedStaleHost = false+ install()}func uninstall() {@@ -269,9 +283,11 @@ final class HostController {/// Remote screen: starts/stops Codync Screen and tells the host (which only accepts this from the Mac itself).func setRemoteScreen(_ on: Bool) {+ guard !preparingForUpdate else { return }Task {do {if on { try screenAgent.register() } else { try await screenAgent.unregister() }+ UserDefaults.standard.set(on ? Self.helperStamp : nil, forKey: Self.helperStampKey)try await store?.setScreenEnabled(on)screenError = nil} catch {@@ -285,16 +301,80 @@ final class HostController {SMAppService.openSystemSettingsLoginItems()}- /// Keeps Codync Screen registered while the host has Remote screen on (e.g. after the app moved).- private func syncScreenAgent() {- guard screen?.enabled == true, screenAgent.status != .enabled else {+ /// Keeps Codync Screen registered while the host has Remote screen on (e.g. after the app moved),+ /// and registers it again when this app ships a different helper binary (an update or a rebuild):+ /// launchd keeps running the old helper, and a new binary under the old registration fails to start.+ private func syncScreenAgent() async {+ guard !preparingForUpdate else { return }+ guard screen?.enabled == true else {+ screenAgentNeedsApproval = false+ return+ }+ let stamp = Self.helperStamp+ let stale = UserDefaults.standard.string(forKey: Self.helperStampKey) != stamp+ guard stale || screenAgent.status != .enabled else {screenAgentNeedsApproval = falsereturn}+ if stale, screenAgent.status == .enabled {+ log.info("Codync Screen changed; registering it again")+ // Stops the old helper along with its job.+ try? await screenAgent.unregister()+ }try? screenAgent.register()+ if screenAgent.status == .enabled { UserDefaults.standard.set(stamp, forKey: Self.helperStampKey) }screenAgentNeedsApproval = screenAgent.status == .requiresApproval}+ private static let helperStampKey = "screenHelperStamp"++ /// Identifies the helper binary inside this app: its path and modification date.+ private static var helperStamp: String {+ let url = Bundle.main.bundleURL.appending(path: "Contents/Library/LoginItems/CodyncScreen.app/Contents/MacOS/CodyncScreen")+ let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate+ return "\(url.path)@\(modified?.timeIntervalSince1970 ?? 0)"+ }++ func isIdleForUpdate() async -> Bool {+ guard !installingHost, !preparingForUpdate, Self.devPort == nil else { return false }+ if !FileManager.default.fileExists(atPath: plistURL.path) { return true }+ guard let health = await HostHealth.fetch(Self.baseURL) else { return false }+ return health.busy == false+ }++ func prepareForUpdate() async throws {+ guard Self.devPort == nil else { return }+ guard !installingHost else {+ throw NSError(domain: "Codync.Update", code: 1,+ userInfo: [NSLocalizedDescriptionKey: "The host is being installed. Try again when it finishes."])+ }+ preparingForUpdate = true+ // Persist before stopping: Sparkle can install on Quit and relaunch later.+ if FileManager.default.fileExists(atPath: plistURL.path) {+ UserDefaults.standard.set(true, forKey: Self.updateRestartKey)+ }+ streamTask?.cancel()+ if screenAgent.status == .enabled {+ try await screenAgent.unregister()+ UserDefaults.standard.removeObject(forKey: Self.helperStampKey)+ }+ guard let bin = binaryURL else {+ throw NSError(domain: "Codync.Update", code: 2,+ userInfo: [NSLocalizedDescriptionKey: "The bundled host is missing."])+ }+ let result = await Self.run(bin, ["stop"])+ guard result.status == 0 else {+ throw NSError(domain: "Codync.Update", code: 3,+ userInfo: [NSLocalizedDescriptionKey: result.output.isEmpty ? "The old host could not be stopped." : result.output])+ }+ }++ func resumeAfterCancelledUpdate() {+ guard preparingForUpdate else { return }+ preparingForUpdate = false+ if FileManager.default.fileExists(atPath: plistURL.path) { install() } else { refresh() }+ }+func stop(_ item: RosterItem) {accounts.store(for: item.ref.computerId)?.stop(item.bot.id)}@@ -471,15 +551,28 @@ final class HostController {/// Watches the host's health; the BotStore handles the event stream itself.private func connect() {+ guard !preparingForUpdate else { return }streamTask?.cancel()streamTask = Task { [weak self] in+ if let bin = self?.binaryURL {+ let hash = await Task.detached {+ (try? Data(contentsOf: bin)).map { data in+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }+ }.value+ guard !Task.isCancelled else { return }+ self?.expectedBinaryHash = hash+ }var failures = 0while !Task.isCancelled {guard let self else { return }if await self.attachLocal() {failures = 0self.state = .running- self.syncScreenAgent()+ if Self.devPort == nil {+ UserDefaults.standard.removeObject(forKey: Self.updateRestartKey)+ }+ await self.syncScreenAgent()} else {failures += 1if failures > 5 { self.state = .failed("The host isn't responding. See the log for details.") }@@ -495,12 +588,22 @@ final class HostController {guard let token = readToken(), let health = await HostHealth.fetch(Self.baseURL), let id = health.computerId else {return false}- // An upgrade (Homebrew, a new DMG) replaced the app while the old host kept running.- if Self.devPort == nil, !replacedStaleHost, let running = health.version,- running != Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {- log.info("Host \(running, privacy: .public) differs from the app's; reinstalling the service")- replacedStaleHost = true- install()+ // A rebuild can change the host without changing the release version.+ // Legacy hosts have no fingerprint and are replaced once as well.+ if Self.devPort == nil {+ guard let expectedBinaryHash, let bin = binaryURL else { return false }+ let matches = health.binaryHash == expectedBinaryHash+ && health.binaryPath == bin.resolvingSymlinksInPath().path+ if !matches {+ if !replacedStaleHost {+ log.info("Host binary differs from this app's; reinstalling the service")+ replacedStaleHost = true+ install()+ }+ return false+ }+ }+ if Task.isCancelled {return false}if local?.id == id, localToken == token, store != nil { return true }diff --git a/apps/macos/App/SSHTunnel.swift b/apps/macos/App/SSHTunnel.swiftindex ab8368ee..ab27eb26 100644--- a/apps/macos/App/SSHTunnel.swift+++ b/apps/macos/App/SSHTunnel.swift@@ -285,6 +285,9 @@ struct HostHealth: Decodable {var hostId: String?var computerId: ComputerID?var version: String?+ var binaryPath: String?+ var binaryHash: String?+ var busy: Bool?static func fetch(_ baseURL: URL, timeout: TimeInterval = 2) async -> HostHealth? {var request = URLRequest(url: baseURL.appending(path: "health"))diff --git a/apps/macos/App/UpdatesManager.swift b/apps/macos/App/UpdatesManager.swiftnew file mode 100644index 00000000..68a11c89--- /dev/null+++ b/apps/macos/App/UpdatesManager.swift@@ -0,0 +1,219 @@+import AppKit+import Observation+import Sparkle++/// Sparkle owns download, signature verification and app replacement. Codync+/// coordinates its background services before letting the installer proceed.+@MainActor+@Observable+final class UpdatesManager: NSObject, SPUUpdaterDelegate, @preconcurrency SPUStandardUserDriverDelegate {+ private(set) var canCheckForUpdates = false+ private(set) var availableVersion: String?+ private(set) var lastUpdateCheckDate: Date?+ private(set) var errorMessage: String?+ private(set) var hasStagedUpdate = false+ private(set) var preparingInstallation = false++ var automaticallyChecksForUpdates = true {+ didSet { controller?.updater.automaticallyChecksForUpdates = automaticallyChecksForUpdates }+ }+ var automaticallyDownloadsUpdates = false {+ didSet { controller?.updater.automaticallyDownloadsUpdates = automaticallyDownloadsUpdates }+ }++ #if DEBUG+ let isSupported = false+ #else+ let isSupported = true+ #endif++ @ObservationIgnored private weak var host: HostController?+ @ObservationIgnored private var controller: SPUStandardUpdaterController?+ @ObservationIgnored private var observations: [NSKeyValueObservation] = []+ @ObservationIgnored private var idleTask: Task<Void, Never>?+ @ObservationIgnored private var pendingInstall: (() -> Void)?+ @ObservationIgnored private var automaticInstall: (() -> Void)?+ @ObservationIgnored private var servicesPrepared = false+ @ObservationIgnored private var preparationTask: Task<Bool, Never>?++ func start(host: HostController) {+ guard controller == nil, isSupported else { return }+ self.host = host+ let controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: self, userDriverDelegate: self)+ self.controller = controller+ let updater = controller.updater+ observations = [+ updater.observe(\.canCheckForUpdates, options: [.initial, .new]) { [weak self] _, _ in+ Task { @MainActor in self?.readSettings() }+ },+ updater.observe(\.lastUpdateCheckDate, options: [.initial, .new]) { [weak self] _, _ in+ Task { @MainActor in self?.readSettings() }+ },+ updater.observe(\.automaticallyChecksForUpdates, options: [.new]) { [weak self] _, _ in+ Task { @MainActor in self?.readSettings() }+ },+ updater.observe(\.automaticallyDownloadsUpdates, options: [.new]) { [weak self] _, _ in+ Task { @MainActor in self?.readSettings() }+ },+ ]+ do {+ try updater.start()+ readSettings()+ } catch {+ errorMessage = error.localizedDescription+ }+ }++ private func readSettings() {+ guard let updater = controller?.updater else { return }+ canCheckForUpdates = updater.canCheckForUpdates+ lastUpdateCheckDate = updater.lastUpdateCheckDate+ if automaticallyChecksForUpdates != updater.automaticallyChecksForUpdates {+ automaticallyChecksForUpdates = updater.automaticallyChecksForUpdates+ }+ if automaticallyDownloadsUpdates != updater.automaticallyDownloadsUpdates {+ automaticallyDownloadsUpdates = updater.automaticallyDownloadsUpdates+ }+ }++ func checkForUpdates() {+ if let install = automaticInstall {+ automaticInstall = nil+ idleTask?.cancel()+ prepareAndContinue(install)+ return+ }+ guard canCheckForUpdates else { return }+ errorMessage = nil+ NSApp.activate()+ controller?.checkForUpdates(nil)+ }++ func retryInstallation() {+ guard let pendingInstall else { return }+ prepareAndContinue(pendingInstall)+ }++ private func prepareAndContinue(_ install: @escaping () -> Void) {+ guard !preparingInstallation else { return }+ pendingInstall = install+ preparingInstallation = true+ Task {+ defer { preparingInstallation = false }+ if await prepareServices() {+ pendingInstall = nil+ install()+ }+ }+ }++ /// Also used on Quit: Sparkle may install a staged update without relaunching,+ /// in which case its postpone-relaunch delegate is not guaranteed to run.+ func prepareServices() async -> Bool {+ if servicesPrepared { return true }+ if let preparationTask { return await preparationTask.value }+ let task = Task { await self.stopServices() }+ preparationTask = task+ let ready = await task.value+ preparationTask = nil+ return ready+ }++ private func stopServices() async -> Bool {+ guard let host else { return false }+ do {+ try await host.prepareForUpdate()+ guard !Task.isCancelled else {+ host.resumeAfterCancelledUpdate()+ return false+ }+ servicesPrepared = true+ errorMessage = nil+ return true+ } catch {+ errorMessage = "Update paused: \(error.localizedDescription)"+ host.resumeAfterCancelledUpdate()+ return false+ }+ }++ func updater(_ updater: SPUUpdater, shouldPostponeRelaunchForUpdate item: SUAppcastItem,+ untilInvokingBlock installHandler: @escaping () -> Void) -> Bool {+ hasStagedUpdate = true+ prepareAndContinue(installHandler)+ return true+ }++ func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) {+ hasStagedUpdate = true+ }++ func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem,+ immediateInstallationBlock installHandler: @escaping () -> Void) -> Bool {+ hasStagedUpdate = true+ availableVersion = item.displayVersionString+ automaticInstall = installHandler+ idleTask?.cancel()+ idleTask = Task { [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(30))+ guard !Task.isCancelled, let self else { return }+ guard self.automaticallyDownloadsUpdates, !NSApp.isActive,+ CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: .null) >= 600,+ await self.host?.isIdleForUpdate() == true,+ let install = self.automaticInstall else { continue }+ self.automaticInstall = nil+ self.prepareAndContinue(install)+ return+ }+ }+ return true+ }++ func updater(_ updater: SPUUpdater, didAbortWithError error: Error) {+ idleTask?.cancel()+ preparationTask?.cancel()+ pendingInstall = nil+ automaticInstall = nil+ hasStagedUpdate = false+ servicesPrepared = false+ availableVersion = nil+ // No-update and user cancellation are ordinary outcomes; Sparkle shows+ // actionable errors in its standard interface for a manual update check.+ let failure = error as NSError+ let ordinary = failure.domain == SUSparkleErrorDomain &&+ [Int(SUError.noUpdateError.rawValue), Int(SUError.installationCanceledError.rawValue)].contains(failure.code)+ errorMessage = ordinary ? nil : error.localizedDescription+ host?.resumeAfterCancelledUpdate()+ readSettings()+ }++ var supportsGentleScheduledUpdateReminders: Bool { true }++ func standardUserDriverShouldHandleShowingScheduledUpdate(_ update: SUAppcastItem,+ andInImmediateFocus immediateFocus: Bool) -> Bool {+ NSApp.isActive && immediateFocus+ }++ func standardUserDriverWillHandleShowingUpdate(_ handleShowingUpdate: Bool,+ forUpdate update: SUAppcastItem, state: SPUUserUpdateState) {+ availableVersion = update.displayVersionString+ if state.userInitiated { NSApp.activate() }+ }+}++/// Normal Quit leaves the daemon running. If Sparkle has staged an update,+/// termination waits until the background services have actually stopped.+@MainActor+final class CodyncAppDelegate: NSObject, NSApplicationDelegate {+ weak var updates: UpdatesManager?++ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ guard let updates, updates.hasStagedUpdate else { return .terminateNow }+ Task {+ let ready = await updates.prepareServices()+ sender.reply(toApplicationShouldTerminate: ready)+ }+ return .terminateLater+ }+}diff --git a/apps/macos/Resources/Info.plist b/apps/macos/Resources/Info.plistnew file mode 100644index 00000000..3616103c--- /dev/null+++ b/apps/macos/Resources/Info.plist@@ -0,0 +1,20 @@+<?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">+<plist version="1.0">+<dict>+ <key>SUFeedURL</key>+ <string>https://github.com/leepokai/Codync/releases/latest/download/appcast.xml</string>+ <key>SUPublicEDKey</key>+ <string>/WvuKYw0ghkj3ExQbCejTquAcozuP1Llo2k8TIvx0Mc=</string>+ <key>SUEnableAutomaticChecks</key>+ <true/>+ <key>SUAutomaticallyUpdate</key>+ <false/>+ <key>SUAllowsAutomaticUpdates</key>+ <true/>+ <key>SUScheduledCheckInterval</key>+ <integer>86400</integer>+ <key>SUVerifyUpdateBeforeExtraction</key>+ <true/>+</dict>+</plist>diff --git a/apps/project.yml b/apps/project.ymlindex 85f6f0e7..86f4d4cb 100644--- a/apps/project.yml+++ b/apps/project.yml@@ -7,6 +7,9 @@ options:macOS: "14.0"createIntermediateGroups: truepackages:+ Sparkle:+ url: https://github.com/sparkle-project/Sparkle+ exactVersion: 2.10.0Clerk:url: https://github.com/clerk/clerk-iosexactVersion: 1.5.6@@ -49,6 +52,8 @@ targets:destination: wrappersubpath: Contents/Library/LaunchAgentsdependencies:+ - package: Sparkle+ product: Sparkle- package: Clerkproduct: ClerkKit- package: CodyncKit@@ -66,6 +71,9 @@ targets:PRODUCT_NAME: CodyncPRODUCT_BUNDLE_IDENTIFIER: com.pokai.CodyncGENERATE_INFOPLIST_FILE: YES+ INFOPLIST_FILE: macos/Resources/Info.plist+ # Sparkle compares this version; iOS retains its separate upload counter.+ CURRENT_PROJECT_VERSION: "$(MARKETING_VERSION)"INFOPLIST_KEY_LSUIElement: YESINFOPLIST_KEY_CFBundleDisplayName: CodyncINFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-toolsdiff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 497bf47a..a90e90fc 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -14,6 +14,10 @@ Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/S## macOS menu bar+Release update controls live in the native Settings → Updates menu. Sparkle's+standard update/install windows are a native system-integration exception; keep+signature errors, progress and relaunch in its supported user driver.+Use `MenuBarExtra` with `.menuBarExtraStyle(.menu)`. Its commands, submenus, checkmarked toggles, usage-icon picker, separators and keyboard navigation use system styling. Do not add custom cards, hover backgrounds, icon buttons or a window-style menu panel here.The menu retains host installation/restart, bot conversation/stop actions, approval review, usage limits, remote-screen permissions, launch-at-login and quit. Pairing opens a separate titled window because its QR needs a persistent scanning surface. The chat window retains its own UI conventions.diff --git a/docs/guides/development.md b/docs/guides/development.mdindex 2e871855..d1d36926 100644--- a/docs/guides/development.md+++ b/docs/guides/development.md@@ -1,5 +1,7 @@# Development and validation+For release updates, automatic installation and host rollback, see [updates](updates.md).+Run commands from the repository root unless a block changes directory. See [file structure](../architecture/file-structure.md) for ownership and [environment configuration](environments-and-deployment.md) before testing cloud access.## Apple apps@@ -21,7 +23,24 @@ pkill -x Codyncopen build/dd/Build/Products/Debug/Codync.app```-`pkill` can return nonzero when no process exists. If the development launch agent is installed, restart the embedded host and inspect other host processes for stale binaries:+`pkill` can return nonzero when no process exists.++The Mac app compares the running host's executable path and SHA-256 fingerprint+with its bundled host, so reopening a rebuild replaces the service even when the+version number has not changed. **Restart host** reinstalls the service from this+app and waits for the old host's data lock to be released. If a manually started+host still owns that data directory, installation fails instead of reporting a+successful restart; stop that host in its terminal and retry. Hosts attached using+`CODYNC_PORT` are managed manually.++On SIGTERM the host stops its bots without waiting for open SSE or WebSocket+connections. ACP adapters run in separate process groups; stopping an adapter+also kills tools and MCP servers that remain in its group. Processes that detach+into their own sessions and unrelated hosts using other data directories are+outside this cleanup.++For a manual restart of the installed launch agent, and to inspect other host+processes for stale binaries:```shlaunchctl kickstart -k gui/$(id -u)/com.pokai.codync.hostdiff --git a/docs/guides/updates.md b/docs/guides/updates.mdnew file mode 100644index 00000000..efe43d3a--- /dev/null+++ b/docs/guides/updates.md@@ -0,0 +1,97 @@+# App and host updates++## macOS++Release builds use Sparkle 2.10.0. Open **Settings → Updates** in the menu bar+to check for a release, enable scheduled checks, or opt into automatic downloads+and installation. Debug builds disable the production updater.++The app checks daily. Automatic installation waits until the app is inactive,+there has been no keyboard/mouse input for ten minutes, and the local host reports+no working bots, pending input, or running setup terminals. A staged update can+also install when quitting. Manual installation can interrupt work.++Before replacement, Codync unregisters its screen helper and stops the host,+waiting for its data lock to be released. If cleanup fails, installation pauses+with a retry action. A persistent restart marker makes the next app launch+reinstall the host service from the new bundle; remote screen registration is+restored when the host reports that it is enabled. Ordinary Quit keeps the host+running when no update is staged.++Sparkle verifies Ed25519 signatures before extraction. Its standard installer+handles app replacement and relaunch. Appcast URLs identify an immutable release+archive; the feed itself is served from the latest GitHub release. macOS build+versions follow the marketing version; the iOS build counter is independent.++## Standalone hosts on Linux and macOS++```sh+codync-host update --check+codync-host update+codync-host update --status --json+codync-host update --auto on+codync-host update --auto off+```++Use `--port` for a host on a nondefault port. `--force` explicitly allows a manual+update to interrupt bots. Stop a manually launched host before replacing it.+Automatic updates require an installed background service and are off by default.+They check daily while idle; failures are reported in update status.++The Linux app exposes these controls under **Computers & devices → Host updates**.+The API operations (`hostUpdateStatus`, `checkHostUpdate`, `installHostUpdate`,+`setHostAutomaticUpdates`) require a local connection, including an SSH tunnel.++Installed services schedule the updater as an independent launchd job or systemd+user unit, so stopping the daemon does not kill its updater. The CLI returns after+scheduling; inspect progress with `--status`. A lock prevents concurrent updates.+The updater verifies the manifest's Ed25519 signature, platform, stable version,+URL, archive size and SHA-256 before extracting only the host executable.++It stages beside the installed executable, keeps a rollback copy, stops the old+service, atomically replaces the binary and starts the service with its existing+configuration. Health must report the expected version, binary fingerprint and+computer identity within 30 seconds. Startup failure restores and restarts the+previous binary. Data is preserved; this is binary rollback, not database rollback+or recovery from power loss during installation.++Bundled hosts are updated with the Mac app. Homebrew hosts use+`brew upgrade leepokai/codync/codync-host`, followed by `codync-host install`.+Development builds must be rebuilt. The independent updater refuses to overwrite+those installations. The Linux desktop executable remains package-managed or+manually installed; its update controls update the host.++## Release configuration++Both workflows run for a `vMAJOR.MINOR.PATCH` tag. Keep the host Cargo version and+the app marketing version aligned before tagging. The host workflow refuses a+tag/version mismatch. Existing clients without this updater need one manual+upgrade to adopt it.++Public keys are committed in `packaging/updates/`. Keep their corresponding+private keys backed up securely; replacing a public key breaks updates for+already distributed clients. Repository Actions secrets:++| Secret | Contents |+| --- | --- |+| `SPARKLE_PRIVATE_KEY` | Sparkle's base64 Ed25519 private key export |+| `HOST_UPDATE_SIGNING_KEY` | Separate base64 32-byte Ed25519 seed for host manifests |++The Mac workflow signs/notarizes the app, builds its DMG, generates `appcast.xml`,+then verifies the actual DMG signature and metadata before upload. The host+workflow emits `codync-host-<platform>.update.json` and `.update.json.sig` alongside+each archive. Signing fails if a private key does not match the committed public+key. Never commit private keys or put them in command-line arguments.++A published release must include these assets before clients can update. A+missing feed or manifest is reported as a check failure; no unsigned fallback is+used. Building locally or configuring secrets does not publish a release.++## References++- [Sparkle publishing documentation](https://sparkle-project.org/documentation/publishing/)+- [Sparkle gentle reminders](https://sparkle-project.org/documentation/gentle-reminders/)+- [Grok Bot's safe relaunch gate](https://github.com/b-nnett/grok-bot-0.18-reconstructed/blob/main/source/electron-main/update/safe-relaunch-gate.ts)++Grok Bot supplied the reference for opt-in, staged updates and idle-gated restart.+Codync uses app inactivity and input idle time; it does not require a locked screen.diff --git a/host/Cargo.lock b/host/Cargo.lockindex 56d6ae78..257c94b3 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -2,6 +2,12 @@# It is not intended for manual editing.version = 4+[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]name = "aead"version = "0.6.1"@@ -575,6 +581,7 @@ dependencies = ["crossterm","dirs","ed25519-dalek",+ "flate2","fs2","futures","gethostname",@@ -587,10 +594,12 @@ dependencies = ["ratatui","reqwest","rusqlite",+ "semver","serde","serde_json","sha2 0.11.0","shlex",+ "tar","tokio","tokio-stream","tokio-tungstenite",@@ -700,6 +709,15 @@ dependencies = ["libc",]+[[package]]+name = "crc32fast"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+dependencies = [+ "cfg-if",+]+[[package]]name = "croner"version = "3.0.1"@@ -1151,12 +1169,33 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"+[[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.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"+[[package]]+name = "flate2"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+dependencies = [+ "crc32fast",+ "miniz_oxide",+ "zlib-rs",+]+[[package]]name = "fnv"version = "1.0.7"@@ -2027,6 +2066,16 @@ version = "0.3.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]+[[package]]name = "mio"version = "1.2.3"@@ -3133,6 +3182,12 @@ version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"+[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"+[[package]]name = "simd_cesu8"version = "1.2.0"@@ -3297,6 +3352,17 @@ dependencies = ["syn 3.0.6",]+[[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 = "tempfile"version = "3.27.0"@@ -4094,6 +4160,16 @@ dependencies = ["zeroize",]+[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]+[[package]]name = "xdg-home"version = "1.3.0"@@ -4277,6 +4353,12 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"+[[package]]name = "zmij"version = "1.0.23"diff --git a/host/Cargo.toml b/host/Cargo.tomlindex 247cda8d..523b405b 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -20,6 +20,7 @@ croner = "3"crossterm = { version = "0.29", features = ["event-stream"] }dirs = "7.0.0"ed25519-dalek = "3.0.0"+flate2 = "1.1.10"fs2 = "0.4.3"futures = "0.3.34"gethostname = "1.1.0"@@ -31,10 +32,12 @@ qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }ratatui = { version = "0.30", default-features = false, features = ["crossterm"] }reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream"] }rusqlite = { version = "0.40.2", features = ["bundled"] }+semver = "1.0.28"serde = { version = "1.0.229", features = ["derive"] }serde_json = { version = "1.0.151", features = ["preserve_order"] }sha2 = "0.11.0"shlex = "2.0.1"+tar = "0.4.46"tokio = { version = "1.53.1", features = ["full"] }tokio-stream = { version = "0.1.19", features = ["sync"] }tokio-tungstenite = { version = "0.29", features = ["rustls-tls-webpki-roots"] }diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex 16e1d35a..806dd5b7 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -90,6 +90,7 @@ impl Acp {.stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true)+ .process_group(0).spawn().with_context(|| format!("starting `{command}`"))?;let stdin = child.stdin.take().expect("stdin is piped");@@ -201,8 +202,18 @@ impl Acp {}pub async fn kill(&self) {+ let mut child = self.child.lock().await;+ // ACP adapters spawn MCP servers and tools. Give each adapter its own+ // group and stop that group before reaping its leader.+ if let Some(pid) = child.id() {+ let _ = Command::new("/bin/kill")+ .args(["-KILL", "--", &format!("-{pid}")])+ .stderr(Stdio::null())+ .status()+ .await;+ }// Already exited is fine; anything else is worth a log line.- if let Err(error) = self.child.lock().await.kill().await+ if let Err(error) = child.kill().await&& error.kind() != std::io::ErrorKind::InvalidInput{tracing::debug!(%error, "couldn't kill agent process");@@ -253,6 +264,22 @@ mod tests {assert_eq!(truncate("héllo", 2), "h…");}+ #[tokio::test]+ async fn stopping_an_agent_closes_its_descendants_pipes() {+ let (acp, mut rx) = Acp::spawn(+ r#"sh -c 'sleep 60 & echo "{\"jsonrpc\":\"2.0\",\"method\":\"ready\"}"; read line'"#,+ "/tmp",+ &[],+ )+ .unwrap();+ let ready = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await.unwrap();+ assert!(matches!(ready, Some(Incoming::Notification { .. })));+ acp.kill().await;+ // Killing only the shell leaves sleep holding stdout for 60 seconds.+ let closed = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await.unwrap();+ assert!(matches!(closed, Some(Incoming::Closed { .. })));+ }+#[tokio::test]async fn request_response_roundtrip() {// A fake agent: answers `initialize`, then sends a notification and exits.diff --git a/host/src/agent/term.rs b/host/src/agent/term.rsindex ab3a1b62..4d46f9b8 100644--- a/host/src/agent/term.rs+++ b/host/src/agent/term.rs@@ -81,6 +81,10 @@ impl Term {pub struct Terms(Mutex<HashMap<String, Arc<Term>>>);impl Terms {+ pub fn busy(&self) -> bool {+ self.0.locked().values().any(|term| term.output.locked().exit.is_none())+ }+pub fn get(&self, id: &str) -> Option<Arc<Term>> {self.0.locked().get(id).cloned()}diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 78f4b837..d05c92b9 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -30,6 +30,10 @@ impl Caller {/// Methods only this computer may call.const LOCAL_ONLY: &[&str] = &[+ "hostUpdateStatus",+ "checkHostUpdate",+ "installHostUpdate",+ "setHostAutomaticUpdates","setScreenEnabled","pairing","computerCall",diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 5c2723c7..52b0f5b8 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -106,6 +106,9 @@ async fn health(State(hub): State<Arc<Hub>>) -> Json<Value> {"hostId": hub.host_id,"computerId": hub.identity.computer_id(),"version": env!("CARGO_PKG_VERSION"),+ "binaryPath": crate::service::binary_identity().map(|(path, _)| path),+ "binaryHash": crate::service::binary_identity().map(|(_, hash)| hash),+ "busy": hub.busy(),}))}@@ -251,6 +254,20 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -market::vault::unlock(hub.clone()).await?;}Ok(match method {+ "hostUpdateStatus" => crate::update::status()?,+ "checkHostUpdate" => crate::update::check().await?,+ "setHostAutomaticUpdates" => {+ crate::update::set_automatic(b["enabled"].as_bool().context("enabled must be a boolean")?)?+ }+ "installHostUpdate" => {+ let port = hub.port;+ let force = b["force"].as_bool().unwrap_or(false);+ if !force && hub.busy() {+ bail!("host is busy; retry when idle or explicitly allow interruption");+ }+ tokio::task::spawn_blocking(move || crate::update::spawn_worker(port, force)).await??;+ json!({"scheduled": true})+ }"credentialUpdateConnector" => {let id = str_arg(&b, "id")?;let fields = b["fields"].as_object().ok_or_else(|| anyhow!("Credential fields are required"))?;diff --git a/host/src/hub.rs b/host/src/hub.rsindex 30778277..ce4a7ac3 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -75,6 +75,11 @@ pub struct Hub {}impl Hub {+ pub fn busy(&self) -> bool {+ self.runtime.locked().values().any(|r| matches!(r.status, BotStatus::Working | BotStatus::NeedsInput))+ || self.terms.busy()+ }+pub fn new(store: Store, host_id: String, identity: Identity, token: String, port: u16) -> Arc<Self> {let (events, _) = broadcast::channel(1024);let screen = Arc::new(Screen::new(Screen::load_enabled(&store), events.clone()));diff --git a/host/src/main.rs b/host/src/main.rsindex 53c01bc8..01c79963 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -12,6 +12,7 @@ mod screen;mod service;mod store;mod tui;+mod update;mod usage;use agent::{backends, registry};@@ -21,6 +22,7 @@ use anyhow::{Context, Result};use clap::{Parser, Subcommand};use serde_json::json;use std::fmt::Write as _;+use std::future::IntoFuture;use std::io::Read;use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};use std::time::Duration;@@ -121,6 +123,27 @@ enum Sub {},/// Stop and remove the background service.Uninstall,+ /// Stop the background service, keeping its configuration and all data.+ Stop,+ /// Update a standalone host, or inspect/configure its automatic updates.+ Update {+ #[arg(long, conflicts_with_all = ["status", "worker"])]+ check: bool,+ /// Read update progress without checking or installing a release.+ #[arg(long, conflicts_with = "worker")]+ status: bool,+ #[arg(long, value_parser = ["on", "off"], conflicts_with_all = ["check", "status", "worker"])]+ auto: Option<String>,+ /// Allow a manual update to interrupt active bots (their sessions resume).+ #[arg(long)]+ force: bool,+ #[arg(long, default_value_t = service::DEFAULT_PORT)]+ port: u16,+ #[arg(long)]+ json: bool,+ #[arg(long, hide = true)]+ worker: bool,+ },/// Show whether the host is installed and running.Status {#[arg(long, default_value_t = service::DEFAULT_PORT)]@@ -340,6 +363,42 @@ async fn main() -> Result<()> {println!("Codync host installed and started on port {port}. Run `codync-host pair` to connect your phone.");Ok(())}+ Sub::Update { check, status, auto, force, port, json, worker } => {+ let status = if let Some(auto) = auto {+ update::set_automatic(auto == "on")?+ } else if status {+ update::status()?+ } else if check {+ update::check().await?+ } else if !worker && service::installed() {+ tokio::task::spawn_blocking(move || update::spawn_worker(port, force)).await??;+ update::status()?+ } else {+ update::apply(port, force, worker).await?+ };+ if json {+ println!("{}", serde_json::to_string_pretty(&status)?);+ } else {+ println!(+ "Host {} · {}",+ status["currentVersion"].as_str().unwrap_or("unknown"),+ status["state"]["phase"].as_str().unwrap_or("ready")+ );+ println!("Automatic updates: {}", if status["automatic"] == true { "on" } else { "off" });+ if let Some(version) = status["state"]["availableVersion"].as_str() {+ println!("Available version: {version}");+ }+ if let Some(error) = status["state"]["error"].as_str() {+ println!("Last error: {error}");+ }+ }+ Ok(())+ }+ Sub::Stop => {+ tokio::task::spawn_blocking(service::stop).await??;+ println!("Codync host stopped.");+ Ok(())+ }Sub::Uninstall => {service::uninstall();if let Some(home) = dirs::home_dir()@@ -403,6 +462,7 @@ fn cap_log() {async fn serve(bind: &str, port: u16) -> Result<()> {let _instance_lock = tokio::task::spawn_blocking(service::lock_host).await??;+ tokio::task::spawn_blocking(service::capture_binary_identity).await??;let listener =tokio::net::TcpListener::bind((bind, port)).await.with_context(|| format!("binding {bind}:{port}"))?;cap_log();@@ -420,6 +480,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {tokio::spawn(registry::refresh_loop());tokio::spawn(backends::refresh_sign_in());tokio::spawn(usage::poll(hub.clone()));+ tokio::spawn(update::automatic_loop(hub.clone()));tokio::spawn(screen::serve_helpers(hub.screen.clone()));tokio::spawn(relay::run(hub.clone()));#[cfg(target_os = "linux")]@@ -427,8 +488,14 @@ async fn serve(bind: &str, port: u16) -> Result<()> {tracing::info!(version = env!("CARGO_PKG_VERSION"), bind, port, "codync-host listening");// Peer addresses: some settings may only be changed from this computer.let app = api::router(hub.clone()).into_make_service_with_connect_info::<std::net::SocketAddr>();- axum::serve(listener, app).with_graceful_shutdown(shutdown_signal()).await?;- // launchd/systemd stop us with SIGTERM: stop every agent instead of orphaning it.+ // SSE/WebSocket clients can stay connected forever. Stop agents immediately+ // on the signal instead of waiting for those connections to finish.+ let server = axum::serve(listener, app).into_future();+ tokio::pin!(server);+ tokio::select! {+ result = &mut server => result?,+ () = shutdown_signal() => {},+ }hub.shutdown().await;tracing::info!("codync-host stopped");Ok(())diff --git a/host/src/service.rs b/host/src/service.rsindex 87b25036..2a2cfb89 100644--- a/host/src/service.rs+++ b/host/src/service.rs@@ -7,8 +7,93 @@use anyhow::{Context, Result, bail};use serde_json::{Value, json};+use sha2::{Digest, Sha256};+use std::fmt::Write as _;use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};+use std::sync::OnceLock;+use std::time::{Duration, Instant};++static BINARY_IDENTITY: OnceLock<(String, String)> = OnceLock::new();++/// Snapshot before serving: reading the path again after an update would identify+/// the replacement on disk rather than this running process.+pub fn capture_binary_identity() -> Result<()> {+ let exe = std::env::current_exe()?.canonicalize()?;+ let mut hash = String::with_capacity(64);+ for byte in Sha256::digest(std::fs::read(&exe)?) {+ write!(hash, "{byte:02x}")?;+ }+ let _ = BINARY_IDENTITY.set((exe.to_string_lossy().into_owned(), hash));+ Ok(())+}++pub fn binary_identity() -> Option<&'static (String, String)> {+ BINARY_IDENTITY.get()+}++/// Do not claim a restart succeeded while an old daemon still holds the data.+fn wait_for_host_exit() -> Result<()> {+ let deadline = Instant::now() + Duration::from_secs(15);+ loop {+ match lock_host() {+ Ok(lock) => {+ drop(lock);+ return Ok(());+ }+ Err(error) if Instant::now() >= deadline => {+ return Err(error.context("old host did not exit; stop any manually started host before reinstalling"));+ }+ Err(_) => std::thread::sleep(Duration::from_millis(100)),+ }+ }+}++/// Stops the installed job, preserving its configuration for a later start.+/// A manually started daemon is never mistaken for the service we own.+pub fn stop() -> Result<()> {+ if cfg!(target_os = "macos") {+ let _ = Command::new("launchctl")+ .args(["bootout", &format!("gui/{}/{LABEL}", current_uid())])+ .stderr(Stdio::null())+ .status()?;+ } else if installed() {+ run("systemctl", &["--user", "stop", "codync-host.service"])?;+ }+ wait_for_host_exit()+}++pub fn start() -> Result<()> {+ if cfg!(target_os = "macos") {+ run("launchctl", &["bootstrap", &format!("gui/{}", current_uid()), &launchd_plist().to_string_lossy()])+ } else {+ run("systemctl", &["--user", "start", "codync-host.service"])+ }+}++/// Refuse to replace one installation while restarting a service owned by another.+pub fn require_executable(expected: &Path) -> Result<()> {+ let configured = if cfg!(target_os = "macos") {+ let output = Command::new("/usr/bin/plutil")+ .args(["-extract", "ProgramArguments.0", "raw", "-o", "-"])+ .arg(launchd_plist())+ .output()?;+ if !output.status.success() {+ bail!("cannot read the installed host service");+ }+ PathBuf::from(String::from_utf8(output.stdout)?.trim())+ } else {+ let unit = std::fs::read_to_string(systemd_unit())?;+ let command =+ unit.lines().find_map(|line| line.strip_prefix("ExecStart=")).context("service has no ExecStart")?;+ let args = shlex::split(command).context("invalid service ExecStart")?;+ PathBuf::from(args.first().context("service has no executable")?)+ };+ if configured.canonicalize()? != expected.canonicalize()? {+ bail!("the installed service runs another host binary; run that binary's update command");+ }+ Ok(())+}pub const DEFAULT_PORT: u16 = 19222;const LABEL: &str = "com.pokai.codync.host";@@ -89,6 +174,7 @@ pub fn install(port: u16) -> Result<()> {// Not loaded yet is the normal case here.let _ =Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{LABEL}")]).stderr(Stdio::null()).status();+ wait_for_host_exit()?;std::fs::write(&file, plist).with_context(|| format!("writing {}", file.display()))?;run("launchctl", &["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])?;} else {@@ -99,6 +185,8 @@ pub fn install(port: u16) -> Result<()> {create_parent(&file)?;std::fs::write(&file, unit).with_context(|| format!("writing {}", file.display()))?;run("systemctl", &["--user", "daemon-reload"])?;+ run("systemctl", &["--user", "stop", "codync-host.service"])?;+ wait_for_host_exit()?;run("systemctl", &["--user", "enable", "--now", "codync-host.service"])?;println!("Tip: `loginctl enable-linger $USER` keeps the host running while you're logged out.");}@@ -233,7 +321,7 @@ pub enum Device {/// Detected once; on macOS from `system_profiler`'s model name.pub fn device() -> Device {- static DEVICE: std::sync::OnceLock<Device> = std::sync::OnceLock::new();+ static DEVICE: OnceLock<Device> = OnceLock::new();*DEVICE.get_or_init(|| {if !cfg!(target_os = "macos") {return Device::Linux;diff --git a/host/src/update/install.rs b/host/src/update/install.rsnew file mode 100644index 00000000..a136a316--- /dev/null+++ b/host/src/update/install.rs@@ -0,0 +1,175 @@+use super::release;+use crate::service;+use anyhow::{Context, Result, bail, ensure};+use std::{future::Future, path::Path, time::Duration};++#[derive(Clone, Copy, Debug, serde::Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum Method {+ Standalone,+ AppBundle,+ Homebrew,+ Development,+}++pub fn method(executable: &Path) -> Method {+ let path = executable.to_string_lossy();+ if path.contains(".app/Contents/") {+ Method::AppBundle+ } else if path.contains("/Cellar/") || path.contains("/linuxbrew/") {+ Method::Homebrew+ } else if path.contains("/target/debug/") || path.contains("/target/release/") || cfg!(debug_assertions) {+ Method::Development+ } else {+ Method::Standalone+ }+}++pub fn require_standalone(executable: &Path) -> Result<()> {+ match method(executable) {+ Method::Standalone => Ok(()),+ Method::AppBundle => bail!("this host belongs to Codync.app; update the Mac app from Settings > Updates"),+ Method::Homebrew => bail!(+ "this host belongs to Homebrew; run `brew upgrade leepokai/codync/codync-host`, then `codync-host install`"+ ),+ Method::Development => bail!("this is a development build; rebuild it instead of replacing it with a release"),+ }+}++pub async fn health(port: u16) -> Option<serde_json::Value> {+ crate::http()+ .get(format!("http://127.0.0.1:{port}/health"))+ .timeout(Duration::from_secs(2))+ .send()+ .await+ .ok()?+ .error_for_status()+ .ok()?+ .json()+ .await+ .ok()+}++async fn verify_running(port: u16, version: &str, hash: &str, identity: Option<&str>) -> Result<()> {+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);+ loop {+ if let Some(health) = health(port).await+ && health["version"] == version+ && health["binaryHash"] == hash+ && identity.is_none_or(|id| health["computerId"] == id)+ {+ return Ok(());+ }+ ensure!(tokio::time::Instant::now() < deadline, "the updated host did not become healthy within 30 seconds");+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+}++/// The backup lives beside the executable, so replacement and rollback use+/// atomic rename on the same filesystem. It is retained if rollback fails.+pub async fn replace<Stop, Stopped, Verify, Verified, Restore, Restored>(+ target: &Path,+ candidate: &Path,+ stop: Stop,+ verify: Verify,+ restore: Restore,+) -> Result<()>+where+ Stop: FnOnce() -> Stopped,+ Stopped: Future<Output = Result<()>>,+ Verify: FnOnce() -> Verified,+ Verified: Future<Output = Result<()>>,+ Restore: FnOnce() -> Restored,+ Restored: Future<Output = Result<()>>,+{+ let backup = target.with_file_name(format!(".codync-host-backup-{}", uuid::Uuid::new_v4()));+ std::fs::hard_link(target, &backup).context("creating the rollback copy")?;+ if let Err(error) = stop().await {+ let _ = std::fs::remove_file(&backup);+ return Err(error.context("old host could not be stopped; executable was not replaced"));+ }+ let update = async {+ std::fs::rename(candidate, target).context("replacing the host executable")?;+ verify().await+ }+ .await;+ if let Err(error) = update {+ // Renaming a live executable is safe on Unix; processes retain their+ // original inode. restore() then stops the failed service and restarts it.+ std::fs::rename(&backup, target)+ .with_context(|| format!("update failed ({error:#}); restore the saved binary at {}", backup.display()))?;+ restore()+ .await+ .with_context(|| format!("update failed ({error:#}); restored the old binary but could not restart it"))?;+ bail!("update failed; restored the previous host: {error:#}");+ }+ std::fs::remove_file(backup)?;+ Ok(())+}++pub async fn apply(release: &release::Release, target: &Path, port: u16, force: bool) -> Result<()> {+ require_standalone(target)?;+ let managed = service::installed();+ if managed {+ service::require_executable(target)?;+ }+ let old_health = health(port).await;+ if !force {+ ensure!(+ old_health.as_ref().is_none_or(|h| h["busy"] == false),+ "host is busy or its activity is unknown; retry when idle, or use --force"+ );+ }+ if !managed {+ drop(service::lock_host().context("stop the manually started host before updating its executable")?);+ }+ let bytes = release::archive(release).await?;+ let stage = target.with_file_name(format!(".codync-host-update-{}", uuid::Uuid::new_v4()));+ let result = async {+ release::extract(&bytes, &release.platform, &stage)?;+ let output = tokio::process::Command::new(&stage).arg("--version").kill_on_drop(true).output();+ let output = tokio::time::timeout(Duration::from_secs(10), output).await??;+ ensure!(+ output.status.success()+ && String::from_utf8_lossy(&output.stdout).trim() == format!("codync-host {}", release.version),+ "downloaded executable reported the wrong version"+ );+ let old_hash = release::sha256(&std::fs::read(target)?);+ let new_hash = release::sha256(&std::fs::read(&stage)?);+ let identity = old_health.as_ref().and_then(|h| h["computerId"].as_str());+ // Recheck immediately before stopping; downloads can take minutes.+ if !force && managed {+ let current = health(port).await.context("cannot confirm the running host is idle")?;+ ensure!(current["busy"] == false, "host became busy while downloading; retry after its work finishes");+ }+ replace(+ target,+ &stage,+ || async {+ if managed {+ tokio::task::spawn_blocking(service::stop).await??;+ }+ Ok(())+ },+ || async {+ if managed {+ tokio::task::spawn_blocking(service::start).await??;+ verify_running(port, &release.version, &new_hash, identity).await?;+ }+ Ok(())+ },+ || async {+ if managed {+ tokio::task::spawn_blocking(service::stop).await??;+ tokio::task::spawn_blocking(service::start).await??;+ verify_running(port, env!("CARGO_PKG_VERSION"), &old_hash, identity).await?;+ }+ Ok(())+ },+ )+ .await+ }+ .await;+ let _ = std::fs::remove_file(stage);+ result+}diff --git a/host/src/update/mod.rs b/host/src/update/mod.rsnew file mode 100644index 00000000..4ace831f--- /dev/null+++ b/host/src/update/mod.rs@@ -0,0 +1,237 @@+//! Standalone host updates. App bundles and package managers retain ownership+//! of their binaries. A signed manifest is required before executing new code.+mod install;+mod release;+#[cfg(test)]+mod tests;++use crate::{hub::Hub, service};+use anyhow::{Context, Result, ensure};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::{path::Path, sync::Arc, time::Duration};++#[derive(Default, Deserialize, Serialize)]+struct Config {+ automatic: bool,+}++#[derive(Default, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+struct State {+ phase: String,+ available_version: Option<String>,+ checked_at: Option<i64>,+ error: Option<String>,+}++fn read<T: serde::de::DeserializeOwned + Default>(name: &str) -> Result<T> {+ match std::fs::read(service::data_dir().join(name)) {+ Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(T::default()),+ Err(error) => Err(error.into()),+ }+}++fn write(name: &str, value: &impl Serialize) -> Result<()> {+ let path = service::data_dir().join(name);+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(service::data_dir())?;+ std::fs::write(&temporary, serde_json::to_vec_pretty(value)?)?;+ std::fs::rename(temporary, path)?;+ Ok(())+}++fn lock() -> Result<std::fs::File> {+ std::fs::create_dir_all(service::data_dir())?;+ let file = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(service::data_dir().join("update.lock"))?;+ fs2::FileExt::try_lock_exclusive(&file).context("another host update is already running")?;+ Ok(file)+}++pub fn status() -> Result<Value> {+ let executable = std::env::current_exe()?.canonicalize()?;+ status_at(&executable)+}++fn status_at(executable: &Path) -> Result<Value> {+ let state: State = read("update-state.json")?;+ let config: Config = read("update-config.json")?;+ Ok(json!({+ "currentVersion": env!("CARGO_PKG_VERSION"), "method": install::method(executable),+ "automatic": config.automatic, "state": state,+ }))+}++pub fn set_automatic(enabled: bool) -> Result<Value> {+ let executable = std::env::current_exe()?.canonicalize()?;+ if enabled {+ install::require_standalone(&executable)?;+ ensure!(service::installed(), "install the background host service before enabling automatic updates");+ service::require_executable(&executable)?;+ }+ write("update-config.json", &Config { automatic: enabled })?;+ status()+}++pub async fn check() -> Result<Value> {+ let _lock = lock()?;+ let mut state: State = read("update-state.json")?;+ ensure!(!awaiting_worker(&state), "a host update is starting");+ state.checked_at = Some(crate::store::now_ms());+ match release::latest().await {+ Ok(release) => {+ state.available_version = (semver::Version::parse(&release.version)?+ > semver::Version::parse(env!("CARGO_PKG_VERSION"))?)+ .then_some(release.version);+ state.phase = if state.available_version.is_some() { "available" } else { "upToDate" }.into();+ state.error = None;+ }+ Err(error) => {+ state.phase = "failed".into();+ state.error = Some(format!("{error:#}"));+ write("update-state.json", &state)?;+ return Err(error);+ }+ }+ write("update-state.json", &state)?;+ status()+}++pub async fn apply(port: u16, force: bool, worker: bool) -> Result<Value> {+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);+ let _lock = loop {+ match lock() {+ Ok(lock) => break lock,+ Err(_) if worker && tokio::time::Instant::now() < deadline => {+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ Err(error) => return Err(error),+ }+ };+ let target = std::env::current_exe()?.canonicalize()?;+ install::require_standalone(&target)?;+ let mut state = State { phase: "checking".into(), checked_at: Some(crate::store::now_ms()), ..State::default() };+ write("update-state.json", &state)?;+ let result = async {+ let release = release::latest().await?;+ if semver::Version::parse(&release.version)? <= semver::Version::parse(env!("CARGO_PKG_VERSION"))? {+ state.phase = "upToDate".into();+ return Ok(());+ }+ state.available_version = Some(release.version.clone());+ state.phase = "installing".into();+ write("update-state.json", &state)?;+ install::apply(&release, &target, port, force).await?;+ state.phase = "complete".into();+ Ok::<_, anyhow::Error>(())+ }+ .await;+ if let Err(error) = &result {+ state.phase = "failed".into();+ state.error = Some(format!("{error:#}"));+ }+ write("update-state.json", &state)?;+ result?;+ // On Linux /proc/self/exe refers to the unlinked old inode after replacement.+ // Reuse the path captured before installing rather than resolving it again.+ let mut status = status_at(&target)?;+ if state.phase == "complete" {+ status["currentVersion"] = json!(state.available_version);+ }+ Ok(status)+}++/// The updater must live outside the daemon's job/cgroup. Otherwise stopping+/// the host would also kill the process responsible for starting its replacement.+pub fn spawn_worker(port: u16, force: bool) -> Result<()> {+ let _lock = lock()?;+ let previous: State = read("update-state.json")?;+ ensure!(!awaiting_worker(&previous), "a host update is already starting");+ let executable = std::env::current_exe()?.canonicalize()?;+ install::require_standalone(&executable)?;+ ensure!(+ service::installed(),+ "background updates require an installed host service; run `codync-host update` in a terminal"+ );+ service::require_executable(&executable)?;+ let mut args = vec!["update".to_owned(), "--worker".to_owned(), "--port".to_owned(), port.to_string()];+ if force {+ args.push("--force".to_owned());+ }+ let mut state = State { phase: "scheduled".into(), checked_at: Some(crate::store::now_ms()), ..previous };+ state.error = None;+ write("update-state.json", &state)?;+ if let Err(error) = spawn_job(&executable, &args) {+ state.phase = "failed".into();+ state.error = Some(format!("{error:#}"));+ write("update-state.json", &state)?;+ return Err(error);+ }+ Ok(())+}++fn awaiting_worker(state: &State) -> bool {+ state.phase == "scheduled" && state.checked_at.is_some_and(|at| crate::store::now_ms().saturating_sub(at) < 60_000)+}++fn spawn_job(executable: &Path, args: &[String]) -> Result<()> {+ let mut command;+ if cfg!(target_os = "linux") {+ command = std::process::Command::new("systemd-run");+ command+ .args(["--user", "--collect", "--unit=codync-host-update", "--property=Type=exec"])+ .arg(format!("--setenv=CODYNC_HOME={}", service::data_dir().display()))+ .arg("--")+ .arg(executable)+ .args(args);+ } else {+ // submit jobs do not restart on exit. Remove only a completed old job;+ // an active worker holds update.lock, acquired by our caller above.+ let _ = std::process::Command::new("launchctl").args(["remove", "com.pokai.codync.update"]).output();+ command = std::process::Command::new("launchctl");+ command+ .args(["submit", "-l", "com.pokai.codync.update", "-o"])+ .arg(service::data_dir().join("update.log"))+ .arg("-e")+ .arg(service::data_dir().join("update.log"))+ .args(["--", "/usr/bin/env"])+ .arg(format!("CODYNC_HOME={}", service::data_dir().display()))+ .arg(executable)+ .args(args);+ }+ let output = command.output().context("launching the independent host updater")?;+ ensure!(output.status.success(), "could not launch updater: {}", String::from_utf8_lossy(&output.stderr).trim());+ Ok(())+}++pub async fn automatic_loop(hub: Arc<Hub>) {+ let mut last_check = None;+ loop {+ tokio::time::sleep(Duration::from_secs(60)).await;+ let enabled = read::<Config>("update-config.json").is_ok_and(|c| c.automatic);+ if !enabled || hub.busy() {+ continue;+ }+ if last_check.is_some_and(|at: tokio::time::Instant| at.elapsed() < Duration::from_secs(24 * 60 * 60)) {+ continue;+ }+ last_check = Some(tokio::time::Instant::now());+ match check().await {+ Ok(status) if status["state"]["availableVersion"].is_string() => {+ let port = hub.port;+ match tokio::task::spawn_blocking(move || spawn_worker(port, false)).await {+ Ok(Ok(())) => {}+ result => tracing::warn!(?result, "could not start automatic host update"),+ }+ }+ Ok(_) => {}+ Err(error) => tracing::warn!(%error, "host update check failed"),+ }+ }+}diff --git a/host/src/update/release.rs b/host/src/update/release.rsnew file mode 100644index 00000000..03b9fcbf--- /dev/null+++ b/host/src/update/release.rs@@ -0,0 +1,140 @@+//! Signed release manifests pin platform, version, URL, size and SHA-256.+use anyhow::{Context, Result, bail, ensure};+use base64::{Engine as _, engine::general_purpose::STANDARD as B64};+use ed25519_dalek::{Signature, VerifyingKey};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::{fmt::Write as _, io::Read, path::Path, time::Duration};++pub const RELEASES: &str = "https://github.com/leepokai/Codync/releases";+pub const MAX_ARCHIVE: usize = 128 * 1024 * 1024;+const MAX_UNPACKED: u64 = 256 * 1024 * 1024;+const PUBLIC_KEY: &str = include_str!("../../../packaging/updates/host-public-key.txt");++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct Release {+ pub version: String,+ pub platform: String,+ pub url: String,+ pub sha256: String,+ pub size: u64,+}++pub fn platform() -> Result<String> {+ let os = match std::env::consts::OS {+ "macos" => "macos",+ "linux" => "linux",+ other => bail!("host updates do not support {other}"),+ };+ let arch = match std::env::consts::ARCH {+ "aarch64" => "arm64",+ "x86_64" => "x86_64",+ other => bail!("host updates do not support {other}"),+ };+ Ok(format!("{os}-{arch}"))+}++pub fn sha256(bytes: &[u8]) -> String {+ let mut hash = String::with_capacity(64);+ for byte in Sha256::digest(bytes) {+ let _ = write!(hash, "{byte:02x}");+ }+ hash+}++pub fn verify_manifest(bytes: &[u8], signature: &str, public_key: &str, platform: &str) -> Result<Release> {+ let key: [u8; 32] =+ B64.decode(public_key.trim())?.try_into().map_err(|_| anyhow::anyhow!("invalid update public key"))?;+ let signature = Signature::from_slice(&B64.decode(signature.trim())?)?;+ VerifyingKey::from_bytes(&key)?.verify_strict(bytes, &signature).context("release signature is invalid")?;+ let release: Release = serde_json::from_slice(bytes).context("reading the signed release manifest")?;+ let version = semver::Version::parse(&release.version).context("invalid release version")?;+ ensure!(version.pre.is_empty() && version.build.is_empty(), "only stable host releases are supported");+ ensure!(release.platform == platform, "release targets another platform");+ let expected = format!("{RELEASES}/download/v{version}/codync-host-{platform}.tar.gz");+ ensure!(release.url == expected, "release download URL does not match its version and platform");+ ensure!(release.size > 0 && release.size <= MAX_ARCHIVE as u64, "invalid release archive size");+ ensure!(+ release.sha256.len() == 64 && release.sha256.bytes().all(|b| b.is_ascii_hexdigit()),+ "invalid release checksum"+ );+ Ok(release)+}++pub async fn download(url: &str, limit: usize) -> Result<Vec<u8>> {+ let mut response = crate::http()+ .get(url)+ .header(reqwest::header::USER_AGENT, concat!("codync-host/", env!("CARGO_PKG_VERSION")))+ .timeout(Duration::from_secs(180))+ .send()+ .await?+ .error_for_status()?;+ ensure!(+ response.content_length().is_none_or(|size| size <= limit as u64),+ "update download exceeds the size limit"+ );+ let mut bytes = Vec::new();+ while let Some(chunk) = response.chunk().await? {+ ensure!(bytes.len().saturating_add(chunk.len()) <= limit, "update download exceeds the size limit");+ bytes.extend_from_slice(&chunk);+ }+ Ok(bytes)+}++pub async fn latest() -> Result<Release> {+ let platform = platform()?;+ // Resolve latest once. Fetching manifest and signature through separate+ // latest redirects could straddle two releases.+ let response = crate::http()+ .get("https://api.github.com/repos/leepokai/Codync/releases/latest")+ .header(reqwest::header::USER_AGENT, "codync-host")+ .timeout(Duration::from_secs(20))+ .send()+ .await?+ .error_for_status()?;+ let metadata: serde_json::Value = response.json().await?;+ let tag = metadata["tag_name"].as_str().context("latest release has no tag")?;+ let version = semver::Version::parse(tag.strip_prefix('v').context("invalid release tag")?)?;+ let url = format!("{RELEASES}/download/v{version}/codync-host-{platform}.update.json");+ let bytes = download(&url, 16 * 1024).await.context("this release has no valid signed host update manifest")?;+ let signature = download(&format!("{url}.sig"), 1024).await?;+ let release = verify_manifest(&bytes, std::str::from_utf8(&signature)?, PUBLIC_KEY, &platform)?;+ ensure!(release.version == version.to_string(), "manifest version differs from the selected release");+ Ok(release)+}++pub async fn archive(release: &Release) -> Result<Vec<u8>> {+ let bytes = download(&release.url, MAX_ARCHIVE).await?;+ ensure!(bytes.len() as u64 == release.size, "update archive size differs from signed manifest");+ ensure!(+ sha256(&bytes).eq_ignore_ascii_case(&release.sha256),+ "update archive checksum differs from signed manifest"+ );+ Ok(bytes)+}++/// Extract just the expected regular executable. Never unpack archive paths,+/// symlinks, permissions or other files into the user's installation.+pub fn extract(bytes: &[u8], platform: &str, destination: &Path) -> Result<()> {+ use std::os::unix::fs::PermissionsExt as _;+ let decoder = flate2::read::GzDecoder::new(bytes).take(MAX_UNPACKED);+ let mut archive = tar::Archive::new(decoder);+ let expected = format!("codync-host-{platform}/codync-host");+ let mut found = false;+ for entry in archive.entries()? {+ let mut entry = entry?;+ if entry.path()?.as_ref() != Path::new(&expected) {+ continue;+ }+ ensure!(!found && entry.header().entry_type().is_file(), "update executable must be a single regular file");+ ensure!(entry.size() > 0 && entry.size() < MAX_UNPACKED, "invalid update executable size");+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(destination)?;+ std::io::copy(&mut entry, &mut file)?;+ file.set_permissions(std::fs::Permissions::from_mode(0o755))?;+ file.sync_all()?;+ found = true;+ }+ ensure!(found, "release archive does not contain its host executable");+ Ok(())+}diff --git a/host/src/update/tests.rs b/host/src/update/tests.rsnew file mode 100644index 00000000..e3d9a93f--- /dev/null+++ b/host/src/update/tests.rs@@ -0,0 +1,159 @@+use super::{install, release};+use base64::{Engine as _, engine::general_purpose::STANDARD as B64};+use ed25519_dalek::{Signer as _, SigningKey};+use std::{+ path::PathBuf,+ sync::atomic::{AtomicBool, Ordering},+};++struct Directory(PathBuf);+impl Directory {+ fn new() -> Self {+ let path = std::env::temp_dir().join(format!("codync-update-test-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir(&path).unwrap();+ Self(path)+ }+}+impl Drop for Directory {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++fn manifest() -> release::Release {+ release::Release {+ version: "3.0.0".into(),+ platform: "linux-arm64".into(),+ url: format!("{}/download/v3.0.0/codync-host-linux-arm64.tar.gz", release::RELEASES),+ sha256: "a".repeat(64),+ size: 12,+ }+}++#[test]+fn only_signed_platform_matched_manifests_are_accepted() {+ let key = SigningKey::from_bytes(&[17; 32]);+ let public = B64.encode(key.verifying_key().as_bytes());+ let bytes = serde_json::to_vec(&manifest()).unwrap();+ let signature = B64.encode(key.sign(&bytes).to_bytes());+ assert_eq!(release::verify_manifest(&bytes, &signature, &public, "linux-arm64").unwrap().version, "3.0.0");+ assert!(release::verify_manifest(&bytes, &signature, &public, "macos-arm64").is_err());+ let mut altered = bytes.clone();+ altered[0] ^= 1;+ assert!(release::verify_manifest(&altered, &signature, &public, "linux-arm64").is_err());+ let other = B64.encode(SigningKey::from_bytes(&[18; 32]).verifying_key().as_bytes());+ assert!(release::verify_manifest(&bytes, &signature, &other, "linux-arm64").is_err());+ let mut redirected = manifest();+ redirected.url = "https://example.com/host.tar.gz".into();+ let redirected = serde_json::to_vec(&redirected).unwrap();+ let signature = B64.encode(key.sign(&redirected).to_bytes());+ assert!(release::verify_manifest(&redirected, &signature, &public, "linux-arm64").is_err());+}++fn archive(symlink: bool) -> Vec<u8> {+ let gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ let mut tar = tar::Builder::new(gzip);+ let mut header = tar::Header::new_gnu();+ header.set_mode(0o755);+ header.set_size(if symlink { 0 } else { 3 });+ if symlink {+ header.set_entry_type(tar::EntryType::Symlink);+ header.set_link_name("/tmp/unrelated-executable").unwrap();+ }+ header.set_cksum();+ let contents: &[u8] = if symlink { b"" } else { b"new" };+ tar.append_data(&mut header, "codync-host-linux-arm64/codync-host", contents).unwrap();+ tar.into_inner().unwrap().finish().unwrap()+}++#[test]+fn extraction_refuses_symlinks_and_only_creates_the_expected_binary() {+ let dir = Directory::new();+ let target = dir.0.join("candidate");+ assert!(release::extract(&archive(true), "linux-arm64", &target).is_err());+ assert!(!target.exists());+ assert!(release::extract(&archive(false), "macos-arm64", &target).is_err());+ release::extract(&archive(false), "linux-arm64", &target).unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"new");+ assert!(release::extract(&archive(false), "linux-arm64", &target).is_err());+}++#[tokio::test]+async fn a_failed_health_check_restores_the_previous_binary_and_service() {+ let dir = Directory::new();+ let target = dir.0.join("host");+ let candidate = dir.0.join("candidate");+ std::fs::write(&target, b"old").unwrap();+ std::fs::write(&candidate, b"new").unwrap();+ let restored = AtomicBool::new(false);+ let result = install::replace(+ &target,+ &candidate,+ || async { Ok(()) },+ || async {+ assert_eq!(std::fs::read(&target).unwrap(), b"new");+ anyhow::bail!("new host never answered")+ },+ || async {+ assert_eq!(std::fs::read(&target).unwrap(), b"old");+ restored.store(true, Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(result.is_err());+ assert!(restored.load(Ordering::SeqCst));+ assert_eq!(std::fs::read(&target).unwrap(), b"old");+ assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1);+}++#[tokio::test]+async fn failure_to_stop_the_old_host_never_replaces_its_executable() {+ let dir = Directory::new();+ let target = dir.0.join("host");+ let candidate = dir.0.join("candidate");+ std::fs::write(&target, b"old").unwrap();+ std::fs::write(&candidate, b"new").unwrap();+ let result = install::replace(+ &target,+ &candidate,+ || async { anyhow::bail!("host is still running") },+ || async { panic!("must not start the new host") },+ || async { panic!("old binary was never replaced") },+ )+ .await;+ assert!(result.is_err());+ assert_eq!(std::fs::read(target).unwrap(), b"old");+}++#[tokio::test]+async fn a_healthy_update_replaces_the_binary_and_removes_its_backup() {+ let dir = Directory::new();+ let target = dir.0.join("host");+ let candidate = dir.0.join("candidate");+ std::fs::write(&target, b"old").unwrap();+ std::fs::write(&candidate, b"new").unwrap();+ install::replace(+ &target,+ &candidate,+ || async { Ok(()) },+ || async { Ok(()) },+ || async { panic!("must not roll back a healthy update") },+ )+ .await+ .unwrap();+ assert_eq!(std::fs::read(target).unwrap(), b"new");+ assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1);+}++#[test]+fn app_and_homebrew_binaries_keep_their_installation_owner() {+ assert_eq!(+ install::method(std::path::Path::new("/Applications/Codync.app/Contents/MacOS/codync-host")),+ install::Method::AppBundle+ );+ assert_eq!(+ install::method(std::path::Path::new("/opt/homebrew/Cellar/codync-host/2.2.1/bin/codync-host")),+ install::Method::Homebrew+ );+}diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex e334f8e5..7de8af5d 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -86,6 +86,31 @@ impl Host {}}+#[tokio::test]+async fn termination_exits_with_an_open_event_stream() {+ let mut host = start_host().await;+ let health: Value = reqwest::get(format!("{}/health", host.base)).await.unwrap().json().await.unwrap();+ assert!(health["binaryHash"].as_str().is_some_and(|hash| hash.len() == 64));+ assert_eq!(+ health["binaryPath"],+ std::fs::canonicalize(env!("CARGO_BIN_EXE_codync-host")).unwrap().to_str().unwrap()+ );+ let stream =+ reqwest::Client::new().get(format!("{}/events", host.base)).bearer_auth(&host.token).send().await.unwrap();+ assert!(stream.status().is_success());+ assert!(Command::new("/bin/kill").args(["-TERM", &host.child.id().to_string()]).status().unwrap().success());+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ if let Some(status) = host.child.try_wait().unwrap() {+ assert!(status.success());+ break;+ }+ assert!(Instant::now() < deadline, "open SSE prevented host shutdown");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ drop(stream);+}+#[tokio::test]async fn turn_with_approval_reaches_a_final_reply() {if Command::new("python3").arg("--version").output().is_err() {diff --git a/packaging/updates/host-public-key.txt b/packaging/updates/host-public-key.txtnew file mode 100644index 00000000..c1a8e0d4--- /dev/null+++ b/packaging/updates/host-public-key.txt@@ -0,0 +1 @@+1vt0r7qYhSRzIxrBamVEYiJv5OaDS4crDkB4GDm4BMI=diff --git a/packaging/updates/macos-public-key.txt b/packaging/updates/macos-public-key.txtnew file mode 100644index 00000000..1d3a9c01--- /dev/null+++ b/packaging/updates/macos-public-key.txt@@ -0,0 +1 @@+/WvuKYw0ghkj3ExQbCejTquAcozuP1Llo2k8TIvx0Mc=diff --git a/packaging/updates/sign-host-release.py b/packaging/updates/sign-host-release.pynew file mode 100644index 00000000..d4320dfd--- /dev/null+++ b/packaging/updates/sign-host-release.py@@ -0,0 +1,52 @@+#!/usr/bin/env python3+"""Create a signed manifest for one standalone host release archive.++HOST_UPDATE_SIGNING_KEY contains a base64 Ed25519 seed. Only the public key is+committed. Requires cryptography (installed by the release workflow).+"""+import argparse+import base64+import hashlib+import json+import os+from pathlib import Path+import re++from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey+from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("archive", type=Path)+ parser.add_argument("--version", required=True)+ parser.add_argument("--platform", required=True, choices=["macos-arm64", "macos-x86_64", "linux-arm64", "linux-x86_64"])+ args = parser.parse_args()+ version = args.version.removeprefix("v")+ if not re.fullmatch(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version):+ parser.error("version must be a stable major.minor.patch release")+ name = f"codync-host-{args.platform}.tar.gz"+ if args.archive.name != name:+ parser.error(f"expected archive name {name}")+ key = Ed25519PrivateKey.from_private_bytes(base64.b64decode(os.environ["HOST_UPDATE_SIGNING_KEY"].strip(), validate=True))+ expected = Path(__file__).with_name("host-public-key.txt").read_text().strip()+ actual = base64.b64encode(key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)).decode()+ if actual != expected:+ raise SystemExit("HOST_UPDATE_SIGNING_KEY does not match the committed host public key")+ archive = args.archive.read_bytes()+ manifest = {+ "version": version,+ "platform": args.platform,+ "url": f"https://github.com/leepokai/Codync/releases/download/v{version}/{name}",+ "sha256": hashlib.sha256(archive).hexdigest(),+ "size": len(archive),+ }+ data = (json.dumps(manifest, indent=2) + "\n").encode()+ output = args.archive.with_name(f"codync-host-{args.platform}.update.json")+ output.write_bytes(data)+ output.with_suffix(output.suffix + ".sig").write_text(base64.b64encode(key.sign(data)).decode() + "\n")+ print(f"Signed {output.name}")+++if __name__ == "__main__":+ main()diff --git a/packaging/updates/verify-appcast.py b/packaging/updates/verify-appcast.pynew file mode 100644index 00000000..a7b94210--- /dev/null+++ b/packaging/updates/verify-appcast.py@@ -0,0 +1,38 @@+#!/usr/bin/env python3+"""Fail release packaging if Sparkle metadata does not describe the built app."""+import base64+from pathlib import Path+import plistlib+import sys+import xml.etree.ElementTree as ET+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey+++def main():+ feed, app, archive = map(Path, sys.argv[1:])+ info = plistlib.loads((app / "Contents/Info.plist").read_bytes())+ root = ET.parse(feed).getroot()+ namespace = "http://www.andymatuschak.org/xml-namespaces/sparkle"+ items = root.findall("./channel/item")+ assert len(items) == 1, "expected one current release"+ item = items[0]+ enclosure = item.find("enclosure")+ assert enclosure is not None+ version = item.findtext(f"{{{namespace}}}version") or enclosure.get(f"{{{namespace}}}version")+ assert version == info["CFBundleVersion"], "appcast build version differs from app"+ assert enclosure.get("length") == str(archive.stat().st_size), "appcast archive size is wrong"+ assert len(base64.b64decode(enclosure.attrib[f"{{{namespace}}}edSignature"], validate=True)) == 64+ expected = f"https://github.com/leepokai/Codync/releases/download/v{info['CFBundleShortVersionString']}/{archive.name}"+ assert enclosure.get("url") == expected, "appcast must point to this immutable release archive"+ public_key = Path(__file__).with_name("macos-public-key.txt").read_text().strip()+ Ed25519PublicKey.from_public_bytes(base64.b64decode(public_key, validate=True)).verify(+ base64.b64decode(enclosure.attrib[f"{{{namespace}}}edSignature"], validate=True),+ archive.read_bytes(),+ )+ assert info["SUPublicEDKey"] == public_key, "app has the wrong Sparkle public key"+ assert info["SUVerifyUpdateBeforeExtraction"] is True+ print("Sparkle appcast matches the signed app and release archive")+++if __name__ == "__main__":+ main()