Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Seanaye/feat/improve autoupdate ux (#2733)

Sean Aye7051af3942e7
diff --git a/.github/workflows/deploy-web-app.yml b/.github/workflows/deploy-web-app.yml
index d48b0018e1..38a73b98a5 100644
--- a/.github/workflows/deploy-web-app.yml
+++ b/.github/workflows/deploy-web-app.yml
@@ -49,9 +49,6 @@ concurrency:
# We do not want to cancel a deployment if it's in progress. That could lead to a broken deployment.
cancel-in-progress: false
-env:
- WEB_APP_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || '0.0.0' }}
-
jobs:
build-deploy:
runs-on: linux-latest-beefy
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.yml
index 5b8e9620e7..27cbde79c6 100644
--- a/.github/workflows/release-production.yml
+++ b/.github/workflows/release-production.yml
@@ -9,7 +9,6 @@ concurrency:
env:
MODE: "production"
- WEB_APP_VERSION: ${{ github.ref_name }}
jobs:
migrate-db:
@@ -126,8 +125,8 @@ jobs:
name: web-app-prod-build
path: js/app/packages/app/dist
- name: Create Web App Artifact
- run: tar -czf web-app-${{ env.WEB_APP_VERSION }}.tar.gz -C js/app/packages/app/dist .
+ run: tar -czf web-app-${{ github.ref_name }}.tar.gz -C js/app/packages/app/dist .
- name: Upload Release Artifacts
uses: softprops/action-gh-release@v2
with:
- files: web-app-${{ env.WEB_APP_VERSION }}.tar.gz
+ files: web-app-${{ github.ref_name }}.tar.gz
diff --git a/js/app/packages/app/component/BundleUpdateProgressBar.tsx b/js/app/packages/app/component/BundleUpdateProgressBar.tsx
new file mode 100644
index 0000000000..d985fd5d58
--- /dev/null
+++ b/js/app/packages/app/component/BundleUpdateProgressBar.tsx
@@ -0,0 +1,50 @@
+import { toast } from '@core/component/Toast/Toast';
+import { useTauri } from '@macro/tauri';
+import { invoke } from '@tauri-apps/api/core';
+import { Show, createEffect, createMemo, on } from 'solid-js';
+
+export function BundleUpdateProgressBar() {
+ const tauri = useTauri();
+
+ const status = createMemo(() => tauri?.bundleUpdateStatus().status);
+
+ const progress = createMemo(() => {
+ const s = tauri?.bundleUpdateStatus();
+ if (!s) return null;
+ switch (s.status) {
+ case 'Downloading':
+ return s.data.progress * 0.95;
+ case 'Unzipping':
+ return 95 + s.data.progress * 0.05;
+ default:
+ return null;
+ }
+ });
+
+ createEffect(
+ on(status, (cur, prev) => {
+ if (prev !== 'Completed' && cur === 'Completed') {
+ toast.success('Update downloaded', 'Tap to apply update', [
+ {
+ label: 'Update',
+ onClick: () =>
+ invoke('perform_update').catch((e) =>
+ console.error('[bundle-update] perform_update failed', e)
+ ),
+ },
+ ]);
+ }
+ })
+ );
+
+ return (
+ <Show when={progress() !== null}>
+ <div class="w-full h-0.5 bg-surface-2">
+ <div
+ class="h-full bg-accent transition-[width] duration-200 ease-linear"
+ style={{ width: `${progress() ?? 0}%` }}
+ />
+ </div>
+ </Show>
+ );
+}
diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsx
index 552ccf1565..42b9b44b1b 100644
--- a/js/app/packages/app/component/Layout.tsx
+++ b/js/app/packages/app/component/Layout.tsx
@@ -21,6 +21,7 @@ import {
Suspense,
} from 'solid-js';
import Banner from './banner/Banner';
+import { BundleUpdateProgressBar } from './BundleUpdateProgressBar';
import { GlobalBulkEditEntityModal } from './bulk-edit-entity/BulkEditEntityModal';
import { GlobalShareModal } from './global-share-modal/GlobalShareModal';
import { MacroMcpSetupModal } from './macro-mcp-setup-modal/MacroMcpSetupModal';
@@ -137,6 +138,7 @@ function LayoutInner(props: RouteSectionProps) {
}
)}
>
+ <BundleUpdateProgressBar />
<Suspense>
<Show when={isAuthenticated()}>
<GlobalShortcuts />
diff --git a/js/app/packages/app/package.json b/js/app/packages/app/package.json
index 711bab1d24..a4f8b167d0 100644
--- a/js/app/packages/app/package.json
+++ b/js/app/packages/app/package.json
@@ -17,12 +17,12 @@
"build:desktop": "VITE_PLATFORM=desktop vite build -c vite.desktop.config.ts && bun run postbuild:semver",
"build:ios": "VITE_PLATFORM=ios vite build -c vite.ios.config.ts && bun run postbuild:semver",
"build:android": "VITE_PLATFORM=android vite build -c vite.android.config.ts && bun run postbuild:semver",
- "postbuild:semver": "echo $npm_package_version >> ./dist/semver.txt",
+ "postbuild:semver": "echo $npm_package_version+$(git rev-parse --short HEAD) > ./dist/semver.txt",
"preview:dev": "vite preview -c vite-ci.config.ts --outDir dist --base /app",
"preview:prod": "vite preview -c vite-ci.config.ts --outDir dist --base /app",
"check": "tsc --noEmit --skipLibCheck",
- "ddupload:dev": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $WEB_APP_VERSION --minified-path-prefix https://dev.macro.com/app",
- "ddupload:prod": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $WEB_APP_VERSION --minified-path-prefix https://macro.com/app"
+ "ddupload:dev": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $(cat ./dist/semver.txt) --minified-path-prefix https://dev.macro.com/app",
+ "ddupload:prod": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $(cat ./dist/semver.txt) --minified-path-prefix https://macro.com/app"
},
"dependencies": {
"@macro/tauri": "workspace:*",
diff --git a/js/app/packages/app/vite.base.ts b/js/app/packages/app/vite.base.ts
index 7d6c438ede..34bad3a92a 100644
--- a/js/app/packages/app/vite.base.ts
+++ b/js/app/packages/app/vite.base.ts
@@ -1,3 +1,4 @@
+import { execSync } from 'node:child_process';
import { resolve } from 'node:path';
import tailwind from '@tailwindcss/vite';
import { Features } from 'lightningcss';
@@ -10,6 +11,9 @@ import tsconfigpaths from 'vite-tsconfig-paths';
// @ts-ignore
import { version } from './package.json';
+const shortSha = execSync('git rev-parse --short HEAD').toString().trim();
+const appVersion = `${version}+${shortSha}`;
+
const PLATFORMS = ['web', 'desktop', 'ios', 'android'] as const;
export type AppPlatform = (typeof PLATFORMS)[number];
@@ -167,9 +171,7 @@ function getAssetsPath(mode: string, command: string): string {
function defineEnv(mode: string, command: string, platform: AppPlatform) {
return {
- 'import.meta.env.__APP_VERSION__': JSON.stringify(
- process.env.WEB_APP_VERSION || version
- ),
+ 'import.meta.env.__APP_VERSION__': JSON.stringify(appVersion),
'import.meta.env.VITE_PLATFORM': JSON.stringify(platform),
'import.meta.env.ASSETS_PATH': JSON.stringify(getAssetsPath(mode, command)),
'import.meta.env.__LOCAL_DOCKER__': process.env.LOCAL_DOCKER === 'true',
diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsx
index 663ba8cf31..8492a443de 100644
--- a/js/app/packages/tauri/src/TauriProvider.tsx
+++ b/js/app/packages/tauri/src/TauriProvider.tsx
@@ -5,6 +5,7 @@ import { type OsType, type as osType } from '@tauri-apps/plugin-os';
import {
type Accessor,
createContext,
+ createEffect,
createSignal,
type JSX,
onCleanup,
@@ -14,7 +15,6 @@ import {
import { getInsets, type Insets } from 'tauri-plugin-safe-area-insets';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
-import { listenForHeartbeat } from './heartbeat';
import { useTauriNavigationEffect } from './navigation';
import { MaybePushNotificationRegistration } from './PushNotification';
@@ -54,8 +54,19 @@ function TauriProvider(props: { children: JSX.Element }) {
bundleUpdateStatus,
};
+ // Auto-approve download when an update is found so the user only
+ // needs to confirm the final "Update" step.
+ createEffect(() => {
+ const status = bundleUpdateStatus();
+ if (status.status === 'UpdateFound') {
+ console.info('[bundle-update] update found, auto-approving download');
+ invoke('grant_bundle_update', { approved: true }).catch((e) =>
+ console.error('[bundle-update] grant_bundle_update failed', e)
+ );
+ }
+ });
+
onMount(() => {
- listenForHeartbeat();
console.info('[bundle-update] registering listener');
const unlistenPromise = listen<BundleUpdateStatus>(
'bundle-update-status',
diff --git a/js/app/packages/tauri/src/heartbeat.ts b/js/app/packages/tauri/src/heartbeat.ts
deleted file mode 100644
index 277ce3ccf3..0000000000
--- a/js/app/packages/tauri/src/heartbeat.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { invoke } from '@tauri-apps/api/core';
-import { listen } from '@tauri-apps/api/event';
-
-/**
- * Registers a permanent listener for heartbeat pings from the native side.
- *
- * This listener is intentionally never cleaned up — it must remain active
- * for the entire app lifecycle to respond to resume pings.
- */
-export function listenForHeartbeat() {
- listen('heartbeat_ping', () => {
- invoke('heartbeat_response');
- });
-}
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain.rs
index 901e625fda..fab9215a53 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain.rs
@@ -1,3 +1,6 @@
+/// Data types and error definitions for bundle updates.
pub mod models;
+/// Trait definitions (ports) for update, filesystem, and system queries.
pub mod ports;
+/// Core update service and background worker.
pub mod service;
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
index 76ae8f263c..caae4cf018 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
@@ -5,13 +5,107 @@ use thiserror::Error;
use tokio::sync::mpsc::{Receiver, channel};
use url::Url;
+use super::ports::FsRepo;
+
+/// Name of the file used to persist the bundle root path across restarts.
+const BUNDLE_ROOT_FILE: &str = "bundle_root";
+
+/// Swappable root directory for serving frontend assets.
+/// `None` = use built-in asset resolver (initial bundle from `frontendDist`).
+/// `Some(path)` = serve files from this directory (after OTA update).
+pub(crate) struct BundleRoot(Option<PathBuf>);
+
+impl BundleRoot {
+ /// Create an empty bundle root (no OTA update applied).
+ pub(crate) fn new() -> Self {
+ Self(None)
+ }
+
+ /// Create a bundle root pointing to the given path.
+ pub(crate) fn from_path(path: PathBuf) -> Self {
+ Self(Some(path))
+ }
+
+ /// Load persisted bundle root from the given cache directory.
+ pub(crate) async fn load(cache_dir: &Path, fs: &impl FsRepo) -> Self {
+ let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
+ tracing::info!("Loading bundle root from {persist_path:?}");
+ match fs.read_to_string(&persist_path).await {
+ Ok(contents) => {
+ let path = PathBuf::from(contents.trim());
+ let index = path.join("index.html");
+ if fs.read_to_string(&index).await.is_ok() {
+ tracing::info!("Restored bundle root: {path:?}");
+ Self(Some(path))
+ } else {
+ tracing::warn!(
+ "Persisted bundle root {path:?} missing index.html at {index:?}"
+ );
+ if let Err(e) = fs.remove_file(&persist_path).await {
+ tracing::debug!("Failed to remove stale bundle_root file: {e}");
+ }
+ Self(None)
+ }
+ }
+ Err(e) => {
+ tracing::info!("No persisted bundle root: {e}");
+ Self(None)
+ }
+ }
+ }
+
+ /// Persist the bundle root path so it survives app restarts.
+ pub(crate) async fn persist(
+ &self,
+ cache_dir: &Path,
+ fs: &impl FsRepo,
+ ) -> Result<(), std::io::Error> {
+ let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
+ match self.0.as_ref() {
+ Some(root) => {
+ tracing::info!("Persisting bundle root {root:?} to {persist_path:?}");
+ fs.write(&persist_path, root.to_string_lossy().as_bytes()).await
+ }
+ None => fs.remove_file(&persist_path).await,
+ }
+ }
+
+ /// Get the current bundle root path, if any.
+ pub(crate) fn path(&self) -> Option<&Path> {
+ self.0.as_deref()
+ }
+
+ /// Set the bundle root to a new path.
+ pub(crate) fn set(&mut self, path: PathBuf) {
+ self.0 = Some(path);
+ }
+
+ /// Clear the bundle root, reverting to the built-in assets.
+ pub(crate) fn clear(&mut self) {
+ self.0 = None;
+ }
+
+ /// Read the bundle version from `semver.txt` inside the bundle root.
+ pub(crate) async fn version(&self, fs: &impl FsRepo) -> Option<semver::Version> {
+ let semver_path = self.0.as_ref()?.join("semver.txt");
+ fs.read_to_string(&semver_path)
+ .await
+ .ok()
+ .and_then(|s| s.trim().parse().ok())
+ }
+}
+
/// the bounded size of mpsc channels
const MPSC_CHAN_SIZE: usize = 10;
+/// Application metadata sent to the update server.
#[derive(Debug, Clone)]
pub struct AppInfo {
+ /// The currently running app version.
pub current_version: semver::Version,
+ /// CPU architecture.
pub arch: Arch,
+ /// Operating system target.
pub target: Target,
}
@@ -63,6 +157,7 @@ pub struct BundleUpdate {
}
impl BundleUpdate {
+ /// Convert into a download request targeting `destination`, returning a progress receiver.
pub fn into_download_request<P: AsRef<Path>>(
self,
destination: P,
@@ -79,12 +174,14 @@ impl BundleUpdate {
}
}
+/// Tracks progress as a numerator/denominator pair.
pub struct Progress {
numerator: usize,
denominator: usize,
}
impl Progress {
+ /// Create a progress tracker with the given total.
pub fn from_total(total: usize) -> Self {
Progress {
numerator: 0,
@@ -92,14 +189,17 @@ impl Progress {
}
}
+ /// Increment the numerator by `step`.
pub fn inc_by(&mut self, step: usize) {
self.numerator += step;
}
+ /// Set the numerator to an absolute value.
pub fn set(&mut self, numerator: usize) {
self.numerator = numerator;
}
+ /// Compute the current percentage (0.0–100.0).
pub fn percentage(&self) -> ProgressPercentage {
if self.denominator == 0 {
return ProgressPercentage(0.0);
@@ -120,26 +220,35 @@ impl ProgressPercentage {
Self(100.0)
}
+ /// Get the raw percentage value.
pub fn value(self) -> f64 {
self.0
}
}
+/// Parameters for downloading a bundle zip.
#[non_exhaustive]
pub struct DownloadBundleRequest<P> {
+ /// URL to download the zip from.
pub url: Url,
+ /// Local path to write the downloaded file.
pub destination: P,
+ /// Channel for streaming download progress.
pub on_progress: tokio::sync::mpsc::Sender<ProgressPercentage>,
}
+/// Errors that can occur during bundle download.
#[derive(Debug, Error)]
pub enum DownloadBundleError {
+ /// File I/O failed during download.
#[error("An error occurred reading the file")]
FileError,
+ /// An unexpected error occurred.
#[error("An unknown error occurred")]
OtherError,
}
+/// Parameters for extracting a downloaded bundle zip.
#[non_exhaustive]
pub struct UnzipRequest {
/// the path of the zip file
@@ -151,6 +260,7 @@ pub struct UnzipRequest {
}
impl UnzipRequest {
+ /// Create a new unzip request, returning the request and a progress receiver.
pub fn new(
archive_path: PathBuf,
archive_target: PathBuf,
@@ -167,16 +277,32 @@ impl UnzipRequest {
}
}
+/// Errors that can occur during bundle extraction.
#[derive(Debug, Error)]
pub enum UnzipError {
+ /// The archive file was not found at the expected path.
#[error("Could not find the archive at {path}")]
- ArchiveNotFound { path: PathBuf },
+ ArchiveNotFound {
+ /// The path that was searched.
+ path: PathBuf,
+ },
+ /// SHA-256 digest of the downloaded file did not match.
#[error("Checksum mismatch: expected {expected}, got {actual}")]
- ChecksumMismatch { expected: String, actual: String },
+ ChecksumMismatch {
+ /// Expected hex digest.
+ expected: String,
+ /// Actual hex digest.
+ actual: String,
+ },
+ /// An I/O error occurred.
#[error(transparent)]
IoErr(#[from] std::io::Error),
+ /// An unexpected error occurred.
#[error("{report}")]
- Other { report: rootcause::Report },
+ Other {
+ /// The underlying error report.
+ report: rootcause::Report,
+ },
}
impl From<rootcause::Report> for UnzipError {
@@ -185,16 +311,22 @@ impl From<rootcause::Report> for UnzipError {
}
}
+/// Top-level errors for the update state machine.
#[derive(Debug, Error)]
pub enum UpdateError {
+ /// The download step failed.
#[error("Failed to download the update")]
DownloadErr,
+ /// Extraction or checksum verification failed.
#[error("Failed to unzip the update")]
Unzip,
+ /// User approval could not be obtained.
#[error("Failed to grant permission to update")]
GrantErr,
+ /// A filesystem I/O error occurred.
#[error("An io error occurred")]
IoErr,
+ /// An unexpected error occurred.
#[error("An unknown error occurred")]
Other,
}
@@ -204,6 +336,7 @@ pub enum UpdateError {
pub struct UpdateGranted(());
impl UpdateGranted {
+ /// Create a new granted token.
pub fn new() -> Self {
UpdateGranted(())
}
@@ -214,48 +347,72 @@ impl UpdateGranted {
pub struct UpdateDenied(());
impl UpdateDenied {
+ /// Create a new denied token.
pub fn new() -> Self {
UpdateDenied(())
}
}
+/// Whether the user approved or denied a pending update.
#[derive(Debug, Clone)]
pub enum UpdateApproval {
+ /// User approved the update.
Granted(UpdateGranted),
+ /// User denied the update.
Denied(UpdateDenied),
}
+/// An available update has been found.
#[derive(Debug, Clone)]
pub struct UpdateFoundStatus {
+ /// The bundle update metadata.
pub bundle: BundleUpdate,
}
+/// A bundle download is in progress.
#[derive(Debug, Clone)]
pub struct UpdateDownloadingStatus {
+ /// Proof that the user approved this download.
pub grant: UpdateGranted,
+ /// The bundle being downloaded.
pub update: BundleUpdate,
+ /// Current download progress.
pub progress: ProgressPercentage,
}
+/// A bundle extraction is in progress.
#[derive(Debug, Clone)]
pub struct UnzipStatus {
+ /// Path to the zip archive being extracted.
pub zip_filename: PathBuf,
+ /// Expected SHA-256 hex digest.
pub expected_checksum: String,
+ /// Current extraction progress.
pub progress: ProgressPercentage,
}
+/// The update has been fully downloaded and extracted.
#[derive(Debug, Clone)]
pub struct CompletedStatus {
+ /// Path to the extracted `index.html` entrypoint.
pub entrypoint: PathBuf,
}
+/// Current state of the update state machine.
#[derive(Debug, Clone)]
pub enum UpdateStatus {
+ /// No update activity.
Idle,
+ /// Querying the server for available updates.
CheckingForDownload(AppInfo),
+ /// An update is available and awaiting approval.
UpdateFound(UpdateFoundStatus),
+ /// The app is already on the latest version.
NoUpdateNeeded,
+ /// The bundle zip is being downloaded.
DownloadingBundle(UpdateDownloadingStatus),
+ /// The downloaded zip is being extracted.
UnzippingBundle(UnzipStatus),
+ /// The update has been applied successfully.
Completed(CompletedStatus),
}
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs
index 7f4d790287..f1dca65266 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs
@@ -6,43 +6,87 @@ use crate::domain::models::{
};
use std::path::{Path, PathBuf};
+/// Port for communicating with the update server.
pub trait UpdateRepo: Send + Sync + 'static {
+ /// Check whether a newer bundle version is available.
fn check_for_update(
&self,
request: AppInfo,
) -> impl Future<Output = Result<Option<BundleUpdate>, rootcause::Report>> + Send;
+ /// Download the bundle zip to a local path, streaming progress.
fn get_update_bundle<P: AsRef<Path> + Send>(
&self,
request: DownloadBundleRequest<P>,
) -> impl Future<Output = Result<(), Report<DownloadBundleError>>> + Send;
}
-pub trait FsRepo: Send + Sync + 'static {
+/// Port for filesystem operations (checksum, extract, I/O).
+pub trait FsRepo: Clone + Send + Sync + 'static {
+ /// Verify that the file at `path` has the expected SHA-256 hex digest.
fn verify_checksum<P: AsRef<Path> + Send>(
&self,
path: P,
expected: &str,
) -> impl Future<Output = Result<(), UnzipError>> + Send;
+ /// Extract a zip archive, streaming progress.
fn unzip(
&self,
request: UnzipRequest,
) -> impl Future<Output = Result<PathBuf, UnzipError>> + Send;
+ /// Recursively create directories.
fn create_dir_all<P: AsRef<Path> + Send>(
&self,
path: P,
) -> impl Future<Output = Result<(), std::io::Error>> + Send;
+
+ /// List the names of immediate children in `dir`.
+ fn list_dir_names(
+ &self,
+ dir: &Path,
+ ) -> impl Future<Output = Vec<String>> + Send;
+
+ /// Recursively remove a directory.
+ fn remove_dir_all(
+ &self,
+ dir: &Path,
+ ) -> impl Future<Output = Result<(), std::io::Error>> + Send;
+
+ /// Read a file's contents as a string.
+ fn read_to_string(
+ &self,
+ path: &Path,
+ ) -> impl Future<Output = Result<String, std::io::Error>> + Send;
+
+ /// Write bytes to a file, creating or overwriting it.
+ fn write(
+ &self,
+ path: &Path,
+ contents: &[u8],
+ ) -> impl Future<Output = Result<(), std::io::Error>> + Send;
+
+ /// Remove a file. Returns `Ok(())` if the file does not exist.
+ fn remove_file(
+ &self,
+ path: &Path,
+ ) -> impl Future<Output = Result<(), std::io::Error>> + Send;
}
+/// Port for querying system metadata (version, arch, cache dirs).
pub trait SystemQuery: Send + Sync + 'static {
+ /// Return the current app version, architecture, and OS target.
fn get_system_info(&self) -> impl Future<Output = Result<AppInfo, rootcause::Report>> + Send;
+ /// Return the directory where update bundles should be stored.
fn get_update_dir(&self) -> impl Future<Output = Result<PathBuf, std::io::Error>> + Send;
}
+/// Interface for the update service exposed to the plugin layer.
pub trait AutoUpdateService: 'static {
+ /// Get a receiver for the current update status.
fn status(&self) -> &tokio::sync::watch::Receiver<Result<UpdateStatus, Report<UpdateError>>>;
+
/// Try to receive the oneshot sender the worker offered for grant/deny.
/// Returns `Err` if the worker hasn't offered one yet.
fn try_recv_grant_sender(
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
index 53b4039f57..2633f090f8 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
@@ -1,16 +1,18 @@
use crate::domain::{
models::{
- CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus, UpdateApproval,
- UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
+ BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus,
+ UpdateApproval, UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
},
ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},
};
use rootcause::{Report, prelude::ResultExt, report};
-use semver::Version;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
-pub struct Service {
+/// Manages the update worker and the active bundle root.
+pub struct Service<Fs: FsRepo> {
handle: WorkerHandle,
+ fs_repo: Fs,
+ bundle_root: BundleRoot,
}
/// Sender half the worker uses to offer a oneshot back to the main thread.
@@ -119,9 +121,21 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
.context(UpdateError::DownloadErr)?;
match res {
- Some(update) => Ok(UpdateStatus::UpdateFound(UpdateFoundStatus {
- bundle: update,
- })),
+ Some(update) => {
+ // Check if this version was already downloaded in a previous session.
+ if let Ok(update_dir) = self.system_query.get_update_dir().await {
+ if let Some(entrypoint) =
+ find_cached_bundle(&self.fs_repo, &update_dir, &update.version).await
+ {
+ return Ok(UpdateStatus::Completed(CompletedStatus {
+ entrypoint,
+ }));
+ }
+ }
+ Ok(UpdateStatus::UpdateFound(UpdateFoundStatus {
+ bundle: update,
+ }))
+ }
None => Ok(UpdateStatus::NoUpdateNeeded),
}
}
@@ -156,7 +170,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
.context(UpdateError::IoErr)?;
let download_filename = self
- .create_download_directory(update_dir, &status.update.version)
+ .create_download_directory(update_dir)
.await
.context(UpdateError::IoErr)?;
@@ -213,21 +227,71 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
}
}
- /// given an input directory and a semver, create a folder for the semver and return the path
- /// that the download should be placed at
+ /// Create a monotonically increasing download directory and return the
+ /// path where the zip should be placed.
async fn create_download_directory(
&self,
mut bundle: PathBuf,
- version: &Version,
) -> Result<PathBuf, std::io::Error> {
- let version_str = version.to_string().to_lowercase();
- bundle.push(PathBuf::from(version_str));
+ let next = next_bundle_index(&self.fs_repo.list_dir_names(&bundle).await);
+ bundle.push(next.to_string());
self.fs_repo.create_dir_all(&bundle).await?;
bundle.push("bundle.zip");
Ok(bundle)
}
}
+/// Determine the next monotonic bundle index from a list of directory names.
+pub(crate) fn next_bundle_index(names: &[String]) -> u64 {
+ names
+ .iter()
+ .filter_map(|n| n.parse::<u64>().ok())
+ .max()
+ .map_or(0, |m| m + 1)
+}
+
+/// Search existing numeric bundle directories for one whose `semver.txt`
+/// matches `version`. Returns the entrypoint path if found.
+async fn find_cached_bundle(
+ fs: &impl FsRepo,
+ update_dir: &std::path::Path,
+ version: &semver::Version,
+) -> Option<PathBuf> {
+ let version_str = version.to_string();
+ let names = fs.list_dir_names(update_dir).await;
+ tracing::info!(
+ "find_cached_bundle: looking for version {version_str} in {update_dir:?}, found dirs: {names:?}"
+ );
+ for name in names {
+ if name.parse::<u64>().is_err() {
+ continue;
+ }
+ let dir = update_dir.join(&name);
+ let semver_path = dir.join("semver.txt");
+ match fs.read_to_string(&semver_path).await {
+ Ok(contents) => {
+ tracing::info!(
+ "find_cached_bundle: {semver_path:?} contains {:?}, want {version_str:?}",
+ contents.trim()
+ );
+ if contents.trim() == version_str {
+ let entrypoint = dir.join(ENTRYPOINT_NAME);
+ if fs.read_to_string(&entrypoint).await.is_ok() {
+ tracing::info!("find_cached_bundle: hit — reusing {entrypoint:?}");
+ return Some(entrypoint);
+ }
+ }
+ }
+ Err(e) => {
+ tracing::debug!("find_cached_bundle: no semver.txt in {dir:?}: {e}");
+ }
+ }
+ }
+ tracing::info!("find_cached_bundle: no cached bundle found for {version_str}");
+ None
+}
+
+
/// helper function which pipes the progress of an event from one channel into another
/// returning true if the value in the sender channel was modified
async fn glue_channels<F>(
@@ -245,18 +309,80 @@ async fn glue_channels<F>(
}
}
-impl Service {
- pub fn new<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery>(
+impl<Fs: FsRepo> Service<Fs> {
+ /// Create a new service, spawning the background update worker.
+ pub fn new<U: UpdateRepo, Q: SystemQuery>(
update_repo: U,
fs_repo: Fs,
system_query: Q,
) -> Self {
- let handle = Worker::new_handle(update_repo, fs_repo, system_query);
- Service { handle }
+ let handle = Worker::new_handle(update_repo, fs_repo.clone(), system_query);
+ Service {
+ handle,
+ fs_repo,
+ bundle_root: BundleRoot::new(),
+ }
+ }
+
+ /// Load persisted bundle root from the given cache directory.
+ pub async fn load_bundle_root(&mut self, cache_dir: &Path) {
+ self.bundle_root = BundleRoot::load(cache_dir, &self.fs_repo).await;
+ }
+
+ /// Get the current bundle root path, if an OTA update has been applied.
+ pub fn bundle_root_path(&self) -> Option<&Path> {
+ self.bundle_root.path()
+ }
+
+ /// Set the bundle root to a new directory and persist it.
+ ///
+ /// The in-memory state is only updated after persistence succeeds.
+ pub async fn set_bundle_root(
+ &mut self,
+ path: PathBuf,
+ cache_dir: &Path,
+ ) -> Result<(), std::io::Error> {
+ // Persist first — only commit in-memory if the write succeeds.
+ let new_root = BundleRoot::from_path(path);
+ new_root.persist(cache_dir, &self.fs_repo).await?;
+ self.bundle_root = new_root;
+ Ok(())
+ }
+
+ /// Clear the bundle root and remove all downloaded bundles.
+ pub async fn clear_bundle_root(&mut self, cache_dir: &Path) -> Result<(), std::io::Error> {
+ for name in self.fs_repo.list_dir_names(cache_dir).await {
+ if name.parse::<u64>().is_ok() {
+ let _ = self.fs_repo.remove_dir_all(&cache_dir.join(&name)).await;
+ }
+ }
+ self.bundle_root.clear();
+ self.bundle_root.persist(cache_dir, &self.fs_repo).await
+ }
+
+ /// Read the bundle version from `semver.txt` inside the current bundle root.
+ pub async fn bundle_version(&self) -> Option<semver::Version> {
+ self.bundle_root.version(&self.fs_repo).await
+ }
+
+ /// Remove all numeric bundle subdirectories under `dir` except `keep`.
+ pub async fn cleanup_old_bundles(&self, dir: &Path, keep: &Path) {
+ for name in self.fs_repo.list_dir_names(dir).await {
+ if name.parse::<u64>().is_err() {
+ continue;
+ }
+ let path = dir.join(&name);
+ if path == keep {
+ continue;
+ }
+ if let Err(e) = self.fs_repo.remove_dir_all(&path).await {
+ tracing::warn!(error=?e, "Failed to remove old bundle directory {path:?}");
+ }
+ }
}
}
-impl AutoUpdateService for Service {
+impl<Fs: FsRepo> AutoUpdateService for Service<Fs> {
fn status(&self) -> &tokio::sync::watch::Receiver<Result<UpdateStatus, Report<UpdateError>>> {
&self.handle.status_rx
}
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/inbound.rs b/js/app/tauri/macro_bundle_updater_plugin/src/inbound.rs
index 962cb1bb99..94929aa8db 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/inbound.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/inbound.rs
@@ -1 +1,2 @@
+/// Tauri plugin registration and command handlers.
pub mod plugin;
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
index 4ed7fdf89c..19c0b32bcb 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
@@ -1,4 +1,4 @@
-use std::sync::Mutex;
+use tokio::sync::Mutex;
use rootcause::Report;
use serde::Serialize;
@@ -14,26 +14,43 @@ use crate::{
outbound::{api_client::BundleClient, fs::FileSystem, system_info::SystemInfo},
};
+/// Concrete service type used by the plugin commands.
+pub type PluginService = Service<FileSystem>;
+
const EVENT_NAME: &str = "bundle-update-status";
+/// Serializable event emitted to the frontend via Tauri's event system.
#[derive(Clone, Serialize)]
#[serde(tag = "status", content = "data")]
pub enum BundleUpdateEvent {
+ /// No update activity.
Idle,
+ /// Checking the server for updates.
CheckingForUpdate,
+ /// An update is available.
UpdateFound {
+ /// The new version string.
version: String,
+ /// Optional release notes.
notes: Option<String>,
},
+ /// Already on the latest version.
NoUpdateNeeded,
+ /// Bundle download in progress.
Downloading {
+ /// Download progress percentage (0–100).
progress: f64,
},
+ /// Bundle extraction in progress.
Unzipping {
+ /// Extraction progress percentage (0–100).
progress: f64,
},
+ /// Update applied successfully.
Completed,
+ /// An error occurred during the update.
Error {
+ /// Human-readable error message.
message: String,
},
}
@@ -62,22 +79,25 @@ impl BundleUpdateEvent {
}
}
+/// Tauri plugin that manages OTA bundle updates.
pub struct MacroBundleUpdaterPlugin {
base_url: Url,
}
impl MacroBundleUpdaterPlugin {
+ /// Create the plugin targeting the given update server URL.
pub fn new(base_url: Url) -> Self {
Self { base_url }
}
}
+/// Approve or deny a pending bundle update.
#[tauri::command]
-pub fn grant_bundle_update(
- service: tauri::State<'_, Mutex<Service>>,
+pub async fn grant_bundle_update(
+ service: tauri::State<'_, Mutex<PluginService>>,
approved: bool,
) -> Result<(), String> {
- let mut service = service.lock().unwrap();
+ let mut service = service.lock().await;
let grant_tx = service.try_recv_grant_sender().map_err(|e| e.to_string())?;
let approval = if approved {
UpdateApproval::Granted(UpdateGranted::new())
@@ -89,16 +109,14 @@ pub fn grant_bundle_update(
.map_err(|_| "Worker dropped the grant receiver".to_string())
}
+/// Apply a completed bundle update: set the bundle root and navigate to it.
#[tauri::command]
-#[tracing::instrument(err, skip(service, bundle_root, app_handle))]
-pub fn perform_update<R: Runtime>(
- service: tauri::State<'_, Mutex<Service>>,
- bundle_root: tauri::State<'_, crate::BundleRoot>,
+#[tracing::instrument(err, skip(service, app_handle))]
+pub async fn perform_update<R: Runtime>(
+ service: tauri::State<'_, Mutex<PluginService>>,
app_handle: tauri::AppHandle<R>,
) -> Result<(), String> {
- let Ok(service) = service.lock() else {
- return Err("autoupdate state mutex is poisoned".to_string());
- };
+ let mut service = service.lock().await;
let entrypoint = {
let status = service.status().borrow();
match status.as_ref() {
@@ -107,46 +125,80 @@ pub fn perform_update<R: Runtime>(
}
};
- // Set the bundle root to the parent of index.html (the unzipped directory)
let bundle_dir = entrypoint
.parent()
.ok_or_else(|| format!("entrypoint {entrypoint:?} has no parent directory"))?
.to_path_buf();
- tracing::info!("Setting bundle root to {bundle_dir:?}");
- *bundle_root.0.write().map_err(|e| e.to_string())? = Some(bundle_dir);
- // Persist so subsequent restarts use the updated bundle
let cache_dir = app_handle
.path()
.app_cache_dir()
.map_err(|e| e.to_string())?;
- bundle_root.persist(&cache_dir).map_err(|e| e.to_string())?;
- // Navigate to the updated bundle, preserving the current hash route.
+ tracing::info!("Setting bundle root to {bundle_dir:?}");
+ service
+ .set_bundle_root(bundle_dir.clone(), &cache_dir)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ // Remove old bundle directories now that we've switched to the new one
+ service.cleanup_old_bundles(&cache_dir, &bundle_dir).await;
+
+ drop(service);
+
+ // Reload to pick up the new bundle. Using location.reload() instead of
+ // navigating to a new URL preserves WKWebView's cookie store.
if let Some(webview) = app_handle.webview_windows().values().next() {
- tracing::info!("Bundle update complete, navigating to updated bundle");
- let _ = webview.eval(
- "window.location.href = 'tauri://localhost/app/index.html' + window.location.hash;",
- );
+ tracing::info!("Bundle update complete, reloading to pick up new assets");
+ let _ = webview.eval("window.location.reload();");
}
Ok(())
}
+/// Trigger a manual check for bundle updates.
#[tauri::command]
-pub fn check_for_update(service: tauri::State<'_, Mutex<Service>>) -> Result<(), String> {
- let service = service.lock().unwrap();
+pub async fn check_for_update(
+ service: tauri::State<'_, Mutex<PluginService>>,
+) -> Result<(), String> {
+ let service = service.lock().await;
service.start().map_err(|e| e.to_string())
}
+/// Return the current bundle update status as a serializable event.
#[tauri::command]
-pub fn get_bundle_update_status(
- service: tauri::State<'_, Mutex<Service>>,
+pub async fn get_bundle_update_status(
+ service: tauri::State<'_, Mutex<PluginService>>,
) -> Result<BundleUpdateEvent, String> {
- let service = service.lock().unwrap();
+ let service = service.lock().await;
let status = service.status().borrow();
Ok(BundleUpdateEvent::new(&status))
}
+/// Clear the downloaded bundle and revert to built-in assets.
+#[tauri::command]
+pub async fn clear_bundle<R: Runtime>(
+ service: tauri::State<'_, Mutex<PluginService>>,
+ app_handle: tauri::AppHandle<R>,
+) -> Result<(), String> {
+ let cache_dir = app_handle
+ .path()
+ .app_cache_dir()
+ .map_err(|e| e.to_string())?;
+
+ service
+ .lock()
+ .await
+ .clear_bundle_root(&cache_dir)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ tracing::info!("Bundle cleared, reloading to revert to built-in assets");
+ if let Some(webview) = app_handle.webview_windows().values().next() {
+ let _ = webview.eval("window.location.reload();");
+ }
+ Ok(())
+}
+
impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
fn name(&self) -> &'static str {
"macro-bundle-updater"
@@ -165,7 +217,7 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
let mut status_rx = service.status().clone();
let _ = service.start();
- app.manage(Mutex::new(service));
+ app.manage(tokio::sync::Mutex::new(service));
let app_handle = app.clone();
tauri::async_runtime::spawn(async move {
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs b/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
index e46b34ad5a..996f113e34 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
@@ -1,65 +1,9 @@
-use std::path::{Path, PathBuf};
-use std::sync::RwLock;
+#![deny(missing_docs)]
+//! Tauri plugin for OTA bundle updates.
+/// contains domain level business logic
pub mod domain;
+/// adapter for incoming data into the service
pub mod inbound;
+/// the outbound implementations of ports
pub mod outbound;
-
-/// Name of the file used to persist the bundle root path across restarts.
-const BUNDLE_ROOT_FILE: &str = "bundle_root";
-
-/// Swappable root directory for serving frontend assets.
-/// `None` = use built-in asset resolver (initial bundle from `frontendDist`).
-/// `Some(path)` = serve files from this directory (after OTA update).
-pub struct BundleRoot(pub RwLock<Option<PathBuf>>);
-
-impl BundleRoot {
- /// Load persisted bundle root from the given cache directory.
- /// Returns `BundleRoot(None)` if no persisted path exists or if the directory is gone.
- pub fn load(cache_dir: &Path) -> Self {
- let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
- tracing::info!("Loading bundle root from {persist_path:?}");
- match std::fs::read_to_string(&persist_path) {
- Ok(contents) => {
- let path = PathBuf::from(contents.trim());
- let index = path.join("index.html");
- if index.exists() {
- tracing::info!("Restored bundle root: {path:?}");
- BundleRoot(RwLock::new(Some(path)))
- } else {
- tracing::warn!(
- "Persisted bundle root {path:?} missing index.html at {index:?}"
- );
- BundleRoot(RwLock::new(None))
- }
- }
- Err(e) => {
- tracing::info!("No persisted bundle root: {e}");
- BundleRoot(RwLock::new(None))
- }
- }
- }
-
- /// Persist the bundle root path so it survives app restarts.
- pub fn persist(&self, cache_dir: &Path) -> Result<(), std::io::Error> {
- let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
- let guard = self
- .0
- .read()
- .map_err(|e| std::io::Error::other(e.to_string()))?;
- match guard.as_ref() {
- Some(root) => {
- tracing::info!("Persisting bundle root {root:?} to {persist_path:?}");
- std::fs::write(&persist_path, root.to_string_lossy().as_bytes())
- }
- None => {
- // Remove the file if bundle root is cleared
- match std::fs::remove_file(&persist_path) {
- Ok(()) => Ok(()),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
- Err(e) => Err(e),
- }
- }
- }
- }
-}
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound.rs
index 44e200dfb6..d5f36c03c6 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound.rs
@@ -1,3 +1,6 @@
+/// HTTP client for the bundle update API.
pub mod api_client;
+/// Filesystem operations for bundle extraction and persistence.
pub mod fs;
+/// System information queries (version, arch, target, cache dir).
pub mod system_info;
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs
index 12ab7f8350..8c53e2dd18 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs
@@ -9,20 +9,27 @@ use thiserror::Error;
use tokio::io::AsyncWriteExt;
use url::Url;
+/// HTTP client for checking and downloading bundle updates.
pub struct BundleClient {
+ /// Reusable HTTP client.
client: reqwest::Client,
+ /// Base URL of the update server.
base: Url,
}
+/// Errors returned by [`BundleClient`].
#[derive(Debug, Error)]
pub enum BundleClientErr {
+ /// An HTTP request failed.
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
+ /// The provided URL cannot be used as a base for path segments.
#[error("Url {0} cannot be a base")]
CannotBeABase(Url),
}
impl BundleClient {
+ /// Create a new client pointing at the given base URL.
pub fn new(mut base: Url) -> Self {
base.set_path("");
let client = reqwest::Client::new();
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs
index bba8b19a1f..c08ead8939 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs
@@ -7,6 +7,8 @@ use sha2::Sha256;
use std::path::PathBuf;
use zip::{read::root_dir_common_filter, result::ZipError};
+/// Real filesystem implementation of [`FsRepo`](crate::domain::ports::FsRepo).
+#[derive(Clone)]
pub struct FileSystem;
fn map_zip_err(err: ZipError) -> UnzipError {
@@ -78,4 +80,37 @@ impl FsRepo for FileSystem {
) -> impl Future<Output = Result<(), std::io::Error>> + Send {
tokio::fs::create_dir_all(path)
}
+
+ async fn list_dir_names(&self, dir: &std::path::Path) -> Vec<String> {
+ let mut names = Vec::new();
+ let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
+ return names;
+ };
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ if let Ok(name) = entry.file_name().into_string() {
+ names.push(name);
+ }
+ }
+ names
+ }
+
+ async fn remove_dir_all(&self, dir: &std::path::Path) -> Result<(), std::io::Error> {
+ tokio::fs::remove_dir_all(dir).await
+ }
+
+ async fn read_to_string(&self, path: &std::path::Path) -> Result<String, std::io::Error> {
+ tokio::fs::read_to_string(path).await
+ }
+
+ async fn write(&self, path: &std::path::Path, contents: &[u8]) -> Result<(), std::io::Error> {
+ tokio::fs::write(path, contents).await
+ }
+
+ async fn remove_file(&self, path: &std::path::Path) -> Result<(), std::io::Error> {
+ match tokio::fs::remove_file(path).await {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
+ }
+ }
}
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs
index cf7685923f..d35262f47e 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs
@@ -6,11 +6,13 @@ use crate::domain::{
ports::SystemQuery,
};
+/// Queries the running Tauri app for version, architecture, and OS target.
pub struct SystemInfo<R: Runtime> {
app_handle: tauri::AppHandle<R>,
}
impl<R: Runtime> SystemInfo<R> {
+ /// Create a new system info query bound to the given app handle.
pub fn new(app_handle: tauri::AppHandle<R>) -> Self {
Self { app_handle }
}
@@ -26,7 +28,18 @@ impl<R: Runtime> SystemInfo<R> {
}
}
- fn get_version(&self) -> Version {
+ async fn get_version(&self) -> Version {
+ // If an OTA update has been applied, read the version from semver.txt
+ // in the bundle root so the server can compare build metadata accurately.
+ if let Some(s) = self
+ .app_handle
+ .try_state::<tokio::sync::Mutex<crate::inbound::plugin::PluginService>>()
+ {
+ let service = s.lock().await;
+ if let Some(v) = service.bundle_version().await {
+ return v;
+ }
+ }
self.app_handle.package_info().version.clone()
}
@@ -44,7 +57,7 @@ impl<R: Runtime> SystemInfo<R> {
impl<R: Runtime> SystemQuery for SystemInfo<R> {
async fn get_system_info(&self) -> Result<AppInfo, rootcause::Report> {
Ok(AppInfo {
- current_version: self.get_version(),
+ current_version: self.get_version().await,
arch: self.get_arch(),
target: self.get_target(),
})
diff --git a/js/app/tauri/src-tauri/gen/apple/Sources/app/main.mm b/js/app/tauri/src-tauri/gen/apple/Sources/app/main.mm
index 025a959103..26eb3de617 100644
--- a/js/app/tauri/src-tauri/gen/apple/Sources/app/main.mm
+++ b/js/app/tauri/src-tauri/gen/apple/Sources/app/main.mm
@@ -1,31 +1,6 @@
#include "bindings/bindings.h"
#import <UIKit/UIKit.h>
-extern "C" void on_app_resumed(void);
-
-@interface AppLifecycleObserver : NSObject
-@end
-
-@implementation AppLifecycleObserver
-
-+ (void)load {
- __block BOOL isFirstActivation = YES;
-
- [[NSNotificationCenter defaultCenter]
- addObserverForName:UIApplicationDidBecomeActiveNotification
- object:nil
- queue:[NSOperationQueue mainQueue]
- usingBlock:^(NSNotification * _Nonnull note) {
- if (isFirstActivation) {
- isFirstActivation = NO;
- return;
- }
- on_app_resumed();
- }];
-}
-
-@end
-
int main(int argc, char * argv[]) {
ffi::start_app();
return 0;
diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rs
index 98157a9b4c..72c38e2cf5 100644
--- a/js/app/tauri/src-tauri/src/lib.rs
+++ b/js/app/tauri/src-tauri/src/lib.rs
@@ -1,18 +1,13 @@
use logger::Logger;
-use macro_bundle_updater_plugin::BundleRoot;
+use macro_bundle_updater_plugin::inbound::plugin::PluginService;
use navigation_plugin::MacroNavigationPlugin;
use navigation_plugin::scheme::MacroScheme;
use reqwest::cookie::CookieStore;
use reqwest::header::{COOKIE, ORIGIN};
use rootcause::{Report, report};
use serde::Serialize;
-#[cfg(target_os = "ios")]
-use std::sync::OnceLock;
-use std::sync::RwLock;
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::http::{HeaderMap, HeaderValue};
-use tauri::{AppHandle, Emitter};
-use tauri::{Manager, Runtime};
+use tauri::{AppHandle, Emitter, Manager, Runtime};
mod tauri_protocol;
use tauri_plugin_deep_link::{DeepLinkExt, OpenUrlEvent};
@@ -20,71 +15,10 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use url::Url;
-struct HeartbeatState {
- alive: AtomicBool,
- /// Incremented on each resume event so stale check threads are ignored
- generation: AtomicU64,
-}
-
-#[tauri::command]
-fn heartbeat_response(state: tauri::State<'_, HeartbeatState>) {
- state.alive.store(true, Ordering::SeqCst);
-}
-
/// This module provides debuging utilities and should not be compiled in prodiction builds
#[cfg(debug_assertions)] // do not remove this
mod debug;
-#[cfg(target_os = "ios")]
-static GLOBAL_APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
-
-/// Send a heartbeat ping to the JS layer and check for a response after 1 second.
-/// If no response is received, reload the webview (the content process is likely dead).
-#[cfg(target_os = "ios")]
-fn send_heartbeat(handle: &AppHandle) {
- tracing::info!("app resumed, sending heartbeat ping");
-
- let state = handle.state::<HeartbeatState>();
- let current_gen = state.generation.fetch_add(1, Ordering::SeqCst) + 1;
- state.alive.store(false, Ordering::SeqCst);
-
- let _ = handle.emit("heartbeat_ping", ());
-
- let handle = handle.clone();
- tauri::async_runtime::spawn(async move {
- tokio::time::sleep(std::time::Duration::from_secs(1)).await;
- let state = handle.state::<HeartbeatState>();
-
- if state.generation.load(Ordering::SeqCst) != current_gen {
- tracing::debug!("heartbeat: stale generation {current_gen}, skipping");
- return;
- }
-
- if !state.alive.load(Ordering::SeqCst) {
- tracing::warn!(
- "heartbeat: no response from JS — content process likely dead, reloading webview"
- );
- if let Some(webview) = handle.webview_windows().values().next() {
- let _ = webview.reload();
- }
- } else {
- tracing::info!("heartbeat: JS responded, content process alive");
- }
- });
-}
-
-/// Called from native Objective-C when the iOS app resumes from background.
-/// See `main.mm` for the notification observer.
-#[cfg(target_os = "ios")]
-#[unsafe(no_mangle)]
-extern "C" fn on_app_resumed() {
- let Some(handle) = GLOBAL_APP_HANDLE.get() else {
- tracing::warn!("on_app_resumed: app handle not yet initialized");
- return;
- };
- send_heartbeat(handle);
-}
-
/// domains which the tauri webview can render.
/// This should be as restrictive as possible.
/// If the webview attempts to naviate to other domains,
@@ -222,25 +156,13 @@ pub fn run() {
let h = handler.get_or_init(|| {
// Restore persisted bundle root before the first request is served
let app = ctx.app_handle();
- match app.path().app_cache_dir() {
- Ok(cache_dir) => {
- tracing::info!("Protocol handler init: cache_dir={cache_dir:?}");
- let restored = BundleRoot::load(&cache_dir);
- if let Ok(val) = restored.0.read()
- && let Some(ref path) = *val
- {
- if let Some(br) = app.try_state::<BundleRoot>() {
- tracing::info!("Setting managed BundleRoot to {path:?}");
- if let Ok(mut w) = br.0.write() {
- *w = Some(path.clone());
- }
- } else {
- tracing::warn!("BundleRoot state not managed yet");
- }
- }
- }
- Err(e) => {
- tracing::warn!("Failed to get app_cache_dir: {e}");
+ if let Ok(cache_dir) = app.path().app_cache_dir() {
+ tracing::info!("Protocol handler init: cache_dir={cache_dir:?}");
+ if let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>() {
+ tauri::async_runtime::block_on(async {
+ let mut service = s.lock().await;
+ service.load_bundle_root(&cache_dir).await;
+ });
}
}
tauri_protocol::get(app.clone(), &window_origin)
@@ -248,30 +170,25 @@ pub fn run() {
h(ctx.webview_label(), request, responder);
}
})
- .manage(BundleRoot(RwLock::new(None)))
- .manage(HeartbeatState {
- alive: AtomicBool::new(true),
- generation: AtomicU64::new(0),
- })
.invoke_handler(tauri::generate_handler![
- heartbeat_response,
macro_bundle_updater_plugin::inbound::plugin::grant_bundle_update,
macro_bundle_updater_plugin::inbound::plugin::perform_update,
macro_bundle_updater_plugin::inbound::plugin::check_for_update,
- macro_bundle_updater_plugin::inbound::plugin::get_bundle_update_status
+ macro_bundle_updater_plugin::inbound::plugin::get_bundle_update_status,
+ macro_bundle_updater_plugin::inbound::plugin::clear_bundle
])
.setup(|app| {
// Restore persisted bundle root on startup
if let Ok(cache_dir) = app.path().app_cache_dir() {
- let restored = BundleRoot::load(&cache_dir);
- if let Ok(val) = restored.0.read()
- && let Some(ref path) = *val
- {
- let bundle_root = app.state::<BundleRoot>();
- if let Ok(mut w) = bundle_root.0.write() {
- *w = Some(path.clone());
- tracing::info!("Setup: restored BundleRoot to {path:?}");
- }
+ if let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>() {
+ tauri::async_runtime::block_on(async {
+ let mut service = s.lock().await;
+ service.load_bundle_root(&cache_dir).await;
+ tracing::info!(
+ "Setup: restored bundle root to {:?}",
+ service.bundle_root_path()
+ );
+ });
}
}
@@ -286,11 +203,6 @@ pub fn run() {
app.chain(attach_deep_link_handler);
- #[cfg(target_os = "ios")]
- {
- let _ = GLOBAL_APP_HANDLE.set(app.handle().clone());
- }
-
Ok(())
})
.run(tauri::generate_context!())
diff --git a/js/app/tauri/src-tauri/src/tauri_protocol.rs b/js/app/tauri/src-tauri/src/tauri_protocol.rs
index 429375169c..659df99e78 100644
--- a/js/app/tauri/src-tauri/src/tauri_protocol.rs
+++ b/js/app/tauri/src-tauri/src/tauri_protocol.rs
@@ -11,7 +11,8 @@
use http::{Response as HttpResponse, StatusCode, header::CONTENT_TYPE};
use tauri::{Manager, Runtime, UriSchemeResponder};
-use macro_bundle_updater_plugin::BundleRoot;
+use macro_bundle_updater_plugin::inbound::plugin::PluginService;
+use tokio::sync::Mutex;
type ProtocolHandler = Box<dyn Fn(&str, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;
@@ -58,15 +59,13 @@ pub fn get<R: Runtime>(app_handle: tauri::AppHandle<R>, window_origin: &str) ->
let origin = window_origin.to_string();
Box::new(move |webview_id, request, responder| {
- let bundle_root = app_handle.try_state::<BundleRoot>();
- let has_bundle = bundle_root
+ let service = app_handle.try_state::<Mutex<PluginService>>();
+ let root_dir_owned = service
.as_ref()
- .and_then(|br| br.0.read().ok())
- .as_ref()
- .and_then(|guard| guard.as_ref())
- .is_some();
+ .and_then(|s| s.try_lock().ok())
+ .and_then(|s| s.bundle_root_path().map(|p| p.to_path_buf()));
- if has_bundle {
+ if let Some(ref root_dir) = root_dir_owned {
// Serve from the OTA bundle directory on disk
let raw_path = request
.uri()
@@ -88,10 +87,6 @@ pub fn get<R: Runtime>(app_handle: tauri::AppHandle<R>, window_origin: &str) ->
p => p.strip_prefix('/').unwrap_or(p),
};
- let br = bundle_root.unwrap();
- let guard = br.0.read().unwrap();
- let root_dir = guard.as_ref().unwrap();
-
// Prevent path traversal: canonicalize both paths and verify
// the resolved file stays within the bundle root.
let canonical_root = match root_dir.canonicalize() {
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index 5f694506f7..80e82984b4 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -4,9 +4,7 @@
mod test;
use connection::domain::ports::ConnectionService;
-use entity_access::domain::models::{
- EntityAccessReceipt, EntityType, ViewAccessLevel,
-};
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
diff --git a/rust/cloud-storage/native_app_service/src/domain/service.rs b/rust/cloud-storage/native_app_service/src/domain/service.rs
index 6a582f67b3..ba1fa693f9 100644
--- a/rust/cloud-storage/native_app_service/src/domain/service.rs
+++ b/rust/cloud-storage/native_app_service/src/domain/service.rs
@@ -27,7 +27,7 @@ where
} = req;
let most_recent = self.bundle_fetcher.get_app_semver().await?;
- if most_recent > cur_ver {
+ if needs_update(&most_recent, &cur_ver) {
let checksum = self
.bundle_fetcher
.get_app_bundle_checksum(&most_recent)
@@ -47,3 +47,25 @@ where
req.get_payload(&self.platform_data)
}
}
+
+/// Check whether the client should update to `latest` from `current`.
+///
+/// The `semver` crate's derived `Ord` includes build metadata in the
+/// comparison, but for update purposes we follow the semver 2.0 spec:
+/// compare by precedence (major.minor.patch.pre) only. When precedence
+/// is equal, trigger an update if build metadata differs — each deploy
+/// produces a unique build metadata tag (the short commit SHA).
+pub(crate) fn needs_update(latest: &semver::Version, current: &semver::Version) -> bool {
+ let precedence = latest
+ .major
+ .cmp(&current.major)
+ .then(latest.minor.cmp(&current.minor))
+ .then(latest.patch.cmp(&current.patch))
+ .then(latest.pre.cmp(&current.pre));
+
+ match precedence {
+ std::cmp::Ordering::Greater => true,
+ std::cmp::Ordering::Less => false,
+ std::cmp::Ordering::Equal => latest.build != current.build,
+ }
+}
diff --git a/rust/cloud-storage/native_app_service/src/tests.rs b/rust/cloud-storage/native_app_service/src/tests.rs
index 06cb173f69..8c7da92583 100644
--- a/rust/cloud-storage/native_app_service/src/tests.rs
+++ b/rust/cloud-storage/native_app_service/src/tests.rs
@@ -5,7 +5,7 @@ use crate::{
AllTargets, Arch, BundleUpdate, DesktopTarget, MobileTarget, PlatformData, UpdateErr,
},
ports::{GetJsBundleSemver, NativeAppService},
- service::NativeAppServiceImpl,
+ service::{self, NativeAppServiceImpl},
},
outbound::DefaultBundleFetcher,
};
@@ -166,3 +166,116 @@ async fn it_should_upgrade_desktop() {
);
}
}
+
+#[test]
+fn needs_update_higher_version() {
+ let latest: Version = "2.0.0".parse().unwrap();
+ let current: Version = "1.0.0".parse().unwrap();
+ assert!(service::needs_update(&latest, &current));
+}
+
+#[test]
+fn needs_update_same_version_no_metadata() {
+ let latest: Version = "1.0.0".parse().unwrap();
+ let current: Version = "1.0.0".parse().unwrap();
+ assert!(!service::needs_update(&latest, &current));
+}
+
+#[test]
+fn needs_update_same_version_different_build_metadata() {
+ let latest: Version = "1.0.0+abc1234".parse().unwrap();
+ let current: Version = "1.0.0+def5678".parse().unwrap();
+ assert!(service::needs_update(&latest, &current));
+}
+
+#[test]
+fn needs_update_same_version_same_build_metadata() {
+ let latest: Version = "1.0.0+abc1234".parse().unwrap();
+ let current: Version = "1.0.0+abc1234".parse().unwrap();
+ assert!(!service::needs_update(&latest, &current));
+}
+
+#[test]
+fn needs_update_latest_has_metadata_current_does_not() {
+ let latest: Version = "1.0.0+abc1234".parse().unwrap();
+ let current: Version = "1.0.0".parse().unwrap();
+ assert!(service::needs_update(&latest, &current));
+}
+
+#[test]
+fn needs_update_build_metadata_order_does_not_matter() {
+ let a: Version = "1.0.0+aaaa".parse().unwrap();
+ let z: Version = "1.0.0+zzzz".parse().unwrap();
+ assert!(service::needs_update(&a, &z));
+ assert!(service::needs_update(&z, &a));
+}
+
+#[test]
+fn needs_update_should_not_downgrade() {
+ let latest: Version = "1.0.0+abc1234".parse().unwrap();
+ let current: Version = "2.0.0".parse().unwrap();
+ assert!(!service::needs_update(&latest, &current));
+}
+
+struct MockBundleFetcherWithBuild;
+
+impl GetJsBundleSemver for MockBundleFetcherWithBuild {
+ async fn get_app_semver(&self) -> Result<semver::Version, UpdateErr> {
+ Ok("1.1.1+abc1234".parse().unwrap())
+ }
+
+ fn get_app_bundle_path(&self) -> Url {
+ "https://example.com".parse().unwrap()
+ }
+
+ async fn get_app_bundle_checksum(
+ &self,
+ _version: &semver::Version,
+ ) -> Result<String, UpdateErr> {
+ Ok("abc123".to_string())
+ }
+}
+
+#[tokio::test]
+async fn it_should_upgrade_when_build_metadata_differs() {
+ let semver: Version = "1.1.1+old5678".parse().unwrap();
+
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcherWithBuild,
+ platform_data: mock_platform_data(),
+ };
+
+ assert_matches!(
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target: AllTargets::Desktop(DesktopTarget::Darwin),
+ arch: Arch::Aarch64,
+ semver,
+ })
+ .await,
+ Ok(Some(BundleUpdate { version, .. })) => {
+ assert_eq!(version.to_string(), "1.1.1+abc1234");
+ }
+ );
+}
+
+#[tokio::test]
+async fn it_should_not_upgrade_when_build_metadata_matches() {
+ let semver: Version = "1.1.1+abc1234".parse().unwrap();
+
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcherWithBuild,
+ platform_data: mock_platform_data(),
+ };
+
+ assert_matches!(
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target: AllTargets::Desktop(DesktopTarget::Darwin),
+ arch: Arch::Aarch64,
+ semver,
+ })
+ .await,
+ Ok(None)
+ );
+}