Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(desktop): add signed native auto-updates (#7631)
Eric Hayes18aa16cd031d
diff --git a/.github/workflows/build_appimage_on_tag.yml b/.github/workflows/build_appimage_on_tag.ymlindex 0825fbfe14..d1000552c5 100644--- a/.github/workflows/build_appimage_on_tag.yml+++ b/.github/workflows/build_appimage_on_tag.yml@@ -39,6 +39,11 @@ jobs:shell: bashenv:RAW_REF: ${{ inputs.ref }}+ - name: Prepare desktop release identity+ run: nix develop --command bun apps/web/scripts/desktop-release.mjs prepare "$RAW_REF"+ shell: bash+ env:+ RAW_REF: ${{ inputs.ref }}- name: Build AppImage with Nixrun: |set -euo pipefail@@ -105,6 +110,7 @@ jobs:ficp -v "${appimages[@]}" artifacts/chmod 0755 artifacts/*.AppImage+ cp apps/web/tauri/desktop-release.json artifacts/linux-x86_64.release.json(cd artifacts && sha256sum -- *.AppImage > macro-appimage-SHA256SUMS)shell: bash- name: Upload macro-appimage-${{ steps.metadata.outputs.safe_tag }} artifact@@ -117,37 +123,3 @@ jobs:- name: Teardown Nixif: always()uses: './.github/actions/teardown-nix'- publish-appimage:- needs:- - build-appimage- name: Upload Release Artifacts- runs-on: ubuntu-latest- permissions:- contents: write- steps:- - id: metadata- name: Derive artifact metadata- run: |- set -euo pipefail- tag="${RAW_REF#refs/tags/}"- if [ -z "$tag" ]; then- tag="${GITHUB_REF_NAME:-untagged}"- fi- safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')- echo "tag=$tag" >> "$GITHUB_OUTPUT"- echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"- shell: bash- env:- RAW_REF: ${{ inputs.ref }}- - name: Download Build Artifacts- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0- with:- path: release-artifacts- merge-multiple: 'true'- - name: Upload Release Artifacts- if: startsWith(steps.metadata.outputs.tag, 'v')- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65- with:- tag_name: ${{ steps.metadata.outputs.tag }}- files: release-artifacts/*- fail_on_unmatched_files: 'true'diff --git a/.github/workflows/build_desktop_on_tag.yml b/.github/workflows/build_desktop_on_tag.ymlindex f74117879a..a956d9a72e 100644--- a/.github/workflows/build_desktop_on_tag.yml+++ b/.github/workflows/build_desktop_on_tag.yml@@ -102,6 +102,11 @@ jobs:shell: bashenv:RAW_REF: ${{ needs.resolve-ref.outputs.ref }}+ - name: Prepare desktop release identity+ run: nix develop --command bun apps/web/scripts/desktop-release.mjs prepare "$RAW_REF"+ shell: bash+ env:+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}- name: Build AppImage with Nixrun: |set -euo pipefail@@ -168,6 +173,7 @@ jobs:ficp -v "${appimages[@]}" artifacts/chmod 0755 artifacts/*.AppImage+ cp apps/web/tauri/desktop-release.json artifacts/linux-x86_64.release.json(cd artifacts && sha256sum -- *.AppImage > macro-appimage-SHA256SUMS)shell: bash- name: Upload macro-appimage-${{ steps.metadata.outputs.safe_tag }} artifact@@ -316,6 +322,11 @@ jobs:shell: bashenv:RAW_REF: ${{ needs.resolve-ref.outputs.ref }}+ - name: Prepare desktop release identity+ run: nix develop --command bun apps/web/scripts/desktop-release.mjs prepare "$RAW_REF"+ shell: bash+ env:+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}- name: Build DMG with Nixrun: |set -euo pipefail@@ -484,6 +495,10 @@ jobs:cp -v "${dmgs[@]}" artifacts/# Nix outputs are read-only; stapler must write Apple's ticket into the copy.chmod u+w artifacts/*.dmg+ mkdir -p updater-app+ cp -a result/Macro.app updater-app/+ chmod -R u+w updater-app/Macro.app+ cp apps/web/tauri/desktop-release.json artifacts/darwin-aarch64.release.jsonshell: bash- name: Validate signed DMGrun: |@@ -561,6 +576,20 @@ jobs:xcrun stapler validate "$dmg"spctl --assess --type open --context context:primary-signature --verbose=2 "$dmg"+ # The updater ships the app rather than the DMG. Notarize and staple that exact+ # final app too; stapling only the disk image does not staple the updater app.+ ditto -c -k --keepParent updater-app/Macro.app "$credentials_dir/updater-app.zip"+ xcrun notarytool submit "$credentials_dir/updater-app.zip" \+ --key "$credentials_dir/AuthKey.p8" --key-id "$key_id" --issuer "$issuer" \+ --wait --timeout 30m --output-format json > "$credentials_dir/app-submission.json"+ jq -e '.status == "Accepted"' "$credentials_dir/app-submission.json" > /dev/null+ xcrun stapler staple updater-app/Macro.app+ xcrun stapler validate updater-app/Macro.app+ codesign --verify --deep --strict --verbose=2 updater-app/Macro.app+ spctl --assess --type execute --verbose=2 updater-app/Macro.app+ version=$(jq -er '.version' apps/web/tauri/desktop-release.json)+ COPYFILE_DISABLE=1 tar -czf "artifacts/Macro-${version}-aarch64-darwin.app.tar.gz" -C updater-app Macro.app+# Stapling changes the DMG bytes, so checksum the final distributable.(cd artifacts && shasum -a 256 -- *.dmg > macro-dmg-SHA256SUMS)shell: bash@@ -578,11 +607,22 @@ jobs:- resolve-ref- build-appimage- build-dmg- name: Upload Release Artifacts+ if: startsWith(needs.resolve-ref.outputs.ref, 'refs/tags/v')+ name: Sign and publish desktop updatesruns-on: ubuntu-latestpermissions:contents: write+ concurrency:+ group: desktop-stable-publish+ cancel-in-progress: falsesteps:+ - name: Checkout Repo+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10+ with:+ ref: ${{ needs.resolve-ref.outputs.ref }}+ persist-credentials: 'false'+ - name: Setup Nix+ uses: './.github/actions/setup-nix'- id: metadataname: Derive artifact metadatarun: |@@ -602,13 +642,128 @@ jobs:with:path: release-artifactsmerge-multiple: 'true'- - name: Upload Release Artifacts- if: startsWith(steps.metadata.outputs.tag, 'v')- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65- with:- tag_name: ${{ steps.metadata.outputs.tag }}- files: release-artifacts/*- fail_on_unmatched_files: 'true'+ - name: Sign updater artifacts+ run: |+ set -euo pipefail++ # All private material stays on the ephemeral runner, outside Nix derivations.+ umask 077+ credentials_dir=$(mktemp -d)+ trap 'rm -rf "$credentials_dir"' EXIT+ curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=macos-release&config=prd&format=json&secrets=TAURI_SIGNING_PRIVATE_KEY,TAURI_SIGNING_PRIVATE_KEY_PASSWORD' \+ > "$credentials_dir/secrets.json"+ jq -er '.TAURI_SIGNING_PRIVATE_KEY | strings | select(length > 0)' \+ "$credentials_dir/secrets.json" > "$credentials_dir/updater.key"+ export TAURI_SIGNING_PRIVATE_KEY_PATH="$credentials_dir/updater.key"+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD=$(jq -r '.TAURI_SIGNING_PRIVATE_KEY_PASSWORD // ""' "$credentials_dir/secrets.json")+ export TAURI_SIGNING_PRIVATE_KEY_PASSWORD++ # Verify against the public key compiled into BOTH packages before publishing.+ jq -er '.publicKey | select(length > 0)' release-artifacts/darwin-aarch64.release.json > "$credentials_dir/mac.pub"+ jq -er '.publicKey | select(length > 0)' release-artifacts/linux-x86_64.release.json > "$credentials_dir/linux.pub"+ cmp "$credentials_dir/mac.pub" "$credentials_dir/linux.pub"+ base64 --decode "$credentials_dir/mac.pub" > "$credentials_dir/minisign.pub"+ if ! gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --json assets > "$credentials_dir/release.json"; then+ # Reading the collection must succeed before treating the version as absent.+ gh api --paginate --slurp "repos/$RELEASE_REPOSITORY/releases" > "$credentials_dir/releases.json"+ if jq -e --arg tag "$RELEASE_TAG" '.[][] | select(.tag_name == $tag)' "$credentials_dir/releases.json" >/dev/null; then+ echo "Could not inspect existing release assets" >&2+ exit 1+ fi+ printf '{"assets":[]}' > "$credentials_dir/release.json"+ fi+ shopt -s nullglob+ artifacts=(release-artifacts/*.app.tar.gz release-artifacts/*.AppImage)+ if [ "${#artifacts[@]}" -ne 2 ]; then+ echo "Expected one macOS and one Linux updater artifact" >&2+ exit 1+ fi+ for artifact in "${artifacts[@]}"; do+ name=$(basename "$artifact")+ if jq -e --arg name "$name.sig" '.assets | any(.name == $name)' "$credentials_dir/release.json" >/dev/null; then+ # Signatures include signing time. Reuse a previously published signature+ # only after checking both the immutable package bytes and its signature.+ gh release download "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --pattern "$name" --pattern "$name.sig" --dir "$credentials_dir"+ cmp "$artifact" "$credentials_dir/$name"+ cp "$credentials_dir/$name.sig" "$artifact.sig"+ else+ nix shell --inputs-from . nixpkgs#cargo-tauri --command cargo-tauri signer sign "$artifact"+ fi+ base64 --decode "$artifact.sig" > "$credentials_dir/artifact.minisig"+ nix shell --inputs-from . nixpkgs#minisign --command minisign \+ -Vm "$artifact" -p "$credentials_dir/minisign.pub" -x "$credentials_dir/artifact.minisig"+ done+ shell: bash+ env:+ DOPPLER_TOKEN: ${{ secrets.MACOS_RELEASE_DOPPLER_TOKEN }}+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ steps.metadata.outputs.tag }}+ RELEASE_REPOSITORY: ${{ github.repository }}+ - name: Publish desktop release and update feed+ run: |+ set -euo pipefail++ nix develop --command bun apps/web/scripts/desktop-release.mjs manifest \+ release-artifacts "$RELEASE_TAG" "$RELEASE_REPOSITORY"++ # Refuse to overwrite release assets: the manifest may already reference them.+ # A failed publication can be resumed if every existing asset has identical bytes.+ if ! gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" >/dev/null 2>&1; then+ gh release create "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --verify-tag \+ --title "Macro $RELEASE_TAG" --notes "Desktop release $RELEASE_TAG" --latest=false+ fi+ work_dir=$(mktemp -d)+ trap 'rm -rf "$work_dir"' EXIT+ gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --json assets > "$work_dir/release.json"+ for file in release-artifacts/*; do+ name=$(basename "$file")+ # The mutable feed is published only after the immutable packages.+ [ "$name" != latest.json ] || continue+ if jq -e --arg name "$name" '.assets | any(.name == $name)' "$work_dir/release.json" >/dev/null; then+ gh release download "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --pattern "$name" --dir "$work_dir"+ cmp "$file" "$work_dir/$name"+ else+ gh release upload "$RELEASE_TAG" "$file" --repo "$RELEASE_REPOSITORY"+ fi+ done++ # A dedicated prerelease hosts only the mutable pointer. It never becomes the+ # public download page's latest release, nor follows SDK/daemon release tags.+ if gh release view desktop-stable --repo "$RELEASE_REPOSITORY" --json assets > "$work_dir/channel.json"; then+ if jq -e '.assets | any(.name == "latest.json")' "$work_dir/channel.json" >/dev/null; then+ gh release download desktop-stable --repo "$RELEASE_REPOSITORY" --pattern latest.json --dir "$work_dir"+ result=0+ nix develop --command bun apps/web/scripts/desktop-release.mjs newer \+ release-artifacts/latest.json "$work_dir/latest.json" || result=$?+ if [ "$result" -eq 2 ]; then+ echo "A matching or newer desktop release is already promoted."+ exit 0+ fi+ [ "$result" -eq 0 ] || exit "$result"+ fi+ else+ # Do not mistake an authentication/network error for an absent release.+ gh api --paginate --slurp "repos/$RELEASE_REPOSITORY/releases" > "$work_dir/releases.json"+ if jq -e '.[][] | select(.tag_name == "desktop-stable")' "$work_dir/releases.json" >/dev/null; then+ echo "Could not read the existing desktop update channel" >&2+ exit 1+ fi+ gh release create desktop-stable --repo "$RELEASE_REPOSITORY" --target "$RELEASE_TAG" \+ --prerelease --latest=false --title "Desktop stable update feed" \+ --notes "Update metadata only. Download installers from a versioned desktop release."+ fi+ gh release upload desktop-stable release-artifacts/latest.json --repo "$RELEASE_REPOSITORY" --clobber+ gh release edit "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --latest+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ steps.metadata.outputs.tag }}+ RELEASE_REPOSITORY: ${{ github.repository }}+ - name: Teardown Nix+ if: always()+ uses: './.github/actions/teardown-nix'concurrency:group: desktop-${{ inputs.ref || (github.event.ref_type == 'tag' && github.event.ref || github.ref_name) }}cancel-in-progress: truediff --git a/.github/workflows/build_dmg_on_tag.yml b/.github/workflows/build_dmg_on_tag.ymlindex 0d35b9456d..8fdd374f00 100644--- a/.github/workflows/build_dmg_on_tag.yml+++ b/.github/workflows/build_dmg_on_tag.yml@@ -143,6 +143,11 @@ jobs:shell: bashenv:RAW_REF: ${{ inputs.ref }}+ - name: Prepare desktop release identity+ run: nix develop --command bun apps/web/scripts/desktop-release.mjs prepare "$RAW_REF"+ shell: bash+ env:+ RAW_REF: ${{ inputs.ref }}- name: Build DMG with Nixrun: |set -euo pipefail@@ -311,6 +316,10 @@ jobs:cp -v "${dmgs[@]}" artifacts/# Nix outputs are read-only; stapler must write Apple's ticket into the copy.chmod u+w artifacts/*.dmg+ mkdir -p updater-app+ cp -a result/Macro.app updater-app/+ chmod -R u+w updater-app/Macro.app+ cp apps/web/tauri/desktop-release.json artifacts/darwin-aarch64.release.jsonshell: bash- name: Validate signed DMGrun: |@@ -388,6 +397,20 @@ jobs:xcrun stapler validate "$dmg"spctl --assess --type open --context context:primary-signature --verbose=2 "$dmg"+ # The updater ships the app rather than the DMG. Notarize and staple that exact+ # final app too; stapling only the disk image does not staple the updater app.+ ditto -c -k --keepParent updater-app/Macro.app "$credentials_dir/updater-app.zip"+ xcrun notarytool submit "$credentials_dir/updater-app.zip" \+ --key "$credentials_dir/AuthKey.p8" --key-id "$key_id" --issuer "$issuer" \+ --wait --timeout 30m --output-format json > "$credentials_dir/app-submission.json"+ jq -e '.status == "Accepted"' "$credentials_dir/app-submission.json" > /dev/null+ xcrun stapler staple updater-app/Macro.app+ xcrun stapler validate updater-app/Macro.app+ codesign --verify --deep --strict --verbose=2 updater-app/Macro.app+ spctl --assess --type execute --verbose=2 updater-app/Macro.app+ version=$(jq -er '.version' apps/web/tauri/desktop-release.json)+ COPYFILE_DISABLE=1 tar -czf "artifacts/Macro-${version}-aarch64-darwin.app.tar.gz" -C updater-app Macro.app+# Stapling changes the DMG bytes, so checksum the final distributable.(cd artifacts && shasum -a 256 -- *.dmg > macro-dmg-SHA256SUMS)shell: bash@@ -400,37 +423,3 @@ jobs:path: artifacts/*if-no-files-found: errorretention-days: '30'- publish-dmg:- needs:- - build-dmg- name: Upload Release Artifacts- runs-on: ubuntu-latest- permissions:- contents: write- steps:- - id: metadata- name: Derive artifact metadata- run: |- set -euo pipefail- tag="${RAW_REF#refs/tags/}"- if [ -z "$tag" ]; then- tag="${GITHUB_REF_NAME:-untagged}"- fi- safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')- echo "tag=$tag" >> "$GITHUB_OUTPUT"- echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"- shell: bash- env:- RAW_REF: ${{ inputs.ref }}- - name: Download Build Artifacts- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0- with:- path: release-artifacts- merge-multiple: 'true'- - name: Upload Release Artifacts- if: startsWith(steps.metadata.outputs.tag, 'v')- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65- with:- tag_name: ${{ steps.metadata.outputs.tag }}- files: release-artifacts/*- fail_on_unmatched_files: 'true'diff --git a/apps/web/scripts/desktop-release.mjs b/apps/web/scripts/desktop-release.mjsnew file mode 100644index 0000000000..2d0924e8f0--- /dev/null+++ b/apps/web/scripts/desktop-release.mjs@@ -0,0 +1,103 @@+import { execFileSync } from 'node:child_process';+import { readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';++const CONFIG = 'apps/web/tauri/desktop-release.json';+const TARGETS = {+ 'darwin-aarch64': '-aarch64-darwin.app.tar.gz',+ 'linux-x86_64': '-x86_64-linux.AppImage',+};++/** Map existing four-part desktop tags to sortable SemVer and OTA build IDs. */+export function releaseIdentity(ref) {+ const tag = ref.replace(/^refs\/tags\//, '');+ const calendar = /^v(\d{4})\.(\d{1,2})\.(\d{1,2})\.(\d{1,4})$/.exec(tag);+ let parts;+ if (calendar) {+ const [year, month, day, revision] = calendar.slice(1).map(Number);+ const date = new Date(Date.UTC(year, month - 1, day));+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {+ throw new Error(`Invalid release date: ${tag}`);+ }+ parts = [year, month * 100 + day, revision];+ } else {+ const semver = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(tag);+ if (!semver) throw new Error(`Expected vMAJOR.MINOR.PATCH or vYEAR.MONTH.DAY.REVISION: ${tag}`);+ parts = semver.slice(1).map(Number);+ }+ if (parts.some((part) => part < 0 || part > 9999)) throw new Error('Release version components must be between 0 and 9999');+ const [major, minor, patch] = parts;+ const nativeBuild = major * 100_000_000 + minor * 10_000 + patch;+ if (nativeBuild === 0) throw new Error('Release build must be positive');+ return { tag, version: parts.join('.'), nativeBuild };+}++export function isNewer(candidate, current) {+ const parse = (version) => {+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`Invalid feed version: ${version}`);+ return version.split('.').map(Number);+ };+ const a = parse(candidate);+ const b = parse(current);+ for (let i = 0; i < a.length; i++) {+ if (a[i] !== b[i]) return a[i] > b[i];+ }+ return false;+}++export function createManifest(directory, tag, repository) {+ const identity = releaseIdentity(tag);+ if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) throw new Error('Invalid release repository');+ const files = readdirSync(directory);+ const platforms = {};+ for (const [target, suffix] of Object.entries(TARGETS)) {+ const metadata = JSON.parse(readFileSync(join(directory, `${target}.release.json`), 'utf8'));+ if (!metadata.enabled || metadata.version !== identity.version || metadata.nativeBuild !== identity.nativeBuild) {+ throw new Error(`Packaged identity disagrees with release tag for ${target}`);+ }+ const matches = files.filter((name) => name === `Macro-${identity.version}${suffix}`);+ if (matches.length !== 1) throw new Error(`Missing updater artifact for ${target}`);+ const name = matches[0];+ const signature = readFileSync(join(directory, `${name}.sig`), 'utf8').trim();+ if (!signature) throw new Error(`Missing signature for ${target}`);+ platforms[target] = {+ url: `https://github.com/${repository}/releases/download/${identity.tag}/${name}`,+ signature,+ };+ }+ return { version: identity.version, notes: `Macro ${identity.tag}`, platforms };+}++function main([command, ...args]) {+ if (command === 'prepare') {+ const [ref] = args;+ if (!ref) throw new Error('Missing build ref');+ const config = JSON.parse(readFileSync(CONFIG, 'utf8'));+ const release = ref.startsWith('refs/tags/') || /^v\d/.test(ref);+ const commitSeconds = Number(execFileSync('git', ['log', '-1', '--format=%ct'], { encoding: 'utf8' }).trim());+ if (!Number.isSafeInteger(commitSeconds) || commitSeconds <= 0) throw new Error('Missing source commit timestamp');+ if (release) {+ Object.assign(config, releaseIdentity(ref));+ if (!config.publicKey.trim()) throw new Error('The desktop updater public key must be configured before release');+ }+ config.enabled = release;+ config.bundleBuild = commitSeconds * 1000;+ writeFileSync(CONFIG, `${JSON.stringify(config, null, 2)}\n`);+ } else if (command === 'manifest') {+ const [directory, tag, repository] = args;+ writeFileSync(join(directory, 'latest.json'), `${JSON.stringify(createManifest(directory, tag, repository), null, 2)}\n`);+ } else if (command === 'newer') {+ const [candidatePath, currentPath] = args;+ const candidate = JSON.parse(readFileSync(candidatePath, 'utf8'));+ const current = JSON.parse(readFileSync(currentPath, 'utf8'));+ // Exit 2 distinguishes a superseded/equal release from validation/network errors.+ if (!isNewer(candidate.version, current.version)) process.exitCode = 2;+ } else {+ throw new Error('Usage: desktop-release.mjs prepare REF | manifest DIR TAG REPO | newer CANDIDATE CURRENT');+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {+ main(process.argv.slice(2));+}diff --git a/apps/web/scripts/desktop-release.test.ts b/apps/web/scripts/desktop-release.test.tsnew file mode 100644index 0000000000..3d19806793--- /dev/null+++ b/apps/web/scripts/desktop-release.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, test } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createManifest, isNewer, releaseIdentity } from './desktop-release.mjs';++describe('desktop releases', () => {+ test('maps calendar tags without losing revision ordering', () => {+ expect(releaseIdentity('refs/tags/v2026.10.6.12')).toEqual({+ tag: 'v2026.10.6.12', version: '2026.1006.12', nativeBuild: 202610060012,+ });+ expect(isNewer('2026.1006.12', '2026.1006.9')).toBe(true);+ expect(isNewer('2026.1007.0', '2026.1006.9999')).toBe(true);+ expect(isNewer('2026.1006.12', '2026.1006.12')).toBe(false);+ expect(isNewer('2.5.0', '2026.1006.12')).toBe(false);+ });++ test('rejects malformed tags and impossible dates', () => {+ for (const tag of ['v2026.2.30.1', 'v2026.13.1.1', 'v1.2.3-beta', 'main', 'v1.2.10000', 'v0.0.0']) {+ expect(() => releaseIdentity(tag)).toThrow();+ }+ });++ const directories: string[] = [];+ afterEach(() => { for (const dir of directories.splice(0)) rmSync(dir, { recursive: true }); });++ test('requires both signed platform artifacts with the packaged version', () => {+ const dir = mkdtempSync(join(tmpdir(), 'macro-desktop-release-'));+ directories.push(dir);+ const tag = 'v2026.10.6.1';+ const identity = releaseIdentity(tag);+ for (const [target, suffix] of [['darwin-aarch64', 'aarch64-darwin.app.tar.gz'], ['linux-x86_64', 'x86_64-linux.AppImage']]) {+ const name = `Macro-${identity.version}-${suffix}`;+ writeFileSync(join(dir, name), 'artifact');+ writeFileSync(join(dir, `${name}.sig`), 'signature');+ writeFileSync(join(dir, `${target}.release.json`), JSON.stringify({ ...identity, enabled: true }));+ }+ const manifest = createManifest(dir, tag, 'macro-inc/macro');+ expect(Object.keys(manifest.platforms)).toEqual(['darwin-aarch64', 'linux-x86_64']);+ expect(manifest.platforms['darwin-aarch64'].url).toContain('/v2026.10.6.1/Macro-2026.1006.1-');+ rmSync(join(dir, 'Macro-2026.1006.1-x86_64-linux.AppImage.sig'));+ expect(() => createManifest(dir, tag, 'macro-inc/macro')).toThrow();+ });+});diff --git a/apps/web/scripts/desktop-signing.test.ts b/apps/web/scripts/desktop-signing.test.tsnew file mode 100644index 0000000000..4c9c97281d--- /dev/null+++ b/apps/web/scripts/desktop-signing.test.ts@@ -0,0 +1,79 @@+import { afterEach, expect, test, vi } from 'vitest';+import { spawn } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const directories: string[] = [];+afterEach(() => {+ vi.unstubAllEnvs();+ for (const directory of directories.splice(0)) rmSync(directory, { recursive: true });+});++test('publication retries reuse signatures and reject changed package bytes', async () => {+ const directory = mkdtempSync(join(tmpdir(), 'macro-signing-retry-'));+ directories.push(directory);+ const bin = join(directory, 'bin');+ const artifacts = join(directory, 'release-artifacts');+ const published = join(directory, 'published');+ const startup = join(directory, 'shell-startup.sh');+ writeFileSync(startup, 'echo "Inherited shell startup executed" >&2\nexit 97\n');+ vi.stubEnv('BASH_ENV', startup);+ vi.stubEnv('ENV', startup);+ for (const path of [bin, artifacts, published]) mkdirSync(path);+ const names = ['Macro-test.app.tar.gz', 'Macro-test.AppImage'];+ const signature = Buffer.from('previously published signature').toString('base64');+ for (const name of names) {+ writeFileSync(join(artifacts, name), 'immutable package');+ writeFileSync(join(published, name), 'immutable package');+ writeFileSync(join(published, `${name}.sig`), signature);+ }+ for (const target of ['darwin-aarch64', 'linux-x86_64']) {+ writeFileSync(join(artifacts, `${target}.release.json`), JSON.stringify({ publicKey: Buffer.from('test key').toString('base64') }));+ }+ const executable = (name: string, body: string) => writeFileSync(join(bin, name), `#!/usr/bin/env bash\nset -euo pipefail\n${body}\n`, { mode: 0o755 });+ executable('curl', `printf '%s' '{"TAURI_SIGNING_PRIVATE_KEY":"test-only-unused-key"}'`);+ executable('gh', `+if [ "$1 $2" = 'release view' ]; then+ printf '%s' '{"assets":[{"name":"Macro-test.app.tar.gz.sig"},{"name":"Macro-test.AppImage.sig"}]}'+elif [ "$1 $2" = 'release download' ]; then+ patterns=()+ while [ "$#" -gt 0 ]; do+ case "$1" in+ --pattern) patterns+=("$2"); shift 2 ;;+ --dir) destination="$2"; shift 2 ;;+ *) shift ;;+ esac+ done+ for name in "\${patterns[@]}"; do cp "$TEST_PUBLISHED/$name" "$destination/$name"; done+else+ exit 1+fi`);+ // Verification is covered cryptographically by the Rust fixture tests.+ // This mock forbids signing again, the source of the publication retry bug.+ executable('nix', `+case "$*" in+ *'cargo-tauri signer sign'*) echo 'Unexpected re-signing' >&2; exit 1 ;;+ *'minisign -Vm'*) echo verified >> "$TEST_VERIFICATIONS" ;;+ *) exit 1 ;;+esac`);+ const script = resolve(dirname(fileURLToPath(import.meta.url)), '../../../tooling/xtask/crates/xtask_workflows/src/workflows/scripts/sign_desktop_updates.sh');+ const run = () => new Promise<{ code: number | null; stderr: string }>((resolve, reject) => {+ const child = spawn('bash', [script], {+ cwd: directory,+ // CI's Nix BASH_ENV resets PATH, bypassing the command fixtures.+ env: { ...process.env, BASH_ENV: undefined, ENV: undefined, PATH: `${bin}:${process.env.PATH}`, DOPPLER_TOKEN: 'test-only', RELEASE_TAG: 'v1.0.0', RELEASE_REPOSITORY: 'test/test', TEST_PUBLISHED: published, TEST_VERIFICATIONS: join(directory, 'verified') },+ stdio: ['ignore', 'ignore', 'pipe'],+ });+ let stderr = '';+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });+ child.on('error', reject);+ child.on('close', (code) => resolve({ code, stderr }));+ });+ expect(await run()).toEqual({ code: 0, stderr: '' });+ for (const name of names) expect(readFileSync(join(artifacts, `${name}.sig`), 'utf8')).toBe(signature);+ expect(readFileSync(join(directory, 'verified'), 'utf8').trim().split('\n')).toHaveLength(2);+ writeFileSync(join(artifacts, names[0]), 'changed package');+ expect((await run()).code).not.toBe(0);+});diff --git a/apps/web/src/components/app/sidebar-next/footer-actions.tsx b/apps/web/src/components/app/sidebar-next/footer-actions.tsxindex f22adbe836..5effd6f187 100644--- a/apps/web/src/components/app/sidebar-next/footer-actions.tsx+++ b/apps/web/src/components/app/sidebar-next/footer-actions.tsx@@ -8,11 +8,13 @@ import { useSettingsTabAvailable } from '@core/constant/settingsTabsConfig';import { useEmail, useUserId } from '@core/context/user';import { TOKENS } from '@core/hotkey/tokens';import DeviceMobileDownloadIcon from '@icon/device-mobile-download.svg';+import { useTauri } from '@macro/tauri';import GearIcon from '@phosphor/gear.svg';import GearFillIcon from '@phosphor-fill/gear-fill.svg';import { isRealNamePart, useOwnUserName } from '@queries/auth/user-name-self';import { Button, cn, pressHandlers } from '@ui';import { createEffect, createMemo, Show } from 'solid-js';+import { NativeUpdateButton } from './native-update-button';import { NavGlyph } from './nav-glyph';/**@@ -80,14 +82,15 @@ const MobileAppButton = () => {};/**- * The rail's bottom actions: the mobile app link, then Settings, opened like- * any other rail view. The gear carries the signed-in account's photo as a- * badge, so people with several accounts can still tell which one they are in.+ * The rail's bottom actions: a ready app update, the mobile app link, then+ * Settings, opened like any other rail view. The gear carries the account photo+ * as a badge, so people with several accounts can tell which one they are in.*/export const FooterActions = (props: {onMenuOpenChange?: (open: boolean) => void;}) => {const analytics = useAnalytics();+ const tauri = useTauri();const { openSettings, openSettingsInSplit, settingsOpen, activeTabId } =useSettingsState();const userId = useUserId();@@ -115,6 +118,16 @@ export const FooterActions = (props: {return (<div class="flex w-full shrink-0 flex-col items-center gap-1">+ <Show when={tauri}>+ {(native) => (+ <Show when={native().nativeUpdateStatus().status === 'Ready'}>+ <NativeUpdateButton+ preparing={native().nativeUpdatePreparing()}+ onRestart={() => void native().restartNativeUpdate()}+ />+ </Show>+ )}+ </Show><MobileAppButton /><SidebarOpenInSplitMenucontent={() => SETTINGS_CONTENT}diff --git a/apps/web/src/components/app/sidebar-next/native-update-button.tsx b/apps/web/src/components/app/sidebar-next/native-update-button.tsxnew file mode 100644index 0000000000..0f17bcef4f--- /dev/null+++ b/apps/web/src/components/app/sidebar-next/native-update-button.tsx@@ -0,0 +1,44 @@+import ArrowCircleUpIcon from '@phosphor/arrow-circle-up.svg';+import { Button } from '@ui';+import { createSignal, lazy, Show, Suspense } from 'solid-js';+import { NavGlyph } from './nav-glyph';++const NativeUpdateDialog = lazy(() => import('./native-update-dialog'));++export function NativeUpdateButton(props: {+ preparing: boolean;+ onRestart: () => void;+}) {+ const [open, setOpen] = createSignal(false);+ let trigger: HTMLButtonElement | undefined;++ return (+ <>+ <Button+ ref={trigger}+ variant="accent"+ size="icon-md"+ class="size-10 cursor-default rounded-xl"+ label="Update available"+ tooltip="Update available"+ tooltipPlacement="right"+ aria-haspopup="dialog"+ aria-expanded={open()}+ data-sidebar-next-item="app-update"+ onClick={() => setOpen(true)}+ >+ <NavGlyph icon={ArrowCircleUpIcon} class="size-6" />+ </Button>+ <Show when={open()}>+ <Suspense>+ <NativeUpdateDialog+ preparing={props.preparing}+ onClose={() => setOpen(false)}+ onRestoreFocus={() => trigger?.focus()}+ onRestart={props.onRestart}+ />+ </Suspense>+ </Show>+ </>+ );+}diff --git a/apps/web/src/components/app/sidebar-next/native-update-dialog.tsx b/apps/web/src/components/app/sidebar-next/native-update-dialog.tsxnew file mode 100644index 0000000000..a1c7731efe--- /dev/null+++ b/apps/web/src/components/app/sidebar-next/native-update-dialog.tsx@@ -0,0 +1,63 @@+import ArrowCircleUpIcon from '@phosphor/arrow-circle-up.svg';+import { Button, Dialog, Surface } from '@ui';++export default function NativeUpdateDialog(props: {+ preparing: boolean;+ onClose: () => void;+ onRestoreFocus: () => void;+ onRestart: () => void;+}) {+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !props.preparing) props.onClose();+ }}+ onCloseAutoFocus={(event) => {+ // The sidebar button lives outside this lazily mounted dialog root.+ event.preventDefault();+ props.onRestoreFocus();+ }}+ position="center"+ animate+ class="w-100 max-w-[calc(100vw-16px)]"+ >+ <Surface depth={2}>+ <div class="flex flex-col gap-5 p-6" aria-busy={props.preparing}>+ <div class="flex flex-col gap-2">+ <ArrowCircleUpIcon+ class="mb-1 size-8 text-accent"+ aria-hidden="true"+ />+ <Dialog.Title class="text-lg font-semibold text-ink">+ Update Macro+ </Dialog.Title>+ <Dialog.Description class="text-sm leading-5 text-ink-muted">+ A new version of Macro is ready. Restart to install it, or keep+ working and it will update when you quit.+ </Dialog.Description>+ </div>+ <div class="flex justify-end gap-2">+ <Dialog.CloseButton+ as={Button}+ aria-label="Later"+ variant="strong"+ size="sm"+ disabled={props.preparing}+ >+ Later+ </Dialog.CloseButton>+ <Button+ variant="accent"+ size="sm"+ disabled={props.preparing}+ onClick={props.onRestart}+ >+ {props.preparing ? 'Preparing to restart…' : 'Restart and update'}+ </Button>+ </div>+ </div>+ </Surface>+ </Dialog>+ );+}diff --git a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx b/apps/web/src/features/block-canvas/component/CanvasDocument.tsxindex 246a0cb9ae..9354cc599b 100644--- a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx+++ b/apps/web/src/features/block-canvas/component/CanvasDocument.tsx@@ -2,6 +2,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import type { PortalScope } from '@core/component/ScopedPortal';import { toast } from '@core/component/Toast/Toast';import { enableCanvasNext } from '@core/constant/featureFlags';+import { useTauri } from '@macro/tauri';import { debounce } from '@solid-primitives/scheduled';import {type Accessor,@@ -215,6 +216,15 @@ function CanvasDocumentState(props: CanvasDocumentProps) {const [animation] = canvas.state.stores.animation;const [dataState, setDataState] = createSignal<CanvasDataState>('loading');const [visible, setVisible] = createSignal(false);+ const unregisterUpdatePreparation =+ useTauri()?.registerNativeUpdatePreparation(async () => {+ if (pending() && !(await saveCanvasDataImmediate())) {+ throw new Error(+ 'Could not save your canvas. Please try again before restarting.'+ );+ }+ });+ onCleanup(() => unregisterUpdatePreparation?.());const [pendingLocationParams, setPendingLocationParams] =createSignal<Record<string, unknown>>();diff --git a/apps/web/src/features/block-canvas/store/canvasData.ts b/apps/web/src/features/block-canvas/store/canvasData.tsindex 4163feaa32..ad8a4117aa 100644--- a/apps/web/src/features/block-canvas/store/canvasData.ts+++ b/apps/web/src/features/block-canvas/store/canvasData.ts@@ -849,11 +849,13 @@ export const useSaveCanvasDataImmediate = sharedInstance(() => {const { file, saved } = await saveCanvasDocument(documentId, canvas);if (!saved) {console.error('error on canvas save');+ return false;}setCurrentSavedFile(() => file);setPendingUpdates(false);+ return true;});});diff --git a/apps/web/src/features/block-pdf/component/Document.tsx b/apps/web/src/features/block-pdf/component/Document.tsxindex 44f5b3e3bc..1bf5553faf 100644--- a/apps/web/src/features/block-pdf/component/Document.tsx+++ b/apps/web/src/features/block-pdf/component/Document.tsx@@ -272,7 +272,7 @@ export function Document() {const annotationsPromise = loadAnnotations(documentProxy);if (updateModificationDataOnLoad()) {- annotationsPromise.then(saveModificationData);+ annotationsPromise.then(() => saveModificationData());}const documentId = pdf.documentId();diff --git a/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx b/apps/web/src/features/block-pdf/component/PdfDocument.test.tsxindex 71befad4ac..629be44be9 100644--- a/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx+++ b/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx@@ -13,6 +13,7 @@ const state = vi.hoisted(() => ({}));vi.mock('@solidjs/router', () => ({ useBeforeLeave: () => {} }));+vi.mock('@macro/tauri', () => ({ useTauri: () => undefined }));vi.mock('../context/pdf-document-context', () => ({PdfDocumentProvider: (props: { children: JSX.Element }) => props.children,usePdfDocument: () => ({diff --git a/apps/web/src/features/block-pdf/component/PdfDocument.tsx b/apps/web/src/features/block-pdf/component/PdfDocument.tsxindex 02abe14a91..7a891ae4a6 100644--- a/apps/web/src/features/block-pdf/component/PdfDocument.tsx+++ b/apps/web/src/features/block-pdf/component/PdfDocument.tsx@@ -1,6 +1,7 @@import './block.css';import type { PortalScope } from '@core/component/ScopedPortal';+import { useTauri } from '@macro/tauri';import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';import { debounce, leading } from '@solid-primitives/scheduled';import { type BeforeLeaveEventArgs, useBeforeLeave } from '@solidjs/router';@@ -109,6 +110,11 @@ function PdfDocumentBehavior(props: PdfDocumentProps) {const pdfViewer = usePdfViewer();const comments = usePdfCommentProjection();const savePdf = usePdfSave();+ const unregisterUpdatePreparation =+ useTauri()?.registerNativeUpdatePreparation(() =>+ savePdf({ throwOnError: true })+ );+ onCleanup(() => unregisterUpdatePreparation?.());const [pendingLocationParams, setPendingLocationParams] =createSignal<LocationBlockParams>();const goToInitialLocation = useGoToLinkLocation();diff --git a/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.tsindex 06957fa5f8..c31d19e275 100644--- a/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.ts+++ b/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.ts@@ -1,5 +1,6 @@import { createRoot } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';+import { createNativeUpdatePreparation } from '../../../lib/tauri/native-update-preparation';import { createPdfPersistence, type PdfPersistence } from './pdf-persistence';function createDeferred() {@@ -25,6 +26,46 @@ afterEach(() => {});describe('createPdfPersistence', () => {+ it('prevents restart when a strict PDF save fails', async () => {+ const { persistence, dispose } = setup();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const flush = vi.fn();+ const preparation = createNativeUpdatePreparation({+ isBlocked: () => false,+ flush,+ });+ preparation.register(() =>+ persistence.runSave(+ async () => {+ throw new Error('PDF save failed');+ },+ () => true,+ { throwOnError: true }+ )+ );+ await expect(preparation.prepare()).rejects.toThrow('PDF save failed');+ expect(flush).not.toHaveBeenCalled();+ expect(persistence.isSaving()).toBe(false);+ dispose();+ });++ it('waits for an ongoing save before preparation can continue', async () => {+ const { persistence, dispose } = setup();+ const deferred = createDeferred();+ const saving = persistence.runSave(+ () => deferred.promise,+ () => true+ );+ const finished = vi.fn();+ const waiting = persistence.waitForSaves().then(finished);+ await Promise.resolve();+ expect(finished).not.toHaveBeenCalled();+ deferred.resolve();+ await Promise.all([saving, waiting]);+ expect(finished).toHaveBeenCalledOnce();+ dispose();+ });+it('skips saves that are not required', async () => {const { persistence, dispose } = setup();let saves = 0;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-persistence.ts b/apps/web/src/features/block-pdf/primitives/pdf-persistence.tsindex 007b2a0bad..c6d5587c20 100644--- a/apps/web/src/features/block-pdf/primitives/pdf-persistence.ts+++ b/apps/web/src/features/block-pdf/primitives/pdf-persistence.ts@@ -4,21 +4,28 @@ import { createSignal } from 'solid-js';export function createPdfPersistence() {const [savingCount, setSavingCount] = createSignal(0);const isSaving: Accessor<boolean> = () => savingCount() > 0;+ const pending = new Set<Promise<void>>();const runSave = async (save: () => Promise<void>,- shouldSave: () => boolean+ shouldSave: () => boolean,+ options?: { throwOnError?: boolean }) => {let saving = false;+ let operation: Promise<void> | undefined;try {if (!shouldSave()) return;saving = true;setSavingCount((previous) => previous + 1);- await save();+ operation = save();+ pending.add(operation);+ await operation;} catch (error) {console.error('Error saving PDF', error);+ if (options?.throwOnError) throw error;} finally {if (saving) {+ if (operation) pending.delete(operation);setSavingCount((previous) => previous - 1);}}@@ -27,6 +34,9 @@ export function createPdfPersistence() {return {isSaving,runSave,+ async waitForSaves() {+ await Promise.all([...pending]);+ },};}diff --git a/apps/web/src/features/block-pdf/signal/save.ts b/apps/web/src/features/block-pdf/signal/save.tsindex 1810388455..e2d60e66af 100644--- a/apps/web/src/features/block-pdf/signal/save.ts+++ b/apps/web/src/features/block-pdf/signal/save.ts@@ -52,22 +52,18 @@ export function useSaveModificationData() {pinnedTerms: [],});- const serverSaves: Promise<any>[] = [];-const sha = await hashModificationData(modificationData);- serverSaves.push(- storageServiceClient.pdfSave({- documentId: pdf.documentId(),- modificationData,- sha,- })- );- serverSaves.push(refetchHistory());-- await Promise.all(serverSaves);+ const result = await storageServiceClient.pdfSave({+ documentId: pdf.documentId(),+ modificationData,+ sha,+ });+ if (result.isErr()) throw new Error('Could not save PDF changes');+ await refetchHistory();};- return () => pdf.persistence.runSave(save, shouldSave);+ return (options?: { throwOnError?: boolean }) =>+ pdf.persistence.runSave(save, shouldSave, options);}export function usePdfSaveLocation() {@@ -86,28 +82,33 @@ export function usePdfSaveLocation() {const save = async () => {const location = viewer()?.getLocationHash();- pdf.setPersistedViewLocation(location);if (location == null) {- await storageServiceClient.deleteDocumentViewLocation({+ const result = await storageServiceClient.deleteDocumentViewLocation({documentId: pdf.documentId(),});+ if (result.isErr()) throw new Error('Could not save PDF view location');} else {- await storageServiceClient.upsertDocumentViewLocation({+ const result = await storageServiceClient.upsertDocumentViewLocation({documentId: pdf.documentId(),location,});+ if (result.isErr()) throw new Error('Could not save PDF view location');}+ pdf.setPersistedViewLocation(location);};- return () => pdf.persistence.runSave(save, shouldSave);+ return (options?: { throwOnError?: boolean }) =>+ pdf.persistence.runSave(save, shouldSave, options);}export const usePdfSave = () => {+ const pdf = usePdfDocument();const saveLocation = usePdfSaveLocation();const saveModificationData = useSaveModificationData();- const save = async () => {- await Promise.all([saveLocation(), saveModificationData()]);+ const save = async (options?: { throwOnError?: boolean }) => {+ if (options?.throwOnError) await pdf.persistence.waitForSaves();+ await Promise.all([saveLocation(options), saveModificationData(options)]);};return save;diff --git a/apps/web/src/features/settings/Account.tsx b/apps/web/src/features/settings/Account.tsxindex acee8d72bf..8a0d7389b6 100644--- a/apps/web/src/features/settings/Account.tsx+++ b/apps/web/src/features/settings/Account.tsx@@ -24,7 +24,11 @@ import {} from '@core/signal/profilePicture';import { createStaticFile } from '@core/util/create';import { openFilePicker } from '@core/util/upload';-import { type BundleUpdateStatus, useTauri } from '@macro/tauri';+import {+ type BundleUpdateStatus,+ nativeUpdateDescription,+ useTauri,+} from '@macro/tauri';import {type SupportedNotificationSettings,useNotificationSettings,@@ -450,6 +454,7 @@ export function Account() {/></Row>+ <NativeUpdateRow /><Show when={autoUpdateUIEnabled()}><BundleVersionRow /><BundleUpdateRow />@@ -869,3 +874,28 @@ function BundleUpdateRow() {</Row>);}++function NativeUpdateRow() {+ const tauri = useTauri();+ return (+ <Show when={tauri && tauri.nativeUpdateStatus().status !== 'Disabled'}>+ <Row label="Desktop app update">+ <div class="flex items-center gap-3">+ <span class="text-sm text-ink-muted">+ {tauri && nativeUpdateDescription(tauri.nativeUpdateStatus())}+ </span>+ <Show when={tauri?.nativeUpdateStatus().status === 'Ready'}>+ <Button+ variant="accent"+ size="sm"+ depth={3}+ onClick={() => void tauri?.restartNativeUpdate()}+ >+ Restart to update+ </Button>+ </Show>+ </div>+ </Row>+ </Show>+ );+}diff --git a/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsxindex 18c5123054..67388ffe59 100644--- a/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx+++ b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx@@ -1,8 +1,11 @@import { Button, Dialog, Surface } from '@ui';+import { Show } from 'solid-js';export function NativeAppUpdateRequiredDialog(props: {open: boolean;onClose: () => void;+ description?: string;+ onRestart?: () => void;}) {const title = 'Update Macro App required';const description =@@ -24,10 +27,19 @@ export function NativeAppUpdateRequiredDialog(props: {{title}</Dialog.Title><Dialog.Description class="text-sm leading-5 text-ink-extra-muted">- {description}+ {props.description ?? description}</Dialog.Description></div>- <div class="flex justify-end">+ <div class="flex justify-end gap-2">+ <Show when={props.onRestart}>+ <Button+ variant="accent"+ size="sm"+ onClick={() => props.onRestart?.()}+ >+ Restart to update+ </Button>+ </Show><Dialog.CloseButton as={Button} variant="strong" size="sm">OK</Dialog.CloseButton>diff --git a/apps/web/src/lib/core/util/reloadForNewerBuild.ts b/apps/web/src/lib/core/util/reloadForNewerBuild.tsindex 685c2b4374..fc991bb0bb 100644--- a/apps/web/src/lib/core/util/reloadForNewerBuild.ts+++ b/apps/web/src/lib/core/util/reloadForNewerBuild.ts@@ -52,6 +52,11 @@ const browserPage: ReloadPage = {const holds = new Set<symbol>();let scheduled = false;+/** Checks active calls/uploads/imports without executing unload side effects. */+export function hasAutomaticReloadHolds(): boolean {+ return holds.size > 0;+}+/*** Keeps this tab from reloading by itself into a newer build while work a* reload would cut off is running, such as a call or an upload. Returns thediff --git a/apps/web/src/lib/queries/persistence.ts b/apps/web/src/lib/queries/persistence.tsindex fbfc1d7f8b..a309309dbe 100644--- a/apps/web/src/lib/queries/persistence.ts+++ b/apps/web/src/lib/queries/persistence.ts@@ -32,6 +32,8 @@ export type PersistScope = Readonly<{export type QueryPersistence = {/** Restore this query without starting or waiting for its network request. */restoreQuery: (queryKey: QueryKey) => Promise<void>;+ /** Await pending local writes before restarting the native app. */+ flush: () => Promise<void>;dispose: () => void;};@@ -166,14 +168,12 @@ export function setupQueryPersistence(return pending;};- const flushAll = () => {- for (const scope of scopes) {- void scope.store.flush();- }+ const flushAll = async () => {+ await Promise.all(scopes.map((scope) => scope.store.flush()));};const onVisibilityChange = () => {- if (document.visibilityState === 'hidden') flushAll();+ if (document.visibilityState === 'hidden') void flushAll();};document.addEventListener('visibilitychange', onVisibilityChange);@@ -205,6 +205,11 @@ export function setupQueryPersistence(.build(queryClient, { queryKey });return restore(query, scope);},+ flush: async () => {+ await Promise.all(+ scopes.map((scope) => scope.store.flush({ throwOnError: true }))+ );+ },dispose() {disposed = true;cacheUnsubscribe();diff --git a/apps/web/src/lib/queries/persistence/per-query-idb.test.ts b/apps/web/src/lib/queries/persistence/per-query-idb.test.tsindex faf2879c83..f830dd29d2 100644--- a/apps/web/src/lib/queries/persistence/per-query-idb.test.ts+++ b/apps/web/src/lib/queries/persistence/per-query-idb.test.ts@@ -23,6 +23,45 @@ const store = () =>afterEach(() => vi.restoreAllMocks());describe('clearable query persistence', () => {+ it('rejects a strict flush on storage failure and retries the pending data', async () => {+ const db = store();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementationOnce(() => {+ throw new Error('Storage unavailable');+ });+ db.set(entry('pending'));+ await expect(db.flush({ throwOnError: true })).rejects.toThrow(+ 'Storage unavailable'+ );+ await db.flush({ throwOnError: true });+ expect(await db.get('pending')).toEqual(entry('pending'));+ });++ it('strict flush waits for an already started write with an empty pending queue', async () => {+ const db = store();+ await db.clear();+ const started = Promise.withResolvers<void>();+ const put = IDBObjectStore.prototype.put;+ let completed = false;+ vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementationOnce(function (+ this: IDBObjectStore,+ value,+ key+ ) {+ this.transaction.addEventListener('complete', () => {+ completed = true;+ });+ started.resolve();+ return put.call(this, value, key);+ });+ db.set(entry('pending'));+ const background = db.flush();+ await started.promise;+ await db.flush({ throwOnError: true });+ expect(completed).toBe(true);+ await background;+ });+it('fences pending puts and deletes', async () => {const db = store();db.set(entry('old'));diff --git a/apps/web/src/lib/queries/persistence/per-query-idb.ts b/apps/web/src/lib/queries/persistence/per-query-idb.tsindex c78b36392a..55ae3bb707 100644--- a/apps/web/src/lib/queries/persistence/per-query-idb.ts+++ b/apps/web/src/lib/queries/persistence/per-query-idb.ts@@ -13,7 +13,7 @@ export type PerQueryPersistence = {get: (queryHash: string) => Promise<PersistedQueryEntry | undefined>;set: (entry: PersistedQueryEntry) => void;remove: (queryHash: string) => void;- flush: () => Promise<void>;+ flush: (options?: { throwOnError?: boolean }) => Promise<void>;};export type ClearablePerQueryPersistence = PerQueryPersistence & {@@ -98,7 +98,7 @@ export function createPerQueryIDBStore(return next;}- const flush = async () => {+ const flush = async (throwOnError = false) => {const currentGeneration = generation;const puts = new Map(pendingPuts);const deletes = new Set(pendingDeletes);@@ -136,6 +136,7 @@ export function createPerQueryIDBStore(if (!pendingPuts.has(hash)) pendingDeletes.add(hash);}console.error('[query] IDB persistence flush failed', err);+ if (throwOnError) throw err;}};@@ -169,12 +170,14 @@ export function createPerQueryIDBStore(scheduleFlush();},- flush: async () => {+ flush: async (options) => {if (timer) {clearTimeout(timer);timer = null;}- await flush();+ // Background failures requeue their writes before this barrier retries them.+ if (options?.throwOnError) await writes;+ await flush(options?.throwOnError);await writes;},diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsxindex 244e03c2e3..c84d8cf560 100644--- a/apps/web/src/lib/tauri/TauriProvider.tsx+++ b/apps/web/src/lib/tauri/TauriProvider.tsx@@ -5,10 +5,12 @@ import { useAndroidWindowInsets } from '@core/mobile/androidWindowInsets';import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';import { isPlatform, isTauri } from '@core/util/platform';import { PlatformNotificationProvider } from '@notifications';+import { queryPersistence } from '@queries/client';import type { RouteSectionProps } from '@solidjs/router';import { invoke } from '@tauri-apps/api/core';import { listen } from '@tauri-apps/api/event';import { type OsType, type as osType } from '@tauri-apps/plugin-os';+import { Dialog, Surface } from '@ui';import {type Accessor,createContext,@@ -19,6 +21,11 @@ import {onMount,useContext,} from 'solid-js';+import {+ createNativeUpdates,+ type NativeUpdateStatus,+ nativeUpdateDescription,+} from './native-updates';import { useTauriNavigationEffect } from './navigation';import { MaybePushNotificationRegistration } from './PushNotification';import { ShareTargetProvider } from './ShareTargetProvider';@@ -42,6 +49,10 @@ export type BundleUpdateStatus =interface TauriContextValue {os: OsType;bundleUpdateStatus: Accessor<BundleUpdateStatus>;+ nativeUpdateStatus: Accessor<NativeUpdateStatus>;+ nativeUpdatePreparing: Accessor<boolean>;+ restartNativeUpdate: () => Promise<void>;+ registerNativeUpdatePreparation: (save: () => Promise<void>) => () => void;}const TauriContext = createContext<TauriContextValue | undefined>(undefined);@@ -66,6 +77,7 @@ function shouldShowNativeAppUpdateRequiredDialog(status: BundleUpdateStatus) {}function TauriProvider(props: { children: JSX.Element }) {+ const nativeUpdates = createNativeUpdates(queryPersistence.flush);useAndroidWindowInsets();useAndroidBack();const [bundleUpdateStatus, setBundleUpdateStatus] =@@ -99,6 +111,10 @@ function TauriProvider(props: { children: JSX.Element }) {const value: TauriContextValue = {os: osType(),bundleUpdateStatus,+ nativeUpdateStatus: nativeUpdates.status,+ nativeUpdatePreparing: nativeUpdates.preparing,+ restartNativeUpdate: nativeUpdates.restart,+ registerNativeUpdatePreparation: nativeUpdates.registerPreparation,};onMount(() => {@@ -149,9 +165,36 @@ function TauriProvider(props: { children: JSX.Element }) {return (<TauriContext.Provider value={value}><ShareTargetProvider os={value.os}>{props.children}</ShareTargetProvider>+ <Dialog+ open={nativeUpdates.preparing()}+ onOpenChange={() => {}}+ class="w-[90%] max-w-120"+ position="center"+ >+ <Surface depth={2}>+ <div class="flex flex-col gap-2 px-4 py-5">+ <Dialog.Title class="text-lg font-semibold text-ink">+ Restarting Macro+ </Dialog.Title>+ <Dialog.Description class="text-sm text-ink-extra-muted">+ Saving your changes before installing the app update…+ </Dialog.Description>+ </div>+ </Surface>+ </Dialog><NativeAppUpdateRequiredDialogopen={nativeAppUpdateRequiredDialogOpen()}onClose={() => setNativeAppUpdateRequiredDialogOpen(false)}+ description={+ isPlatform('desktop') && nativeUpdates.status().status !== 'Disabled'+ ? nativeUpdateDescription(nativeUpdates.status())+ : undefined+ }+ onRestart={+ nativeUpdates.status().status === 'Ready'+ ? () => void nativeUpdates.restart()+ : undefined+ }/></TauriContext.Provider>);diff --git a/apps/web/src/lib/tauri/index.ts b/apps/web/src/lib/tauri/index.tsindex 1c02a09f39..4d02f64fdf 100644--- a/apps/web/src/lib/tauri/index.ts+++ b/apps/web/src/lib/tauri/index.ts@@ -1,3 +1,4 @@+export { nativeUpdateDescription } from './native-updates';export type {PendingShareFile,UploadPendingShareFileArgs,diff --git a/apps/web/src/lib/tauri/native-update-preparation.test.ts b/apps/web/src/lib/tauri/native-update-preparation.test.tsnew file mode 100644index 0000000000..b70650076a--- /dev/null+++ b/apps/web/src/lib/tauri/native-update-preparation.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from 'vitest';+import { createNativeUpdatePreparation } from './native-update-preparation';++describe('native restart preparation', () => {+ it('awaits pending editor saves before flushing local persistence', async () => {+ let finishSave!: () => void;+ const saved = new Promise<void>((resolve) => {+ finishSave = resolve;+ });+ const flush = vi.fn(async () => {});+ const preparation = createNativeUpdatePreparation({+ isBlocked: () => false,+ flush,+ });+ preparation.register(() => saved);+ let ready = false;+ const result = preparation.prepare().then(() => {+ ready = true;+ });+ await Promise.resolve();+ expect(flush).not.toHaveBeenCalled();+ expect(ready).toBe(false);+ finishSave();+ await result;+ expect(flush).toHaveBeenCalledOnce();+ expect(ready).toBe(true);+ });++ it('rejects active calls without running saves or unload side effects', async () => {+ const flush = vi.fn(async () => {});+ const save = vi.fn(async () => {});+ const preparation = createNativeUpdatePreparation({+ isBlocked: () => true,+ flush,+ });+ preparation.register(save);+ const disconnectCall = vi.fn();+ window.addEventListener('beforeunload', disconnectCall);+ try {+ await expect(preparation.prepare()).rejects.toThrow('Finish your call');+ expect(save).not.toHaveBeenCalled();+ expect(flush).not.toHaveBeenCalled();+ expect(disconnectCall).not.toHaveBeenCalled();+ } finally {+ window.removeEventListener('beforeunload', disconnectCall);+ }+ });++ it('does not restart after a failed editor save and unregisters closed editors', async () => {+ const preparation = createNativeUpdatePreparation({+ isBlocked: () => false,+ flush: async () => {},+ });+ const unregister = preparation.register(async () => {+ throw new Error('save failed');+ });+ await expect(preparation.prepare()).rejects.toThrow('save failed');+ unregister();+ await expect(preparation.prepare()).resolves.toBeUndefined();+ });+});diff --git a/apps/web/src/lib/tauri/native-update-preparation.ts b/apps/web/src/lib/tauri/native-update-preparation.tsnew file mode 100644index 0000000000..08f9d5bc8d--- /dev/null+++ b/apps/web/src/lib/tauri/native-update-preparation.ts@@ -0,0 +1,25 @@+/** Owned by one Tauri provider; editors register saves while they are mounted. */+export function createNativeUpdatePreparation(options: {+ isBlocked(): boolean;+ flush(): Promise<void>;+}) {+ const saves = new Set<() => Promise<void>>();+ return {+ register(save: () => Promise<void>) {+ saves.add(save);+ return () => {+ saves.delete(save);+ };+ },+ async prepare() {+ if (options.isBlocked())+ throw new Error(+ 'Finish your call, upload, or import before restarting Macro.'+ );+ await Promise.all([...saves].map((save) => save()));+ await options.flush();+ if (options.isBlocked())+ throw new Error('Finish your current work before restarting Macro.');+ },+ };+}diff --git a/apps/web/src/lib/tauri/native-updates.ts b/apps/web/src/lib/tauri/native-updates.tsnew file mode 100644index 0000000000..a4ed865d7c--- /dev/null+++ b/apps/web/src/lib/tauri/native-updates.ts@@ -0,0 +1,124 @@+import { toast } from '@core/component/Toast/Toast';+import { isPlatform } from '@core/util/platform';+import { hasAutomaticReloadHolds } from '@core/util/reloadForNewerBuild';+import { invoke } from '@tauri-apps/api/core';+import { listen } from '@tauri-apps/api/event';+import { createSignal, onCleanup, onMount } from 'solid-js';+import { match } from 'ts-pattern';+import { createNativeUpdatePreparation } from './native-update-preparation';++export type NativeUpdateStatus =+ | { status: 'Disabled' | 'Idle' | 'Checking' | 'Installing' }+ | { status: 'Downloading' | 'Ready'; data: { version: string } }+ | { status: 'Error'; data: { message: string } };++export function nativeUpdateDescription(status: NativeUpdateStatus): string {+ return match(status)+ .with(+ { status: 'Disabled' },+ () => 'Download the latest Macro app to update.'+ )+ .with(+ { status: 'Idle' },+ () => 'Macro checks for app updates automatically.'+ )+ .with({ status: 'Checking' }, () => 'Checking for an app update…')+ .with({ status: 'Downloading' }, () => 'Downloading an app update…')+ .with(+ { status: 'Ready' },+ () => 'An app update is ready. It will install when you quit Macro.'+ )+ .with({ status: 'Installing' }, () => 'Installing the app update…')+ .with({ status: 'Error' }, (value) => value.data.message)+ .exhaustive();+}++/** Desktop lifecycle integration, scoped to the Tauri provider. */+export function createNativeUpdates(flush: () => Promise<void>) {+ const preparation = createNativeUpdatePreparation({+ isBlocked: hasAutomaticReloadHolds,+ flush,+ });+ const [preparing, setPreparing] = createSignal(false);+ const [status, setStatus] = createSignal<NativeUpdateStatus>({+ status: 'Disabled',+ });+ let disposed = false;+ let unsubscribe = () => {};++ async function restart() {+ if (status().status !== 'Ready' || preparing()) return;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ setPreparing(true);+ await Promise.race([+ preparation.prepare(),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () =>+ reject(+ new Error(+ 'Saving is taking longer than expected. Try restarting again after your changes finish saving.'+ )+ ),+ 15_000+ );+ }),+ ]);+ await invoke('restart_native_update');+ } catch (error) {+ setPreparing(false);+ toast.failure(+ error instanceof Error+ ? error.message+ : 'Could not restart Macro. Try again after your changes finish saving.'+ );+ } finally {+ clearTimeout(timeout);+ }+ }++ function receive(next: NativeUpdateStatus) {+ if (disposed) return;+ setStatus(next);+ }++ async function initialize() {+ let receivedEvent = false;+ try {+ const stop = await listen<NativeUpdateStatus>(+ 'native-update-status',+ (event) => {+ receivedEvent = true;+ receive(event.payload);+ }+ );+ if (disposed) {+ stop();+ return;+ }+ unsubscribe = stop;+ const current = await invoke<NativeUpdateStatus>(+ 'get_native_update_status'+ );+ if (!receivedEvent) receive(current);+ } catch {+ // Older binaries can load this OTA bundle but do not have the command.+ // They retain the existing manual native-upgrade flow.+ }+ }++ onMount(() => {+ if (isPlatform('desktop')) void initialize();+ });+ onCleanup(() => {+ disposed = true;+ unsubscribe();+ });+ return {+ status,+ restart,+ preparing,+ registerPreparation: preparation.register,+ };+}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex 42652cb2a2..484000a4a5 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -290,6 +290,7 @@ dependencies = ["tauri-plugin-pasteboard","tauri-plugin-photo-library","tauri-plugin-single-instance",+ "tauri-plugin-updater","tauri-plugin-virtual-keyboard","tauri-plugin-websocket","thiserror 2.0.18",@@ -952,6 +953,17 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"+[[package]]+name = "cfb"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"+dependencies = [+ "byteorder",+ "fnv",+ "uuid",+]+[[package]]name = "cfb"version = "0.14.0"@@ -2031,6 +2043,16 @@ dependencies = ["rustc_version",]+[[package]]+name = "filetime"+version = "0.2.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"+dependencies = [+ "cfg-if",+ "libc",+]+[[package]]name = "filter_ast"version = "0.1.0"@@ -3125,13 +3147,22 @@ dependencies = ["serde_core",]+[[package]]+name = "infer"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"+dependencies = [+ "cfb 0.7.3",+]+[[package]]name = "infer"version = "0.22.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"dependencies = [- "cfb",+ "cfb 0.14.0",][[package]]@@ -3648,7 +3679,7 @@ dependencies = ["tokio","tracing","url",- "zip",+ "zip 6.0.0",][[package]]@@ -3777,6 +3808,12 @@ dependencies = ["unicase",]+[[package]]+name = "minisign-verify"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"+[[package]]name = "miniz_oxide"version = "0.8.9"@@ -4281,6 +4318,18 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-osa-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"+dependencies = [+ "bitflags 2.11.1",+ "objc2 0.6.4",+ "objc2-app-kit",+ "objc2-foundation",+]+[[package]]name = "objc2-quartz-core"version = "0.3.2"@@ -4418,6 +4467,20 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "osakit"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"+dependencies = [+ "objc2 0.6.4",+ "objc2-foundation",+ "objc2-osa-kit",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]+[[package]]name = "owo-colors"version = "3.5.0"@@ -5096,7 +5159,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.59.0",+ "windows-sys 0.60.2",][[package]]@@ -5573,6 +5636,7 @@ checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"dependencies = ["aws-lc-rs","once_cell",+ "ring","rustls-pki-types","rustls-webpki","subtle",@@ -6548,6 +6612,17 @@ version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"+[[package]]+name = "tar"+version = "0.4.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"+dependencies = [+ "filetime",+ "libc",+ "xattr",+]+[[package]]name = "target-lexicon"version = "0.12.16"@@ -6983,6 +7058,39 @@ dependencies = ["zbus",]+[[package]]+name = "tauri-plugin-updater"+version = "2.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "806d9dac662c2e4594ff03c647a552f2c9bd544e7d0f683ec58f872f952ce4af"+dependencies = [+ "base64 0.22.1",+ "dirs 6.0.0",+ "flate2",+ "futures-util",+ "http",+ "infer 0.19.0",+ "log",+ "minisign-verify",+ "osakit",+ "percent-encoding",+ "reqwest",+ "rustls",+ "semver",+ "serde",+ "serde_json",+ "tar",+ "tauri",+ "tauri-plugin",+ "tempfile",+ "thiserror 2.0.18",+ "time",+ "tokio",+ "url",+ "windows-sys 0.60.2",+ "zip 4.6.1",+]+[[package]]name = "tauri-plugin-virtual-keyboard"version = "0.1.0"@@ -7076,7 +7184,7 @@ dependencies = ["glob","html5ever 0.29.1","http",- "infer",+ "infer 0.22.0","json-patch","kuchikiki","log",@@ -9277,6 +9385,16 @@ dependencies = ["pkg-config",]+[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]+[[package]]name = "yansi"version = "1.0.1"@@ -9463,6 +9581,18 @@ dependencies = ["syn 3.0.3",]+[[package]]+name = "zip"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"+dependencies = [+ "arbitrary",+ "crc32fast",+ "indexmap 2.14.0",+ "memchr",+]+[[package]]name = "zip"version = "6.0.0"diff --git a/apps/web/tauri/desktop-release.json b/apps/web/tauri/desktop-release.jsonnew file mode 100644index 0000000000..f390325c38--- /dev/null+++ b/apps/web/tauri/desktop-release.json@@ -0,0 +1,8 @@+{+ "version": "2.5.0",+ "nativeBuild": 0,+ "bundleBuild": 1,+ "enabled": false,+ "endpoint": "https://github.com/macro-inc/macro/releases/download/desktop-stable/latest.json",+ "publicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE2NDc2RUVGRUJDMjgyOTUKUldTVmdzTHI3MjVIRmtPWVJtT0cya0djY2xEc3JqR0VOVU9yNHN3akNtZ0N6RThHbkpUVUVMd0gK"+}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rsindex f6b43e91b6..0191b9c9e9 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs@@ -239,8 +239,10 @@ pub async fn apply_completed_update_from<R: Runtime>(.app_cache_dir().map_err(|e| e.to_string())?;+ // Keep application and reload dispatch in one critical section. Native+ // installation holds this same lock while shutting down the webview/cache.+ let mut service = service_state.lock().await;let apply_result = {- let mut service = service_state.lock().await;let result = service.apply_update(&cache_dir).await@@ -261,14 +263,14 @@ pub async fn apply_completed_update_from<R: Runtime>(error=?e,"[bundle-update] failed to dispatch webview reload");- service_state.lock().await.unmark_update_reload_dispatched();+ service.unmark_update_reload_dispatched();}} else {tracing::warn!(source,"[bundle-update] completed bundle update applied but no webview was available to reload");- service_state.lock().await.unmark_update_reload_dispatched();+ service.unmark_update_reload_dispatched();}}Ok(apply_result != ApplyUpdateResult::NoUpdate)@@ -352,8 +354,8 @@ pub async fn clear_bundle<R: Runtime>(.app_cache_dir().map_err(|e| e.to_string())?;+ let mut service = service.lock().await;let apply_result = {- let mut service = service.lock().await;let result = service.revert_to_embedded(&cache_dir).await@@ -368,11 +370,11 @@ pub async fn clear_bundle<R: Runtime>(if let Some(webview) = app_handle.webview_windows().values().next() {if let Err(error) = webview.eval("window.location.reload();") {tracing::warn!(error=?error, "[bundle-update] failed to reload after clearing bundle");- service.lock().await.unmark_update_reload_dispatched();+ service.unmark_update_reload_dispatched();}} else {tracing::warn!("[bundle-update] bundle cleared but no webview was available to reload");- service.lock().await.unmark_update_reload_dispatched();+ service.unmark_update_reload_dispatched();}}Ok(())@@ -386,11 +388,20 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {fn initialize(&mut self,app: &tauri::AppHandle<R>,- _config: serde_json::Value,+ config: serde_json::Value,) -> Result<(), Box<dyn std::error::Error>> {let client = BundleClient::new(self.base_url.clone());let fs = FileSystem;- let native_build = native_build();+ // Desktop release builds embed their compatibility number in Tauri config.+ // Mobile continues to use CFBundleVersion / Android versionCode.+ let native_build = if cfg!(not(any(target_os = "ios", target_os = "android"))) {+ config+ .get("nativeBuild")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0)+ } else {+ native_build()+ };let system_info = SystemInfo::new(app.clone(), native_build);let mut service = Service::new::<_, _, TauriTaskSpawner>(diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 24e0145846..c6508e1a29 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -17,6 +17,9 @@ name = "app_lib"serde_json = "1.0"tauri-build = { version = "2.3.1", features = [] }+[dev-dependencies]+tauri = { workspace = true, features = ["test"] }+[features]# Automatic OTA bundle updates: check on launch/resume, apply cached bundles at# startup. Disabled via `--no-default-features` (just ios-dev,@@ -70,6 +73,7 @@ tauri-plugin-os = "2"[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\"))".dependencies]clap = { version = "4", features = ["derive"] }tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }+tauri-plugin-updater = "=2.10.1"[target.'cfg(target_os = "macos")'.dependencies]block2 = "0.6"diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex 0bf7a81ecc..96dcceb03d 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -172,6 +172,64 @@ or enqueueing mutations. An older binary uses the existing uncached fallback andshows an update-required notice; its existing mutation queue stays intact untilthe user installs the native update.+## Desktop native updates++Release builds for macOS Apple Silicon and Linux AppImage check for native updates+after startup and every six hours. Downloads are verified with Tauri's updater+signature before becoming eligible for installation. A ready update installs on+normal app quit; closing/hiding a window only installs if it actually exits the+app. Force-killing loses the in-memory download and the next launch checks again.+No network work is started during quit. Errors retry with backoff.++The ready notification and Settings → Account offer **Restart to update**. Explicit+restart waits for registered canvas/PDF saves and local query persistence, and is+blocked during calls, uploads and imports. Native installation closes the native+cache and excludes concurrent frontend OTA reloads. Neither update channel wipes+user data. Mobile updates remain managed by the app stores. Debug, recording,+branch, and `--no-default-features` builds do not auto-install native updates.++`../desktop-release.json` is the public release configuration; its checked-in+defaults disable updates for local builds. `bun apps/web/scripts/desktop-release.mjs prepare <ref>`+(run from the repository root) updates this tracked file in CI+before Nix evaluates either package. Both packages receive the same native version,+OTA compatibility build number, and source commit timestamp for the embedded+frontend. Existing `vYEAR.MONTH.DAY.REVISION` tags map to+`YEAR.MMDD.REVISION` SemVer, e.g. `v2026.10.6.1` → `2026.1006.1`. Three-part stable+SemVer tags also work. Each component must be at most 9999. Do not reuse a version+or rebuild an already published tag; publish a higher version for fixes/reverts.++The combined desktop workflow is the only publisher. It exports the final+relocated/signed macOS app, notarizes and staples it, and archives it as+`.app.tar.gz`. The Linux AppImage and macOS archive receive updater signatures+outside Nix. `TAURI_SIGNING_PRIVATE_KEY` and `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`+live in Doppler `macos-release/prd`, read using the existing+`MACOS_RELEASE_DOPPLER_TOKEN` CI secret. Only the corresponding public key is+committed. Keep this private key: changing the embedded key requires a transition+release signed with the old key.++Versioned GitHub Release assets are immutable. Publication retries reuse and+verify any already-published signatures, since newly generated signatures include+the signing time. The stable manifest is uploaded last to the dedicated+`desktop-stable` prerelease's `latest.json` asset, after both packages and signatures+exist. Promotions are serialized and reject older/equal versions; unrelated SDK+or daemon releases cannot move the desktop update feed. A brief missing manifest+during replacement is treated as a retryable check error.++Bootstrap requires one manual native upgrade: older binaries cannot acquire the+Rust updater through a frontend OTA. Before promoting the first release, test two+consecutive signed builds on installed macOS and Linux apps, including offline+launch, read-only install locations, quit, restart, and preservation of local data.+Builds run directly from a mounted DMG or the Nix store are not writable installed+apps. For a broken release, stop promotion and release the last working code under+a higher version. No automatic crash rollback is implemented.++The Rust coordinator tests exercise the pinned updater against a local HTTP+server with a test-only public key and signed fixture (the test private key is+discarded), including corrupt signatures and older versions. Release metadata tests+run from `apps/web` with `bunx vitest run --project scripts scripts/desktop-release.test.ts scripts/desktop-signing.test.ts`.+Frontend preparation tests are in the web `tauri` Vitest project. Native replacement/notarization still+requires platform release testing; mocked HTTP tests never replace the test runner.+## Automated offline tests (Linux)See [native E2E](../../tests/native/README.md) for the isolated WebDriver setup,diff --git a/apps/web/tauri/src-tauri/src/desktop_update.rs b/apps/web/tauri/src-tauri/src/desktop_update.rsnew file mode 100644index 0000000000..6b933a4deb--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update.rs@@ -0,0 +1,33 @@+//! Desktop release updates. Native installation is independent of frontend OTA.++mod state;++use state::Status;+use tauri::{AppHandle, Runtime};++#[cfg(desktop)]+mod desktop;+#[cfg(desktop)]+pub use desktop::{on_exit_requested, setup};++#[tauri::command]+pub fn get_native_update_status<R: Runtime>(app: AppHandle<R>) -> Status {+ #[cfg(desktop)]+ return desktop::status(&app);+ #[cfg(mobile)]+ {+ let _ = app;+ Status::Disabled+ }+}++#[tauri::command]+pub fn restart_native_update<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {+ #[cfg(desktop)]+ return desktop::restart(&app);+ #[cfg(mobile)]+ {+ let _ = app;+ Err("Native updates are managed by the app store".into())+ }+}diff --git a/apps/web/tauri/src-tauri/src/desktop_update/desktop.rs b/apps/web/tauri/src-tauri/src/desktop_update/desktop.rsnew file mode 100644index 0000000000..8ec54ab5f9--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/desktop.rs@@ -0,0 +1,254 @@+use super::state::{State, Status};+use macro_bundle_updater_plugin::inbound::plugin::PluginService;+use serde::Deserialize;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tauri::{App, AppHandle, Emitter, ExitRequestApi, Listener, Manager, Runtime};+use tauri_plugin_updater::UpdaterExt;+use tokio::sync::Notify;++const EVENT: &str = "native-update-status";+const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);+const RETRY_INTERVAL: Duration = Duration::from_secs(60);+const MAX_RETRY_INTERVAL: Duration = Duration::from_secs(60 * 60);+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);+const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);++#[cfg(test)]+mod test;++#[derive(Default, Deserialize)]+struct Config {+ enabled: bool,+}++struct Download {+ update: tauri_plugin_updater::Update,+ bytes: Vec<u8>,+}++struct Coordinator {+ state: Mutex<State<Download>>,+ check: Notify,+ restart: Mutex<bool>,+}++pub fn setup<R: Runtime>(+ app: &mut App<R>,+ recording: bool,+) -> Result<(), Box<dyn std::error::Error>> {+ let config: Config = app+ .config()+ .plugins+ .0+ .get("desktop-update")+ .cloned()+ .map(serde_json::from_value)+ .transpose()?+ .unwrap_or_default();+ let enabled = config.enabled+ && cfg!(any(target_os = "macos", target_os = "linux"))+ && !cfg!(debug_assertions)+ && cfg!(feature = "auto_apply_update")+ && !recording;+ let coordinator = Arc::new(Coordinator {+ state: Mutex::new(State::new(enabled)),+ check: Notify::new(),+ restart: Mutex::new(false),+ });+ app.manage(coordinator.clone());+ if !enabled {+ return Ok(());+ }+ app.handle()+ .plugin(tauri_plugin_updater::Builder::new().build())?;+ let notify = coordinator.clone();+ app.listen("bundle-update-status", move |event| {+ // The bundle service owns compatibility decisions; react to its result.+ if serde_json::from_str::<serde_json::Value>(event.payload())+ .is_ok_and(|event| event["status"] == "NativeUpdateRequired")+ {+ notify.check.notify_one();+ }+ });+ let handle = app.handle().clone();+ tauri::async_runtime::spawn(async move {+ let mut retry = RETRY_INTERVAL;+ loop {+ let result = check(&handle, &coordinator).await;+ let delay = match result {+ Ok(()) => {+ retry = RETRY_INTERVAL;+ CHECK_INTERVAL+ }+ Err(error) => {+ tracing::warn!(error=?error, "native update check failed");+ publish(+ &handle,+ &coordinator,+ Status::Error {+ message: "Could not download the app update. Will retry automatically."+ .into(),+ },+ );+ let delay = retry;+ retry = (retry * 2).min(MAX_RETRY_INTERVAL);+ delay+ }+ };+ // Compatibility events cannot turn an unavailable feed into a tight loop.+ tokio::time::sleep(RETRY_INTERVAL).await;+ tokio::select! {+ _ = tokio::time::sleep(delay.saturating_sub(RETRY_INTERVAL)) => {}+ _ = coordinator.check.notified() => {}+ }+ }+ });+ Ok(())+}++pub fn status<R: Runtime>(app: &AppHandle<R>) -> Status {+ app.try_state::<Arc<Coordinator>>()+ .map_or(Status::Disabled, |coordinator| {+ coordinator+ .state+ .lock()+ .expect("native update state poisoned")+ .status+ .clone()+ })+}++fn publish<R: Runtime>(app: &AppHandle<R>, coordinator: &Coordinator, status: Status) {+ coordinator+ .state+ .lock()+ .expect("native update state poisoned")+ .status = status.clone();+ app.emit(EVENT, &status)+ .inspect_err(|error| tracing::warn!(error=?error, "failed to emit native update status"))+ .ok();+}++async fn check<R: Runtime>(+ app: &AppHandle<R>,+ coordinator: &Coordinator,+) -> tauri_plugin_updater::Result<()> {+ if !coordinator+ .state+ .lock()+ .expect("native update state poisoned")+ .begin_check()+ {+ return Ok(());+ }+ publish(app, coordinator, Status::Checking);+ let Some(mut update) = app+ .updater_builder()+ .timeout(REQUEST_TIMEOUT)+ .build()?+ .check()+ .await?+ else {+ publish(app, coordinator, Status::Idle);+ return Ok(());+ };+ let version = update.version.clone();+ publish(+ app,+ coordinator,+ Status::Downloading {+ version: version.clone(),+ },+ );+ update.timeout = Some(DOWNLOAD_TIMEOUT);+ // download() verifies the signature before returning. Never install partial+ // bytes or bytes restored from an unverified disk cache.+ let bytes = update.download(|_, _| {}, || {}).await?;+ coordinator+ .state+ .lock()+ .expect("native update state poisoned")+ .downloaded(version.clone(), Download { update, bytes });+ app.emit(EVENT, Status::Ready { version })+ .inspect_err(|error| tracing::warn!(error=?error, "failed to emit native update ready"))+ .ok();+ Ok(())+}++pub fn restart<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {+ let coordinator = app+ .try_state::<Arc<Coordinator>>()+ .ok_or("Native updater is unavailable")?;+ if !matches!(status(app), Status::Ready { .. }) {+ return Err("No verified app update is ready".into());+ }+ *coordinator+ .restart+ .lock()+ .expect("native update restart state poisoned") = true;+ // Use the same quit path as the menu/OS. restart() itself bypasses exit prevention.+ app.exit(0);+ Ok(())+}++pub fn on_exit_requested<R: Runtime>(app: &AppHandle<R>, api: &ExitRequestApi) {+ let Some(coordinator) = app.try_state::<Arc<Coordinator>>() else {+ return;+ };+ let download = {+ let mut state = coordinator+ .state+ .lock()+ .expect("native update state poisoned");+ if state.is_installing() {+ api.prevent_exit();+ return;+ }+ let Some(download) = state.begin_install() else {+ return;+ };+ download+ };+ api.prevent_exit();+ let coordinator = coordinator.inner().clone();+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ publish(&app, &coordinator, Status::Installing);+ // Serializes against bundle application/reload until the process exits.+ let bundle = app.state::<tokio::sync::Mutex<PluginService>>();+ let _bundle_guard = bundle.lock().await;+ let install_app = app.clone();+ let restart = *coordinator+ .restart+ .lock()+ .expect("native update restart state poisoned");+ let result = tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {+ // Close the native database before handing control to an installer.+ if let Some(cache) = install_app.try_state::<graphql_cache_plugin::CacheState>() {+ cache.shutdown()?;+ }+ download+ .update+ .install(download.bytes)+ .map_err(|error| error.to_string())+ })+ .await;+ let installed = matches!(&result, Ok(Ok(())));+ if !installed {+ tracing::error!(error=?result, "native update installation failed; leaving app for manual recovery");+ }+ coordinator+ .state+ .lock()+ .expect("native update state poisoned")+ .finish_exit();+ if installed && restart {+ app.restart();+ } else {+ app.exit(0);+ // Keep OTA reloads blocked while the event loop processes ExitRequested.+ std::future::pending::<()>().await;+ }+ });+}diff --git a/apps/web/tauri/src-tauri/src/desktop_update/desktop/test.rs b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test.rsnew file mode 100644index 0000000000..09d1425294--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test.rs@@ -0,0 +1,84 @@+use super::*;+use tokio::io::{AsyncReadExt, AsyncWriteExt};++/// Exercises the actual pinned updater's HTTP, version and signature handling.+async fn check_fixture(version: &str, corrupt: bool) -> (tauri_plugin_updater::Result<()>, Status) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let manifest = serde_json::json!({+ "version": version,+ "url": format!("http://{address}/artifact"),+ "signature": include_str!("test/fixtures/update.txt.sig").trim(),+ })+ .to_string();+ let server = tokio::spawn(async move {+ loop {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut request = [0; 4096];+ let size = stream.read(&mut request).await.unwrap();+ let body = if request[..size].starts_with(b"GET /artifact ") {+ if corrupt {+ "tampered artifact".to_string()+ } else {+ include_str!("test/fixtures/update.txt").to_string()+ }+ } else {+ manifest.clone()+ };+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ );+ stream.write_all(response.as_bytes()).await.unwrap();+ }+ });+ let mut context = tauri::test::mock_context(tauri::test::noop_assets());+ context.config_mut().plugins.0.insert(+ "updater".into(),+ serde_json::json!({+ "pubkey": include_str!("test/fixtures/updater.pub").trim(),+ "endpoints": [format!("http://{address}/latest.json")],+ "dangerousInsecureTransportProtocol": true,+ }),+ );+ let app = tauri::test::mock_builder()+ .plugin(tauri_plugin_updater::Builder::new().build())+ .build(context)+ .unwrap();+ let coordinator = Coordinator {+ state: Mutex::new(State::new(true)),+ check: Notify::new(),+ restart: Mutex::new(false),+ };+ let result = check(app.handle(), &coordinator).await;+ let status = coordinator.state.lock().unwrap().status.clone();+ server.abort();+ (result, status)+}++#[tokio::test]+async fn a_verified_download_becomes_ready() {+ let (result, status) = check_fixture("99.0.0", false).await;+ result.unwrap();+ assert_eq!(+ status,+ Status::Ready {+ version: "99.0.0".into()+ }+ );+}++#[tokio::test]+async fn tampered_download_never_becomes_ready() {+ let (result, status) = check_fixture("99.0.0", true).await;+ assert!(result.is_err());+ assert!(!matches!(status, Status::Ready { .. }));+}++#[tokio::test]+async fn older_releases_are_not_downloaded() {+ let (result, status) = check_fixture("0.0.0", false).await;+ result.unwrap();+ assert_eq!(status, Status::Idle);+}diff --git a/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txt b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txtnew file mode 100644index 0000000000..dadb79cd10--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txt@@ -0,0 +1 @@+Macro updater signature test fixture.diff --git a/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txt.sig b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txt.signew file mode 100644index 0000000000..88fd1c1506--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/update.txt.sig@@ -0,0 +1 @@+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUNVlEeFJvTnFkZ1F1Z2FLQ2hxdFdMbmZaMnlvWXRYbndjdzhnSnNUaGNLVHVBWHdmeU5Cby9HRlB5dWExMEFpallFcGVTeHhjbUJ5bEM1WTZWU2E2c1ArcDZOcS9oc3dFPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkxMzAzNTkxCWZpbGU6dXBkYXRlLnR4dApnQm1ValJXd1FTaElVVmdNOFd3WDRQSXVFZ2VjcHdXZFhpWmdUaXFrVFR5N3J5YzRSWkFEQmxtbkF1clp2eTE5WlhCSjlWUEcyYmNYdlVLakMwY3RBZz09Cg==\ No newline at end of filediff --git a/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/updater.pub b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/updater.pubnew file mode 100644index 0000000000..eb4068350f--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/desktop/test/fixtures/updater.pub@@ -0,0 +1 @@+dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDgxOUREQUEwNTEzQzYwRjkKUldUNVlEeFJvTnFkZ1NOUHdYZmNka04vb2FxVmpQaVhESHA3U2lUckhMajI3WHV6cEpDTUpqSUoK\ No newline at end of filediff --git a/apps/web/tauri/src-tauri/src/desktop_update/state.rs b/apps/web/tauri/src-tauri/src/desktop_update/state.rsnew file mode 100644index 0000000000..c396e4169b--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/state.rs@@ -0,0 +1,65 @@+use serde::Serialize;++/// Desktop update status, also exposed to the webview.+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(tag = "status", content = "data")]+pub enum Status {+ Disabled,+ Idle,+ Checking,+ Downloading { version: String },+ Ready { version: String },+ Installing,+ Error { message: String },+}++/// Owns the verified download. Taking it for installation is a one-way transition.+pub struct State<T> {+ pub status: Status,+ ready: Option<T>,+ exiting: bool,+}++impl<T> State<T> {+ pub fn new(enabled: bool) -> Self {+ Self {+ status: if enabled {+ Status::Idle+ } else {+ Status::Disabled+ },+ ready: None,+ exiting: false,+ }+ }++ pub fn begin_check(&mut self) -> bool {+ if self.exiting || !matches!(self.status, Status::Idle | Status::Error { .. }) {+ return false;+ }+ self.status = Status::Checking;+ true+ }++ pub fn downloaded(&mut self, version: String, ready: T) {+ self.ready = Some(ready);+ self.status = Status::Ready { version };+ }++ pub fn begin_install(&mut self) -> Option<T> {+ let ready = self.ready.take()?;+ self.status = Status::Installing;+ Some(ready)+ }++ pub fn is_installing(&self) -> bool {+ !self.exiting && matches!(self.status, Status::Installing)+ }++ pub fn finish_exit(&mut self) {+ self.exiting = true;+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/src-tauri/src/desktop_update/state/test.rs b/apps/web/tauri/src-tauri/src/desktop_update/state/test.rsnew file mode 100644index 0000000000..364b4ec692--- /dev/null+++ b/apps/web/tauri/src-tauri/src/desktop_update/state/test.rs@@ -0,0 +1,45 @@+use super::*;++#[test]+fn disabled_and_busy_states_never_start_another_download() {+ assert!(!State::<()>::new(false).begin_check());+ let mut state = State::new(true);+ assert!(state.begin_check());+ assert!(!state.begin_check());+ state.downloaded("2.5.1".into(), ());+ assert!(!state.begin_check());+}++#[test]+fn quit_during_download_does_not_install_partial_bytes() {+ let mut state = State::<()>::new(true);+ state.begin_check();+ state.status = Status::Downloading {+ version: "2.5.1".into(),+ };+ assert!(state.begin_install().is_none());+ assert!(!state.is_installing());+}++#[test]+fn verified_update_can_only_be_installed_once() {+ let mut state = State::new(true);+ state.downloaded("2.5.1".into(), vec![1, 2, 3]);+ assert_eq!(state.begin_install(), Some(vec![1, 2, 3]));+ assert!(state.is_installing());+ assert!(state.begin_install().is_none());+ assert!(!state.begin_check());+ state.finish_exit();+ assert!(!state.is_installing());+ assert!(!state.begin_check());+}++#[test]+fn failed_checks_can_retry() {+ let mut state = State::<()>::new(true);+ state.begin_check();+ state.status = Status::Error {+ message: "offline".into(),+ };+ assert!(state.begin_check());+}diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex d9c20e573f..955d8f9183 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -33,6 +33,7 @@ use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;use url::Url;+mod desktop_update;mod device;mod diagnostics;mod logging;@@ -264,6 +265,8 @@ pub fn run() {.manage(graphql_cache_plugin::CacheState::default()).manage(IsIpad(is_ipad_device)).invoke_handler(tauri::generate_handler![+ desktop_update::get_native_update_status,+ desktop_update::restart_native_update,diagnostics::read_desktop_diagnostics,#[cfg(target_os = "macos")]macos_notification_permission::get_macos_notification_permission,@@ -309,6 +312,8 @@ pub fn run() {staged_upload::upload_staged_file_to_presigned_url,]).setup(move |app| {+ #[cfg(desktop)]+ desktop_update::setup(app, recording)?;diagnostics::setup(app, diagnostics);#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]{@@ -381,6 +386,10 @@ pub fn run() {});}}+ #[cfg(desktop)]+ RunEvent::ExitRequested { api, .. } => {+ desktop_update::on_exit_requested(app_handle, api)+ }RunEvent::Exit => {if let Some(state) = app_handle.try_state::<graphql_cache_plugin::CacheState>() {statediff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex f67d6b326b..19a9857ecf 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2250,6 +2250,17 @@ Section headings and controls share a white surface in light mode and thecomposer border in dark mode, with subtle row separators. The compact sidebaruses the shared workspace width.+On desktop release builds, **Account → Desktop app update** shows native update+progress. When a verified update is ready, an **Update available** arrow icon+appears in the sidebar above the mobile-app and settings icons. Click it to open+**Update Macro**, then choose **Restart and update** or **Later**. Dismissing the+modal leaves the sidebar notification available. While preparing to restart,+the modal disables its actions. Restart waits for pending canvas/PDF saves and+local persistence; active calls, uploads, and imports must finish first. A ready+update also installs on normal app quit. Closing a window only triggers+installation if it exits the app. Browser, mobile, and development builds do not+show this native updater row.+Left nav (feature and platform gates still apply):- **Blocks**: Email, Calendar, Agents, CRM.diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nixindex 1563793c97..1b17be1b4f 100644--- a/nix/tauri-desktop.nix+++ b/nix/tauri-desktop.nix@@ -18,7 +18,16 @@isX86_64Linux = system == "x86_64-linux";isAarch64Darwin = system == "aarch64-darwin";- appVersion = (builtins.fromJSON (builtins.readFile ../apps/web/package.json)).version;+ desktopRelease = builtins.fromJSON (builtins.readFile ../apps/web/tauri/desktop-release.json);+ appVersion = desktopRelease.version;+ desktopPlugins = {+ desktop-update.enabled = desktopRelease.enabled;+ macro-bundle-updater.nativeBuild = desktopRelease.nativeBuild;+ updater = {+ pubkey = desktopRelease.publicKey;+ endpoints = [ desktopRelease.endpoint ];+ };+ };gitRev = inputs.self.shortRev or inputs.self.dirtyShortRev or "unknown";rustToolchain = fenix.packages.${system}.fromToolchainFile {@@ -128,7 +137,7 @@cd apps/webMODE=production NODE_ENV=production bun ../../node_modules/vite/bin/vite.js build -c vite.config.tsprintf '${appVersion}+${gitRev}\n' > dist/semver.txt- BUNDLE_BUILD_NUMBER=1 MIN_NATIVE_BUILD=0 bun scripts/write-bundle-manifest.mjs+ BUNDLE_BUILD_NUMBER=${toString desktopRelease.bundleBuild} MIN_NATIVE_BUILD=0 bun scripts/write-bundle-manifest.mjs)runHook postBuild@@ -498,6 +507,8 @@rootPaths = tauriRuntimeLibraries ++ tauri.commonArgs.buildInputs;};tauriAppImageConfig = builtins.toJSON {+ version = appVersion;+ plugins = desktopPlugins;build = {frontendDist = "${frontend}";beforeBuildCommand = "";@@ -581,6 +592,8 @@tauriDesktopDmgConfig = builtins.toJSON (lib.recursiveUpdate{+ version = appVersion;+ plugins = desktopPlugins;build = {frontendDist = "${frontend}";beforeBuildCommand = "";@@ -723,6 +736,9 @@sign_darwin_app "$appPath"mkdir -p "$out"+ # Export the final, relocated and signed app for updater packaging.+ # Notarization, stapling and updater signing happen outside the store.+ cp -a "$appPath" "$out/Macro.app"dmgPath="$out/Macro-${appVersion}-${system}.dmg"# Package a drag-to-install volume, including Finder's icon layout.dmgRoot=$(mktemp -d "$TMPDIR/macro-dmg.XXXXXX")diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/build_appimage_on_tag.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/build_appimage_on_tag.rsindex 34d31e177b..e492052c6b 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/build_appimage_on_tag.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/build_appimage_on_tag.rs@@ -26,10 +26,6 @@ pub fn build_appimage() -> Workflow {)),).add_job("build-appimage", build_appimage_job("${{ inputs.ref }}"))- .add_job(- "publish-appimage",- publish_appimage_job("${{ inputs.ref }}").add_needs("build-appimage"),- )}/// Build the AppImage job, checking out and naming artifacts from `ref_expr`.@@ -41,6 +37,7 @@ pub fn build_appimage_job(ref_expr: &str) -> Job {.add_step(steps::mount_nix_cache_volume()).add_step(steps::setup_nix()).add_step(steps::derive_artifact_metadata(ref_expr))+ .add_step(prepare_desktop_release(ref_expr)).add_step(nix_build_appimage()).add_step(collect_appimage()).add_step(steps::upload_artifact(@@ -50,9 +47,12 @@ pub fn build_appimage_job(ref_expr: &str) -> Job {.add_step(steps::teardown_nix())}-/// Publish AppImage artifacts from the workflow run to the release tag.-pub fn publish_appimage_job(ref_expr: &str) -> Job {- publish_job(ref_expr, xtask_paths::runtime_path!("release-artifacts/*"))+/// Embed one release identity in the native app and its bundled frontend.+pub fn prepare_desktop_release(ref_expr: &str) -> Step<Run> {+ Step::new("Prepare desktop release identity")+ .run("nix develop --command bun apps/web/scripts/desktop-release.mjs prepare \"$RAW_REF\"")+ .shell("bash")+ .add_env(("RAW_REF", ref_expr))}/// Publish desktop artifacts from the workflow run to the release tag.diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/build_desktop_on_tag.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/build_desktop_on_tag.rsindex 1a0f3cee73..78be784c2d 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/build_desktop_on_tag.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/build_desktop_on_tag.rs@@ -8,11 +8,11 @@use std::collections::HashMap;use gh_workflow::{- Concurrency, Event, Expression, Job, Push, Run, Step, Workflow, WorkflowDispatch,- WorkflowDispatchInput,+ Concurrency, Event, Expression, Job, Level, Permissions, Push, Run, Step, Workflow,+ WorkflowDispatch, WorkflowDispatchInput,};-use crate::workflows::{build_appimage_on_tag, build_dmg_on_tag};+use crate::workflows::{build_appimage_on_tag, build_dmg_on_tag, steps, vars};const RESOLVED_REF: &str = "${{ needs.resolve-ref.outputs.ref }}";@@ -35,16 +35,54 @@ pub fn build_desktop_on_tag() -> Workflow {).add_job("publish-release",- build_appimage_on_tag::publish_job(- RESOLVED_REF,- xtask_paths::runtime_path!("release-artifacts/*"),- )+ publish_desktop_job().add_needs("resolve-ref").add_needs("build-appimage").add_needs("build-dmg"),)}+fn publish_desktop_job() -> Job {+ Job::default()+ .name("Sign and publish desktop updates")+ .runs_on("ubuntu-latest")+ // Serialize channel promotion across tags; an older build cannot win a race.+ .concurrency(+ Concurrency::new(Expression::new("desktop-stable-publish")).cancel_in_progress(false),+ )+ .cond(Expression::new(+ "startsWith(needs.resolve-ref.outputs.ref, 'refs/tags/v')",+ ))+ .permissions(Permissions {+ contents: Some(Level::Write),+ ..Default::default()+ })+ .add_step(steps::checkout_ref(RESOLVED_REF))+ .add_step(steps::setup_nix())+ .add_step(steps::derive_artifact_metadata(RESOLVED_REF))+ .add_step(steps::download_artifacts(xtask_paths::runtime_path!(+ "release-artifacts"+ )))+ .add_step(+ Step::new("Sign updater artifacts")+ .run(include_str!("scripts/sign_desktop_updates.sh"))+ .shell("bash")+ .add_env(("DOPPLER_TOKEN", vars::MACOS_RELEASE_DOPPLER_TOKEN))+ .add_env(("GH_TOKEN", "${{ github.token }}"))+ .add_env(("RELEASE_TAG", "${{ steps.metadata.outputs.tag }}"))+ .add_env(("RELEASE_REPOSITORY", "${{ github.repository }}")),+ )+ .add_step(+ Step::new("Publish desktop release and update feed")+ .run(include_str!("scripts/publish_desktop_updates.sh"))+ .shell("bash")+ .add_env(("GH_TOKEN", "${{ github.token }}"))+ .add_env(("RELEASE_TAG", "${{ steps.metadata.outputs.tag }}"))+ .add_env(("RELEASE_REPOSITORY", "${{ github.repository }}")),+ )+ .add_step(steps::teardown_nix())+}+fn desktop_events() -> Event {Event::default().push(Push::default().add_tag(build_appimage_on_tag::DESKTOP_TAG_PATTERN))diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rsindex 85b5eee297..a71bb98479 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs@@ -25,10 +25,6 @@ pub fn build_dmg() -> Workflow {)),).add_job("build-dmg", build_dmg_job("${{ inputs.ref }}"))- .add_job(- "publish-dmg",- publish_dmg_job("${{ inputs.ref }}").add_needs("build-dmg"),- )}/// Build the macOS DMG job, checking out and naming artifacts from `ref_expr`.@@ -48,6 +44,7 @@ pub fn build_dmg_job(ref_expr: &str) -> Job {.add_step(configure_nix_cache()).add_step(configure_signing_identity()).add_step(steps::derive_artifact_metadata(ref_expr))+ .add_step(build_appimage_on_tag::prepare_desktop_release(ref_expr)).add_step(nix_build_dmg()).add_step(save_nix_cache()).add_step(collect_dmg())@@ -59,10 +56,6 @@ pub fn build_dmg_job(ref_expr: &str) -> Job {))}-fn publish_dmg_job(ref_expr: &str) -> Job {- build_appimage_on_tag::publish_job(ref_expr, xtask_paths::runtime_path!("release-artifacts/*"))-}-fn assert_arm64() -> Step<Run> {Step::new("Assert arm64 runner").run(indoc::indoc! {r#"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_appimage.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_appimage.shindex d4574ff438..3a110ea56f 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_appimage.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_appimage.sh@@ -9,4 +9,5 @@ if [ "${#appimages[@]}" -eq 0 ]; thenficp -v "${appimages[@]}" artifacts/chmod 0755 artifacts/*.AppImage+cp apps/web/tauri/desktop-release.json artifacts/linux-x86_64.release.json(cd artifacts && sha256sum -- *.AppImage > macro-appimage-SHA256SUMS)diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_dmg.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_dmg.shindex 85b0cc443e..56363c0983 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_dmg.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/collect_dmg.sh@@ -10,3 +10,7 @@ ficp -v "${dmgs[@]}" artifacts/# Nix outputs are read-only; stapler must write Apple's ticket into the copy.chmod u+w artifacts/*.dmg+mkdir -p updater-app+cp -a result/Macro.app updater-app/+chmod -R u+w updater-app/Macro.app+cp apps/web/tauri/desktop-release.json artifacts/darwin-aarch64.release.jsondiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/notarize_dmg.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/notarize_dmg.shindex 37e6409216..072ad237da 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/notarize_dmg.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/notarize_dmg.sh@@ -32,5 +32,19 @@ xcrun stapler staple "$dmg"xcrun stapler validate "$dmg"spctl --assess --type open --context context:primary-signature --verbose=2 "$dmg"+# The updater ships the app rather than the DMG. Notarize and staple that exact+# final app too; stapling only the disk image does not staple the updater app.+ditto -c -k --keepParent updater-app/Macro.app "$credentials_dir/updater-app.zip"+xcrun notarytool submit "$credentials_dir/updater-app.zip" \+ --key "$credentials_dir/AuthKey.p8" --key-id "$key_id" --issuer "$issuer" \+ --wait --timeout 30m --output-format json > "$credentials_dir/app-submission.json"+jq -e '.status == "Accepted"' "$credentials_dir/app-submission.json" > /dev/null+xcrun stapler staple updater-app/Macro.app+xcrun stapler validate updater-app/Macro.app+codesign --verify --deep --strict --verbose=2 updater-app/Macro.app+spctl --assess --type execute --verbose=2 updater-app/Macro.app+version=$(jq -er '.version' apps/web/tauri/desktop-release.json)+COPYFILE_DISABLE=1 tar -czf "artifacts/Macro-${version}-aarch64-darwin.app.tar.gz" -C updater-app Macro.app+# Stapling changes the DMG bytes, so checksum the final distributable.(cd artifacts && shasum -a 256 -- *.dmg > macro-dmg-SHA256SUMS)diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/publish_desktop_updates.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/publish_desktop_updates.shnew file mode 100644index 0000000000..9f01b375de--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/publish_desktop_updates.sh@@ -0,0 +1,53 @@+set -euo pipefail++nix develop --command bun apps/web/scripts/desktop-release.mjs manifest \+ release-artifacts "$RELEASE_TAG" "$RELEASE_REPOSITORY"++# Refuse to overwrite release assets: the manifest may already reference them.+# A failed publication can be resumed if every existing asset has identical bytes.+if ! gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" >/dev/null 2>&1; then+ gh release create "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --verify-tag \+ --title "Macro $RELEASE_TAG" --notes "Desktop release $RELEASE_TAG" --latest=false+fi+work_dir=$(mktemp -d)+trap 'rm -rf "$work_dir"' EXIT+gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --json assets > "$work_dir/release.json"+for file in release-artifacts/*; do+ name=$(basename "$file")+ # The mutable feed is published only after the immutable packages.+ [ "$name" != latest.json ] || continue+ if jq -e --arg name "$name" '.assets | any(.name == $name)' "$work_dir/release.json" >/dev/null; then+ gh release download "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --pattern "$name" --dir "$work_dir"+ cmp "$file" "$work_dir/$name"+ else+ gh release upload "$RELEASE_TAG" "$file" --repo "$RELEASE_REPOSITORY"+ fi+done++# A dedicated prerelease hosts only the mutable pointer. It never becomes the+# public download page's latest release, nor follows SDK/daemon release tags.+if gh release view desktop-stable --repo "$RELEASE_REPOSITORY" --json assets > "$work_dir/channel.json"; then+ if jq -e '.assets | any(.name == "latest.json")' "$work_dir/channel.json" >/dev/null; then+ gh release download desktop-stable --repo "$RELEASE_REPOSITORY" --pattern latest.json --dir "$work_dir"+ result=0+ nix develop --command bun apps/web/scripts/desktop-release.mjs newer \+ release-artifacts/latest.json "$work_dir/latest.json" || result=$?+ if [ "$result" -eq 2 ]; then+ echo "A matching or newer desktop release is already promoted."+ exit 0+ fi+ [ "$result" -eq 0 ] || exit "$result"+ fi+else+ # Do not mistake an authentication/network error for an absent release.+ gh api --paginate --slurp "repos/$RELEASE_REPOSITORY/releases" > "$work_dir/releases.json"+ if jq -e '.[][] | select(.tag_name == "desktop-stable")' "$work_dir/releases.json" >/dev/null; then+ echo "Could not read the existing desktop update channel" >&2+ exit 1+ fi+ gh release create desktop-stable --repo "$RELEASE_REPOSITORY" --target "$RELEASE_TAG" \+ --prerelease --latest=false --title "Desktop stable update feed" \+ --notes "Update metadata only. Download installers from a versioned desktop release."+fi+gh release upload desktop-stable release-artifacts/latest.json --repo "$RELEASE_REPOSITORY" --clobber+gh release edit "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --latestdiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/sign_desktop_updates.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/sign_desktop_updates.shnew file mode 100644index 0000000000..faa40dd5dd--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/sign_desktop_updates.sh@@ -0,0 +1,51 @@+set -euo pipefail++# All private material stays on the ephemeral runner, outside Nix derivations.+umask 077+credentials_dir=$(mktemp -d)+trap 'rm -rf "$credentials_dir"' EXIT+curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=macos-release&config=prd&format=json&secrets=TAURI_SIGNING_PRIVATE_KEY,TAURI_SIGNING_PRIVATE_KEY_PASSWORD' \+ > "$credentials_dir/secrets.json"+jq -er '.TAURI_SIGNING_PRIVATE_KEY | strings | select(length > 0)' \+ "$credentials_dir/secrets.json" > "$credentials_dir/updater.key"+export TAURI_SIGNING_PRIVATE_KEY_PATH="$credentials_dir/updater.key"+TAURI_SIGNING_PRIVATE_KEY_PASSWORD=$(jq -r '.TAURI_SIGNING_PRIVATE_KEY_PASSWORD // ""' "$credentials_dir/secrets.json")+export TAURI_SIGNING_PRIVATE_KEY_PASSWORD++# Verify against the public key compiled into BOTH packages before publishing.+jq -er '.publicKey | select(length > 0)' release-artifacts/darwin-aarch64.release.json > "$credentials_dir/mac.pub"+jq -er '.publicKey | select(length > 0)' release-artifacts/linux-x86_64.release.json > "$credentials_dir/linux.pub"+cmp "$credentials_dir/mac.pub" "$credentials_dir/linux.pub"+base64 --decode "$credentials_dir/mac.pub" > "$credentials_dir/minisign.pub"+if ! gh release view "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --json assets > "$credentials_dir/release.json"; then+ # Reading the collection must succeed before treating the version as absent.+ gh api --paginate --slurp "repos/$RELEASE_REPOSITORY/releases" > "$credentials_dir/releases.json"+ if jq -e --arg tag "$RELEASE_TAG" '.[][] | select(.tag_name == $tag)' "$credentials_dir/releases.json" >/dev/null; then+ echo "Could not inspect existing release assets" >&2+ exit 1+ fi+ printf '{"assets":[]}' > "$credentials_dir/release.json"+fi+shopt -s nullglob+artifacts=(release-artifacts/*.app.tar.gz release-artifacts/*.AppImage)+if [ "${#artifacts[@]}" -ne 2 ]; then+ echo "Expected one macOS and one Linux updater artifact" >&2+ exit 1+fi+for artifact in "${artifacts[@]}"; do+ name=$(basename "$artifact")+ if jq -e --arg name "$name.sig" '.assets | any(.name == $name)' "$credentials_dir/release.json" >/dev/null; then+ # Signatures include signing time. Reuse a previously published signature+ # only after checking both the immutable package bytes and its signature.+ gh release download "$RELEASE_TAG" --repo "$RELEASE_REPOSITORY" --pattern "$name" --pattern "$name.sig" --dir "$credentials_dir"+ cmp "$artifact" "$credentials_dir/$name"+ cp "$credentials_dir/$name.sig" "$artifact.sig"+ else+ nix shell --inputs-from . nixpkgs#cargo-tauri --command cargo-tauri signer sign "$artifact"+ fi+ base64 --decode "$artifact.sig" > "$credentials_dir/artifact.minisig"+ nix shell --inputs-from . nixpkgs#minisign --command minisign \+ -Vm "$artifact" -p "$credentials_dir/minisign.pub" -x "$credentials_dir/artifact.minisig"+done