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
Seanaye/refactor/bundle updater (#4976)
Sean Ayee9023fe9bfbb
diff --git a/apps/web/.helix/languages.toml b/apps/web/.helix/languages.tomlnew file mode 100644index 0000000000..ed80fe0112--- /dev/null+++ b/apps/web/.helix/languages.toml@@ -0,0 +1,11 @@+# Project-local Helix configuration when Helix is launched from apps/web.+# Scope rust-analyzer to the nested Tauri workspace instead of letting it walk+# up to the repository-wide backend workspace.++[language-server.rust-analyzer.config]+linkedProjects = ["Cargo.toml"]++# Consider iOS-gated code active without changing the compilation/link target+# on Linux.+[language-server.rust-analyzer.config.cargo]+cfgs = ["target_os=ios"]diff --git a/apps/web/index.html b/apps/web/index.htmlindex f0876bd96a..d72208fda4 100644--- a/apps/web/index.html+++ b/apps/web/index.html@@ -9,6 +9,7 @@<meta name="mobile-web-app-capable" content="yes" /><meta name="theme-color" content="#FFFFFF" /><meta name="description" content="Macro AI Workspace" />+ <meta name="macro-bundle-build" content="__MACRO_BUNDLE_BUILD__" /><linkrel="shortcut icon"href="%ASSETS_PATH%/macro-favicon.svg"diff --git a/apps/web/scripts/write-bundle-manifest.mjs b/apps/web/scripts/write-bundle-manifest.mjsindex 8ed35d19ba..13f244fc63 100644--- a/apps/web/scripts/write-bundle-manifest.mjs+++ b/apps/web/scripts/write-bundle-manifest.mjs@@ -38,3 +38,14 @@ const manifest = {const outPath = join(packageDir, 'dist', 'bundle-manifest.json');mkdirSync(dirname(outPath), { recursive: true });writeFileSync(outPath, `${JSON.stringify(manifest, null, 2)}\n`);++const indexPath = join(packageDir, 'dist', 'index.html');+const bundleBuildPlaceholder = '__MACRO_BUNDLE_BUILD__';+const indexHtml = readFileSync(indexPath, 'utf8');+if (!indexHtml.includes(bundleBuildPlaceholder)) {+ throw new Error(`${indexPath} is missing ${bundleBuildPlaceholder}`);+}+writeFileSync(+ indexPath,+ indexHtml.replaceAll(bundleBuildPlaceholder, String(manifest.bundleBuild))+);diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsxindex 24f31a6d1d..58dd13e775 100644--- a/apps/web/src/lib/tauri/TauriProvider.tsx+++ b/apps/web/src/lib/tauri/TauriProvider.tsx@@ -48,6 +48,18 @@ interface TauriContextValue {const TauriContext = createContext<TauriContextValue | undefined>(undefined);+const LOADED_BUNDLE_BUILD = (() => {+ if (typeof document === 'undefined') return undefined;+ const value = document+ .querySelector<HTMLMetaElement>('meta[name="macro-bundle-build"]')+ ?.getAttribute('content');+ if (value === undefined || value === null || !/^\d+$/.test(value)) {+ return undefined;+ }+ const bundleBuild = Number(value);+ return Number.isSafeInteger(bundleBuild) ? bundleBuild : undefined;+})();+function shouldShowNativeAppUpdateRequiredDialog(status: BundleUpdateStatus) {return (status.status === 'ClearRequired' ||@@ -101,9 +113,13 @@ function TauriProvider(props: { children: JSX.Element }) {setBundleUpdateStatus(ev.payload);});- invoke<boolean>('ack_bundle_update_reload').catch((e) =>- console.error('[bundle-update] ack_bundle_update_reload failed', e)- );+ if (LOADED_BUNDLE_BUILD !== undefined) {+ invoke<boolean>('ack_bundle_update_reload', {+ loadedBundleBuild: LOADED_BUNDLE_BUILD,+ }).catch((e) =>+ console.error('[bundle-update] ack_bundle_update_reload failed', e)+ );+ }// Fetch current status since events emitted before the listener registered are missedinvoke<BundleUpdateStatus>('get_bundle_update_status').then((status) => {setBundleUpdateStatus(status);diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain.rsindex fab9215a53..2e1a10ca7f 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain.rs@@ -1,3 +1,7 @@+/// Domain service for resolving frontend bundle assets.+pub mod asset_service;+/// Shared routing state for active frontend bundle generations.+pub mod bundle_routes;/// Data types and error definitions for bundle updates.pub mod models;/// Trait definitions (ports) for update, filesystem, and system queries.diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rsnew file mode 100644index 0000000000..ee4a65f39b--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs@@ -0,0 +1,157 @@+use std::path::{Component, Path, PathBuf};++use thiserror::Error;++use crate::domain::{+ bundle_routes::{BundleRoutes, BundleSource},+ ports::BundleAssetRepo,+};++/// A validated path relative to a frontend bundle root.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct BundleAssetPath(PathBuf);++impl BundleAssetPath {+ /// Validate and normalize a relative bundle asset path.+ ///+ /// Empty paths resolve to the application entrypoint. Absolute paths and+ /// parent-directory components are rejected.+ pub fn new(path: impl AsRef<Path>) -> Result<Self, InvalidBundleAssetPath> {+ let mut normalized = PathBuf::new();+ for component in path.as_ref().components() {+ match component {+ Component::Normal(value) => normalized.push(value),+ Component::CurDir => {}+ Component::ParentDir | Component::RootDir | Component::Prefix(_) => {+ return Err(InvalidBundleAssetPath);+ }+ }+ }+ if normalized.as_os_str().is_empty() {+ normalized.push("index.html");+ }+ Ok(Self(normalized))+ }++ /// Return the normalized relative path.+ pub fn as_path(&self) -> &Path {+ &self.0+ }++ fn entrypoint() -> Self {+ Self(PathBuf::from("index.html"))+ }++ fn has_extension(&self) -> bool {+ self.0.extension().is_some()+ }+}++/// Error returned when an asset path is not safe to resolve.+#[derive(Debug, Clone, Copy, Error, PartialEq, Eq)]+#[error("bundle asset path must remain relative to its bundle root")]+pub struct InvalidBundleAssetPath;++/// Error returned by the bundle asset repository.+#[derive(Debug, Error)]+pub enum BundleAssetReadError {+ /// The resolved path escaped the configured bundle root.+ #[error("resolved asset path escaped its bundle root")]+ OutsideBundleRoot,+ /// A filesystem operation failed.+ #[error(transparent)]+ Io(#[from] std::io::Error),+}++/// Result of resolving one custom-protocol asset request.+#[derive(Debug, PartialEq, Eq)]+pub enum BundleAssetResolution {+ /// Asset bytes loaded from an OTA bundle.+ Ota {+ /// Loaded asset bytes.+ bytes: Vec<u8>,+ /// Actual file path used for MIME type inference.+ content_path: BundleAssetPath,+ },+ /// Delegate this request to Tauri's embedded asset handler.+ Embedded,+ /// No eligible bundle generation contained the requested asset.+ NotFound,+}++/// Domain service that selects the correct bundle generation for asset reads.+#[derive(Clone)]+pub struct BundleAssetResolver<Assets> {+ routes: BundleRoutes,+ assets: Assets,+}++impl<Assets> BundleAssetResolver<Assets>+where+ Assets: BundleAssetRepo,+{+ /// Create an asset resolver backed by shared bundle routes and an asset repository.+ pub fn new(routes: BundleRoutes, assets: Assets) -> Self {+ Self { routes, assets }+ }++ /// Resolve an asset against the active bundle and any transition fallback.+ pub async fn resolve(+ &self,+ path: &BundleAssetPath,+ ) -> Result<BundleAssetResolution, BundleAssetReadError> {+ // Keep this lease through every OTA read. Removing a transition fallback+ // acquires the write side before deleting its directory.+ let routes = self.routes.read().await;+ match &routes.active {+ BundleSource::Embedded { .. } => {+ if path.has_extension()+ && let Some(BundleSource::Ota { root, .. }) = &routes.fallback+ && let Some(bytes) = self.assets.read_asset(root, path).await?+ {+ return Ok(BundleAssetResolution::Ota {+ bytes,+ content_path: path.clone(),+ });+ }+ Ok(BundleAssetResolution::Embedded)+ }+ BundleSource::Ota { root, .. } => {+ if let Some(bytes) = self.assets.read_asset(root, path).await? {+ return Ok(BundleAssetResolution::Ota {+ bytes,+ content_path: path.clone(),+ });+ }++ if !path.has_extension() {+ let entrypoint = BundleAssetPath::entrypoint();+ return Ok(match self.assets.read_asset(root, &entrypoint).await? {+ Some(bytes) => BundleAssetResolution::Ota {+ bytes,+ content_path: entrypoint,+ },+ None => BundleAssetResolution::NotFound,+ });+ }++ match &routes.fallback {+ Some(BundleSource::Ota { root, .. }) => {+ Ok(match self.assets.read_asset(root, path).await? {+ Some(bytes) => BundleAssetResolution::Ota {+ bytes,+ content_path: path.clone(),+ },+ None => BundleAssetResolution::NotFound,+ })+ }+ Some(BundleSource::Embedded { .. }) => Ok(BundleAssetResolution::Embedded),+ None => Ok(BundleAssetResolution::NotFound),+ }+ }+ }+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service/test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service/test.rsnew file mode 100644index 0000000000..a99cd904bc--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service/test.rs@@ -0,0 +1,160 @@+use std::{collections::HashMap, sync::Arc};++use tokio::sync::Mutex;++use super::*;++#[derive(Clone, Default)]+struct FakeAssets {+ files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>,+}++impl FakeAssets {+ async fn insert(&self, root: &str, path: &str, contents: &str) {+ self.files+ .lock()+ .await+ .insert(Path::new(root).join(path), contents.as_bytes().to_vec());+ }+}++impl BundleAssetRepo for FakeAssets {+ async fn read_asset(+ &self,+ root: &Path,+ path: &BundleAssetPath,+ ) -> Result<Option<Vec<u8>>, BundleAssetReadError> {+ Ok(self+ .files+ .lock()+ .await+ .get(&root.join(path.as_path()))+ .cloned())+ }+}++fn path(path: &str) -> BundleAssetPath {+ BundleAssetPath::new(path).unwrap()+}++#[test]+fn rejects_paths_that_escape_the_bundle_root() {+ assert_eq!(+ BundleAssetPath::new("assets/../../secret"),+ Err(InvalidBundleAssetPath)+ );+ assert_eq!(+ BundleAssetPath::new("/absolute/path"),+ Err(InvalidBundleAssetPath)+ );+}++#[tokio::test]+async fn delegates_to_embedded_assets_when_no_ota_is_active() {+ let resolver = BundleAssetResolver::new(BundleRoutes::new(1), FakeAssets::default());++ let resolution = resolver.resolve(&path("app.js")).await.unwrap();++ assert_eq!(resolution, BundleAssetResolution::Embedded);+}++#[tokio::test]+async fn reads_assets_from_the_active_ota_bundle() {+ let routes = BundleRoutes::new(1);+ routes+ .restore(BundleSource::ota(2, PathBuf::from("/ota/2")))+ .await;+ let assets = FakeAssets::default();+ assets.insert("/ota/2", "app.js", "current").await;+ let resolver = BundleAssetResolver::new(routes, assets);++ let resolution = resolver.resolve(&path("app.js")).await.unwrap();++ assert_eq!(+ resolution,+ BundleAssetResolution::Ota {+ bytes: b"current".to_vec(),+ content_path: path("app.js"),+ }+ );+}++#[tokio::test]+async fn extensionless_routes_use_the_active_ota_entrypoint() {+ let routes = BundleRoutes::new(1);+ routes+ .restore(BundleSource::ota(2, PathBuf::from("/ota/2")))+ .await;+ let assets = FakeAssets::default();+ assets.insert("/ota/2", "index.html", "entrypoint").await;+ let resolver = BundleAssetResolver::new(routes, assets);++ let resolution = resolver.resolve(&path("login")).await.unwrap();++ assert_eq!(+ resolution,+ BundleAssetResolution::Ota {+ bytes: b"entrypoint".to_vec(),+ content_path: path("index.html"),+ }+ );+}++#[tokio::test]+async fn missing_extensionful_assets_can_use_the_previous_ota_generation() {+ let routes = BundleRoutes::new(1);+ routes+ .restore(BundleSource::ota(2, PathBuf::from("/ota/2")))+ .await;+ routes+ .transition_to(BundleSource::ota(3, PathBuf::from("/ota/3")))+ .await;+ let assets = FakeAssets::default();+ assets.insert("/ota/2", "old-hash.js", "previous").await;+ let resolver = BundleAssetResolver::new(routes, assets);++ let resolution = resolver.resolve(&path("old-hash.js")).await.unwrap();++ assert_eq!(+ resolution,+ BundleAssetResolution::Ota {+ bytes: b"previous".to_vec(),+ content_path: path("old-hash.js"),+ }+ );+}++#[tokio::test]+async fn embedded_to_ota_transition_can_fall_back_to_embedded_assets() {+ let routes = BundleRoutes::new(1);+ routes+ .transition_to(BundleSource::ota(2, PathBuf::from("/ota/2")))+ .await;+ let resolver = BundleAssetResolver::new(routes, FakeAssets::default());++ let resolution = resolver.resolve(&path("embedded-hash.js")).await.unwrap();++ assert_eq!(resolution, BundleAssetResolution::Embedded);+}++#[tokio::test]+async fn ota_to_embedded_transition_checks_the_previous_ota_first() {+ let routes = BundleRoutes::new(1);+ routes+ .restore(BundleSource::ota(2, PathBuf::from("/ota/2")))+ .await;+ routes.transition_to(BundleSource::embedded(1)).await;+ let assets = FakeAssets::default();+ assets.insert("/ota/2", "ota-hash.js", "previous").await;+ let resolver = BundleAssetResolver::new(routes, assets);++ let resolution = resolver.resolve(&path("ota-hash.js")).await.unwrap();++ assert_eq!(+ resolution,+ BundleAssetResolution::Ota {+ bytes: b"previous".to_vec(),+ content_path: path("ota-hash.js"),+ }+ );+}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes.rsnew file mode 100644index 0000000000..784e2b174a--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes.rs@@ -0,0 +1,143 @@+use std::{path::PathBuf, sync::Arc};+use tokio::sync::{OwnedRwLockReadGuard, RwLock};++/// Identifies where a frontend bundle is served from.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BundleSourceKind {+ /// Assets compiled into the native application.+ Embedded,+ /// Assets loaded from an OTA bundle directory.+ Ota,+}++/// Identifies one frontend bundle generation.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BundleIdentity {+ /// Monotonically increasing bundle build number.+ pub bundle_build: u64,+ /// Storage source for this bundle generation.+ pub source: BundleSourceKind,+}++/// A source from which frontend assets can be served.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum BundleSource {+ /// Assets compiled into the native application.+ Embedded {+ /// Build number compiled into the native application.+ bundle_build: u64,+ },+ /// Assets stored in an applied OTA bundle directory.+ Ota {+ /// Build number read from the OTA bundle manifest.+ bundle_build: u64,+ /// Root directory containing the OTA bundle assets.+ root: PathBuf,+ },+}++impl BundleSource {+ /// Construct an embedded bundle source.+ pub fn embedded(bundle_build: u64) -> Self {+ Self::Embedded { bundle_build }+ }++ /// Construct an OTA bundle source.+ pub fn ota(bundle_build: u64, root: PathBuf) -> Self {+ Self::Ota { bundle_build, root }+ }++ /// Return this source's identity.+ pub fn identity(&self) -> BundleIdentity {+ match self {+ Self::Embedded { bundle_build } => BundleIdentity {+ bundle_build: *bundle_build,+ source: BundleSourceKind::Embedded,+ },+ Self::Ota { bundle_build, .. } => BundleIdentity {+ bundle_build: *bundle_build,+ source: BundleSourceKind::Ota,+ },+ }+ }++ /// Return the OTA root directory, if this is an OTA source.+ pub fn ota_root(&self) -> Option<&std::path::Path> {+ match self {+ Self::Embedded { .. } => None,+ Self::Ota { root, .. } => Some(root),+ }+ }+}++/// Atomically published routing state for frontend bundle assets.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct BundleRouteSnapshot {+ /// Source used for the currently active frontend document.+ pub active: BundleSource,+ /// Previous source retained while a document reload is in progress.+ pub fallback: Option<BundleSource>,+}++/// Shared domain state used to coordinate updater transitions and asset reads.+///+/// Asset readers hold a read lease until their file read completes. Route+/// transitions use a short-lived write lease, so they wait for existing reads+/// without sharing the updater service's coarse-grained mutex.+#[derive(Clone)]+pub struct BundleRoutes {+ state: Arc<RwLock<BundleRouteSnapshot>>,+}++impl BundleRoutes {+ /// Create routing state that initially serves the embedded bundle.+ pub fn new(embedded_bundle_build: u64) -> Self {+ Self {+ state: Arc::new(RwLock::new(BundleRouteSnapshot {+ active: BundleSource::embedded(embedded_bundle_build),+ fallback: None,+ })),+ }+ }++ /// Acquire a read lease for resolving an asset request.+ pub async fn read(&self) -> OwnedRwLockReadGuard<BundleRouteSnapshot> {+ self.state.clone().read_owned().await+ }++ /// Return the identity of the active bundle generation.+ pub async fn active_identity(&self) -> BundleIdentity {+ self.state.read().await.active.identity()+ }++ /// Replace the active source without retaining a transition fallback.+ ///+ /// This is used while restoring startup state before a webview is serving+ /// requests.+ pub async fn restore(&self, source: BundleSource) {+ let mut state = self.state.write().await;+ state.active = source;+ state.fallback = None;+ }++ /// Begin a live transition to a new source, retaining the prior source.+ pub async fn transition_to(&self, source: BundleSource) {+ let mut state = self.state.write().await;+ if state.active == source {+ return;+ }+ state.fallback = Some(state.active.clone());+ state.active = source;+ }++ /// Finish a live transition and return the retired fallback source.+ ///+ /// Acquiring the write lease waits for readers of the prior snapshot to+ /// finish, so a returned OTA directory can be safely cleaned up.+ pub async fn finish_transition(&self) -> Option<BundleSource> {+ self.state.write().await.fallback.take()+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes/test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes/test.rsnew file mode 100644index 0000000000..3a262feb8a--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/bundle_routes/test.rs@@ -0,0 +1,61 @@+use super::*;++#[tokio::test]+async fn starts_with_the_embedded_bundle() {+ let routes = BundleRoutes::new(42);++ let state = routes.read().await;++ assert_eq!(state.active, BundleSource::embedded(42));+ assert_eq!(state.fallback, None);+}++#[tokio::test]+async fn live_transition_retains_the_previous_source() {+ let routes = BundleRoutes::new(42);+ let ota = BundleSource::ota(43, PathBuf::from("/cache/43"));++ routes.transition_to(ota.clone()).await;+ let state = routes.read().await;++ assert_eq!(state.active, ota);+ assert_eq!(state.fallback, Some(BundleSource::embedded(42)));+}++#[tokio::test]+async fn startup_restore_does_not_retain_a_fallback() {+ let routes = BundleRoutes::new(42);+ routes+ .transition_to(BundleSource::ota(43, PathBuf::from("/cache/43")))+ .await;++ routes+ .restore(BundleSource::ota(44, PathBuf::from("/cache/44")))+ .await;+ let state = routes.read().await;++ assert_eq!(+ state.active,+ BundleSource::ota(44, PathBuf::from("/cache/44"))+ );+ assert_eq!(state.fallback, None);+}++#[tokio::test]+async fn finishing_transition_waits_for_existing_readers() {+ let routes = BundleRoutes::new(42);+ routes+ .transition_to(BundleSource::ota(43, PathBuf::from("/cache/43")))+ .await;+ let read_lease = routes.read().await;++ let task = tokio::spawn({+ let routes = routes.clone();+ async move { routes.finish_transition().await }+ });+ tokio::task::yield_now().await;++ assert!(!task.is_finished());+ drop(read_lease);+ assert_eq!(task.await.unwrap(), Some(BundleSource::embedded(42)));+}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rsindex 3227aae69e..3031d1a02f 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs@@ -76,11 +76,6 @@ impl BundleRoot {self.0.as_deref()}- /// Clear the bundle root, reverting to the built-in assets.- pub(crate) fn clear(&mut self) {- self.0 = None;- }-/// Read the bundle manifest inside the bundle root.pub(crate) async fn manifest(&self, fs: &impl FsRepo) -> Option<BundleManifest> {let manifest_path = self.0.as_ref()?.join("bundle-manifest.json");@@ -123,6 +118,17 @@ impl BundleManifest {/// the bounded size of mpsc channelsconst MPSC_CHAN_SIZE: usize = 10;+/// Native application metadata reported by the host platform.+#[derive(Debug, Clone)]+pub struct NativeAppInfo {+ /// The native app build number.+ pub native_build: u64,+ /// CPU architecture.+ pub arch: Arch,+ /// Operating system target.+ pub target: Target,+}+/// Application metadata sent to the update server.#[derive(Debug, Clone)]pub struct AppInfo {@@ -468,6 +474,8 @@ pub struct UnzipStatus {/// The update has been fully downloaded and extracted.#[derive(Debug, Clone)]pub struct CompletedStatus {+ /// Build number from the validated bundle manifest.+ pub bundle_build: u64,/// Path to the extracted `index.html` entrypoint.pub entrypoint: PathBuf,}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/ports.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/ports.rsindex b399914d8c..09e978b687 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/ports.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/ports.rs@@ -1,11 +1,32 @@use rootcause::Report;-use crate::domain::models::{- AppInfo, BundleAction, DownloadBundleError, DownloadBundleRequest, UnzipError, UnzipRequest,- UpdateError, UpdateStatus,+use crate::domain::{+ asset_service::{BundleAssetPath, BundleAssetReadError},+ models::{+ AppInfo, BundleAction, DownloadBundleError, DownloadBundleRequest, NativeAppInfo,+ UnzipError, UnzipRequest, UpdateError, UpdateStatus,+ },};use std::path::{Path, PathBuf};+/// Port for spawning detached domain background tasks.+pub trait TaskSpawner: Send + Sync + 'static {+ /// Spawn a task onto the host application's asynchronous runtime.+ fn spawn(task: impl Future<Output = ()> + Send + 'static);+}++/// Port for reading binary assets from an OTA bundle directory.+pub trait BundleAssetRepo: Clone + Send + Sync + 'static {+ /// Read a validated relative asset path from the supplied bundle root.+ ///+ /// Returns `Ok(None)` when the asset does not exist.+ fn read_asset(+ &self,+ root: &Path,+ path: &BundleAssetPath,+ ) -> impl Future<Output = Result<Option<Vec<u8>>, BundleAssetReadError>> + Send;+}+/// Port for communicating with the update server.pub trait UpdateRepo: Send + Sync + 'static {/// Check whether a bundle action is available.@@ -66,10 +87,12 @@ pub trait FsRepo: Clone + Send + Sync + 'static {fn remove_file(&self, path: &Path) -> impl Future<Output = Result<(), std::io::Error>> + Send;}-/// Port for querying system metadata (version, arch, cache dirs).+/// Port for querying native system metadata and cache directories.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 native build, architecture, and OS target.+ fn get_native_app_info(+ &self,+ ) -> impl Future<Output = Result<NativeAppInfo, rootcause::Report>> + Send;/// Return the current network type, such as `wifi`, `ethernet`, or `cellular`.fn get_network_type(&self,diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rsindex abf0638395..6b0004a9ea 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs@@ -1,13 +1,15 @@use crate::domain::{+ bundle_routes::{BundleRoutes, BundleSource, BundleSourceKind},models::{- BundleAction, BundleManifest, BundleRoot, ClearRequiredStatus, CompletedStatus,+ AppInfo, BundleAction, BundleManifest, BundleRoot, ClearRequiredStatus, CompletedStatus,NativeUpdateRequiredStatus, ProgressPercentage, UnzipRequest, UnzipStatus,UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateGranted, UpdateStatus,},- ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},+ ports::{AutoUpdateService, FsRepo, SystemQuery, TaskSpawner, UpdateRepo},};use rootcause::{Report, prelude::ResultExt, report};use std::{+ marker::PhantomData,path::{Path, PathBuf},time::{Duration, Instant},};@@ -20,8 +22,10 @@ pub struct Service<Fs: FsRepo> {handle: WorkerHandle,fs_repo: Fs,embedded_bundle_build: u64,+ native_build: u64,bundle_root: BundleRoot,- reload_pending: bool,+ bundle_routes: BundleRoutes,+ pending_reload_bundle_build: Option<u64>,reload_dispatched_at: Option<Instant>,}@@ -46,10 +50,12 @@ type StartTx = tokio::sync::mpsc::Sender<WorkerCommand>;/// Worker receives on this to know when to run the checker loop.type StartRx = tokio::sync::mpsc::Receiver<WorkerCommand>;-struct Worker<U, Fs, Q> {+struct Worker<U, Fs, Q, S> {update_repo: U,fs_repo: Fs,system_query: Q,+ bundle_routes: BundleRoutes,+ _task_spawner: PhantomData<S>,status_tx: tokio::sync::watch::Sender<Result<UpdateStatus, Report<UpdateError>>>,start_rx: StartRx,}@@ -64,8 +70,13 @@ struct WorkerHandle {const ENTRYPOINT_NAME: &str = "index.html";const PENDING_BUNDLE_ROOT_FILE: &str = "pending_bundle_root";-impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {- fn new_handle(update_repo: U, fs_repo: Fs, system_query: Q) -> WorkerHandle {+impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery, S: TaskSpawner> Worker<U, Fs, Q, S> {+ fn new_handle(+ update_repo: U,+ fs_repo: Fs,+ system_query: Q,+ bundle_routes: BundleRoutes,+ ) -> WorkerHandle {let (status_tx, status_rx) = tokio::sync::watch::channel(Ok(UpdateStatus::Idle));let (start_tx, start_rx) = tokio::sync::mpsc::channel(1);@@ -73,6 +84,8 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {update_repo,fs_repo,system_query,+ bundle_routes,+ _task_spawner: PhantomData::<S>,status_tx: status_tx.clone(),start_rx,}@@ -85,19 +98,20 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {}}- fn run_background(mut self) {- tauri::async_runtime::spawn(async move {+ fn run_background(self) {+ S::spawn(async move {+ let mut worker = self;// Run the checker loop once on startup, then again each time we// receive a restart signal from the main thread.- while let Some(command) = self.start_rx.recv().await {+ while let Some(command) = worker.start_rx.recv().await {if matches!(command, WorkerCommand::Restart) {// Reset status to Idle for the new run.- if self.status_tx.send(Ok(UpdateStatus::Idle)).is_err() {+ if worker.status_tx.send(Ok(UpdateStatus::Idle)).is_err() {break;}}- self.run_check_loop().await;+ worker.run_check_loop().await;}});}@@ -149,11 +163,17 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {) -> Result<UpdateStatus, Report<UpdateError>> {match status {UpdateStatus::Idle => {- let app_info = self+ let native_app_info = self.system_query- .get_system_info()+ .get_native_app_info().await.context(UpdateError::Other)?;+ let app_info = AppInfo {+ current_bundle_build: self.bundle_routes.active_identity().await.bundle_build,+ native_build: native_app_info.native_build,+ arch: native_app_info.arch,+ target: native_app_info.target,+ };Ok(UpdateStatus::CheckingForDownload(app_info))}@@ -177,7 +197,10 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {).await{- return Ok(UpdateStatus::Completed(CompletedStatus { entrypoint }));+ return Ok(UpdateStatus::Completed(CompletedStatus {+ bundle_build: update.bundle_build,+ entrypoint,+ }));}Ok(UpdateStatus::UpdateFound(UpdateFoundStatus {bundle: update,@@ -188,14 +211,12 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {reason: clear.reason,}))}- Some(BundleAction::NativeUpdateRequired(required)) => {- Ok(UpdateStatus::NativeUpdateRequired(- NativeUpdateRequiredStatus {- bundle_build: required.bundle_build,- min_native_build: required.min_native_build,- },- ))- }+ Some(BundleAction::NativeUpdateRequired(required)) => Ok(+ UpdateStatus::NativeUpdateRequired(NativeUpdateRequiredStatus {+ bundle_build: required.bundle_build,+ min_native_build: required.min_native_build,+ }),+ ),None => Ok(UpdateStatus::NoUpdateNeeded),}}@@ -248,7 +269,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {let (req, rx) = status.update.into_download_request(&download_filename);let status_tx = self.status_tx.clone();- tokio::task::spawn(glue_channels(rx, status_tx, |cur, progress| match cur {+ S::spawn(glue_channels(rx, status_tx, |cur, progress| match cur {UpdateStatus::DownloadingBundle(download) => {download.progress = progress;true@@ -284,7 +305,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {let (req, rx) = UnzipRequest::new(unzip_status.zip_filename, archive_target);let status_tx = self.status_tx.clone();- tokio::task::spawn(glue_channels(rx, status_tx, |cur, progress| match cur {+ S::spawn(glue_channels(rx, status_tx, |cur, progress| match cur {UpdateStatus::UnzippingBundle(zip) => {zip.progress = progress;true@@ -299,7 +320,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {unzip_status.expected_bundle_build,unzip_status.expected_min_native_build,self.system_query- .get_system_info()+ .get_native_app_info().await.context(UpdateError::Other)?.native_build,@@ -327,7 +348,10 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {}let mut entrypoint = bundle_dir;entrypoint.push(ENTRYPOINT_NAME);- Ok(UpdateStatus::Completed(CompletedStatus { entrypoint }))+ Ok(UpdateStatus::Completed(CompletedStatus {+ bundle_build: unzip_status.expected_bundle_build,+ entrypoint,+ }))}UpdateStatus::Completed(x) => Ok(UpdateStatus::Completed(x)),}@@ -487,19 +511,28 @@ async fn glue_channels<F>(impl<Fs: FsRepo> Service<Fs> {/// Create a new service, spawning the background update worker.- pub fn new<U: UpdateRepo, Q: SystemQuery>(+ pub fn new<U: UpdateRepo, Q: SystemQuery, S: TaskSpawner>(update_repo: U,fs_repo: Fs,system_query: Q,embedded_bundle_build: u64,+ native_build: u64,+ bundle_routes: BundleRoutes,) -> Self {- let handle = Worker::new_handle(update_repo, fs_repo.clone(), system_query);+ let handle = Worker::<U, Fs, Q, S>::new_handle(+ update_repo,+ fs_repo.clone(),+ system_query,+ bundle_routes.clone(),+ );Service {handle,fs_repo,embedded_bundle_build,+ native_build,bundle_root: BundleRoot::new(),- reload_pending: false,+ bundle_routes,+ pending_reload_bundle_build: None,reload_dispatched_at: None,}}@@ -513,13 +546,22 @@ impl<Fs: FsRepo> Service<Fs> {if !self.current_bundle_is_usable(native_build).await {tracing::warn!("Clearing unusable persisted bundle root");let _ = self.clear_bundle_root(cache_dir).await;+ self.cleanup_old_bundles(cache_dir, None).await;}- if self.bundle_root.path().is_some() {+ if let Some(path) = self.bundle_root.path()+ && let Some(manifest) = self.bundle_root.manifest(&self.fs_repo).await+ {+ self.bundle_routes+ .restore(BundleSource::ota(manifest.bundle_build, path.to_path_buf()))+ .await;if let Err(e) = self.clear_pending_bundle(cache_dir).await {tracing::warn!(error=?e, "Failed to clear stale pending bundle marker");}return false;}+ self.bundle_routes+ .restore(BundleSource::embedded(self.embedded_bundle_build))+ .await;self.restore_pending_completed_update(cache_dir, native_build).await@@ -530,6 +572,11 @@ impl<Fs: FsRepo> Service<Fs> {self.embedded_bundle_build}+ /// Native build of the running application.+ pub fn native_build(&self) -> u64 {+ self.native_build+ }+/// 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()@@ -541,7 +588,7 @@ impl<Fs: FsRepo> Service<Fs> {/// The worker remains in `Completed` until the reloaded webview acknowledges/// that it mounted with the new bundle root.pub async fn apply_update(&mut self, cache_dir: &Path) -> Result<ApplyUpdateResult, Report> {- if self.reload_pending {+ if self.pending_reload_bundle_build.is_some() {return Ok(if self.reload_dispatched_at.is_some() {ApplyUpdateResult::ReloadAlreadyDispatched} else {@@ -554,46 +601,43 @@ impl<Fs: FsRepo> Service<Fs> {matches!(status.as_ref(), Ok(UpdateStatus::ClearRequired(_)))};if should_clear {- self.clear_bundle_root(cache_dir).await?;- self.reload_pending = true;- self.reload_dispatched_at = None;- return Ok(ApplyUpdateResult::ReloadNeeded);+ return Ok(self.revert_to_embedded(cache_dir).await?);}- let entrypoint = {+ let completed = {let status = self.status().borrow();match status.as_ref() {- Ok(UpdateStatus::Completed(bundle_location)) => bundle_location.entrypoint.clone(),+ Ok(UpdateStatus::Completed(completed)) => completed.clone(),_ => return Ok(ApplyUpdateResult::NoUpdate),}};+ let bundle_build = completed.bundle_build;+ let entrypoint = completed.entrypoint;let bundle_dir = entrypoint.parent().ok_or_else(|| report!("entrypoint {entrypoint:?} has no parent directory"))?.to_path_buf();- self.set_bundle_root(bundle_dir.clone(), cache_dir).await?;+ self.set_bundle_root(bundle_dir.clone(), bundle_build, cache_dir)+ .await?;self.clear_pending_bundle(cache_dir).await?;- self.reload_pending = true;+ self.pending_reload_bundle_build = Some(bundle_build);self.reload_dispatched_at = None;- // Remove old bundle directories now that we've switched to the new one- self.cleanup_old_bundles(cache_dir, &bundle_dir).await;-Ok(ApplyUpdateResult::ReloadNeeded)}/// Record that the pending reload was successfully dispatched to the webview.pub fn mark_update_reload_dispatched(&mut self) {- if self.reload_pending {+ if self.pending_reload_bundle_build.is_some() {self.reload_dispatched_at = Some(Instant::now());}}/// Clear a pending reload dispatch marker after dispatch failed synchronously.pub fn unmark_update_reload_dispatched(&mut self) -> bool {- if !self.reload_pending || self.reload_dispatched_at.is_none() {+ if self.pending_reload_bundle_build.is_none() || self.reload_dispatched_at.is_none() {return false;}@@ -603,7 +647,7 @@ impl<Fs: FsRepo> Service<Fs> {/// Allow a stale pending reload dispatch to be attempted again.pub fn allow_update_reload_retry(&mut self) -> bool {- if !self.reload_pending || self.reload_dispatched_at.is_none() {+ if self.pending_reload_bundle_build.is_none() || self.reload_dispatched_at.is_none() {return false;}@@ -622,13 +666,29 @@ impl<Fs: FsRepo> Service<Fs> {////// Returns `Ok(true)` if a pending reload was acknowledged and the updater/// worker was nudged to check again, or `Ok(false)` when no reload was pending.- pub fn acknowledge_update_reload(&mut self) -> Result<bool, Report> {- if !self.reload_pending {+ pub async fn acknowledge_update_reload(+ &mut self,+ cache_dir: &Path,+ loaded_bundle_build: u64,+ ) -> Result<bool, Report> {+ let Some(expected_bundle_build) = self.pending_reload_bundle_build else {+ return Ok(false);+ };+ if loaded_bundle_build != expected_bundle_build {+ tracing::warn!(+ loaded_bundle_build,+ expected_bundle_build,+ "Ignoring bundle reload acknowledgement from a stale document"+ );return Ok(false);}+ self.bundle_routes.finish_transition().await;+ let active_root = self.bundle_root.path().map(Path::to_path_buf);+ self.cleanup_old_bundles(cache_dir, active_root.as_deref())+ .await;self.restart_run_after_reload_ack()?;- self.reload_pending = false;+ self.pending_reload_bundle_build = None;self.reload_dispatched_at = None;Ok(true)}@@ -639,12 +699,16 @@ impl<Fs: FsRepo> Service<Fs> {async fn set_bundle_root(&mut self,path: PathBuf,+ bundle_build: u64,cache_dir: &Path,) -> Result<(), std::io::Error> {// Persist first — only commit in-memory if the write succeeds.- let new_root = BundleRoot::from_path(path);+ let new_root = BundleRoot::from_path(path.clone());new_root.persist(cache_dir, &self.fs_repo).await?;self.bundle_root = new_root;+ self.bundle_routes+ .transition_to(BundleSource::ota(bundle_build, path))+ .await;Ok(())}@@ -734,7 +798,10 @@ impl<Fs: FsRepo> Service<Fs> {if let Err(e) = self.handle.status_tx- .send(Ok(UpdateStatus::Completed(CompletedStatus { entrypoint })))+ .send(Ok(UpdateStatus::Completed(CompletedStatus {+ bundle_build: manifest.bundle_build,+ entrypoint,+ }))){tracing::warn!(error=?e, "[bundle-update] failed to restore pending bundle status");return false;@@ -743,34 +810,53 @@ impl<Fs: FsRepo> Service<Fs> {true}- /// Clear the bundle root and remove all downloaded bundles.- pub async fn clear_bundle_root(&mut self, cache_dir: &Path) -> Result<(), std::io::Error> {- self.clear_pending_bundle(cache_dir).await?;- 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;- }+ /// Revert to the embedded bundle and request a webview reload.+ pub async fn revert_to_embedded(+ &mut self,+ cache_dir: &Path,+ ) -> Result<ApplyUpdateResult, std::io::Error> {+ if self.pending_reload_bundle_build.is_some() {+ return Ok(if self.reload_dispatched_at.is_some() {+ ApplyUpdateResult::ReloadAlreadyDispatched+ } else {+ ApplyUpdateResult::ReloadNeeded+ });}- self.bundle_root.clear();- self.bundle_root.persist(cache_dir, &self.fs_repo).await+ self.clear_bundle_root(cache_dir).await?;+ self.pending_reload_bundle_build = Some(self.embedded_bundle_build);+ self.reload_dispatched_at = None;+ Ok(ApplyUpdateResult::ReloadNeeded)}- /// Read the bundle build from `bundle-manifest.json` inside the current bundle root.+ /// Clear the active bundle root while retaining OTA files needed by the+ /// currently loaded document until reload acknowledgement.+ async fn clear_bundle_root(&mut self, cache_dir: &Path) -> Result<(), std::io::Error> {+ self.clear_pending_bundle(cache_dir).await?;+ let cleared_bundle_root = BundleRoot::new();+ cleared_bundle_root+ .persist(cache_dir, &self.fs_repo)+ .await?;+ self.bundle_root = cleared_bundle_root;+ self.bundle_routes+ .transition_to(BundleSource::embedded(self.embedded_bundle_build))+ .await;+ Ok(())+ }++ /// Return the active OTA bundle build, if the embedded bundle is not active.pub async fn bundle_build(&self) -> Option<u64> {- self.bundle_root- .manifest(&self.fs_repo)- .await- .map(|manifest| manifest.bundle_build)+ let identity = self.bundle_routes.active_identity().await;+ (identity.source == BundleSourceKind::Ota).then_some(identity.bundle_build)}/// Remove all numeric bundle subdirectories under `dir` except `keep`.- async fn cleanup_old_bundles(&self, dir: &Path, keep: &Path) {+ async fn cleanup_old_bundles(&self, dir: &Path, keep: Option<&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 {+ if keep.is_some_and(|keep| path == keep) {continue;}if let Err(e) = self.fs_repo.remove_dir_all(&path).await {@@ -876,13 +962,17 @@ impl<Fs: FsRepo> Service<Fs> {}}+#[cfg(test)]+mod persistence_test;+#[cfg(test)]+mod reload_test;#[cfg(test)]mod tests {use super::*;use crate::domain::{models::{AppInfo, Arch, BundleAction, BundleClear, BundleNativeUpdateRequired, BundleUpdate,- DownloadBundleError, DownloadBundleRequest, Target, UnzipError,+ DownloadBundleError, DownloadBundleRequest, NativeAppInfo, Target, UnzipError,},ports::AutoUpdateService,};@@ -924,7 +1014,7 @@ mod tests {}#[derive(Clone, Default)]- struct FakeFs {+ pub(super) struct FakeFs {state: Arc<StdMutex<FakeFsState>>,}@@ -935,6 +1025,7 @@ mod tests {removed_dirs: Vec<PathBuf>,unzip_target: Option<PathBuf>,checksum_should_fail: bool,+ remove_file_failure: Option<PathBuf>,}impl FakeFs {@@ -955,7 +1046,11 @@ mod tests {self.state.lock().unwrap().unzip_target = Some(path.into());}- fn file_exists(&self, path: impl AsRef<Path>) -> bool {+ pub(super) fn fail_remove_file(&self, path: impl Into<PathBuf>) {+ self.state.lock().unwrap().remove_file_failure = Some(path.into());+ }++ pub(super) fn file_exists(&self, path: impl AsRef<Path>) -> bool {self.state.lock().unwrap().files.contains_key(path.as_ref())}@@ -1075,11 +1170,24 @@ mod tests {}async fn remove_file(&self, path: &Path) -> Result<(), std::io::Error> {- self.state.lock().unwrap().files.remove(path);+ let mut state = self.state.lock().unwrap();+ if state.remove_file_failure.as_deref() == Some(path) {+ return Err(std::io::Error::other("remove failed"));+ }+ state.files.remove(path);Ok(())}}+ #[derive(Clone, Copy)]+ struct TestTaskSpawner;++ impl TaskSpawner for TestTaskSpawner {+ fn spawn(task: impl Future<Output = ()> + Send + 'static) {+ drop(tokio::spawn(task));+ }+ }+#[derive(Clone)]struct FakeSystemQuery {network_type: Arc<StdMutex<Option<String>>>,@@ -1120,9 +1228,8 @@ mod tests {}impl SystemQuery for FakeSystemQuery {- async fn get_system_info(&self) -> Result<AppInfo, rootcause::Report> {- Ok(AppInfo {- current_bundle_build: 0,+ async fn get_native_app_info(&self) -> Result<NativeAppInfo, rootcause::Report> {+ Ok(NativeAppInfo {native_build: *self.native_build.lock().unwrap(),arch: Arch::Aarch64,target: Target::Ios,@@ -1166,7 +1273,7 @@ mod tests {)}- fn cache_dir() -> PathBuf {+ pub(super) fn cache_dir() -> PathBuf {PathBuf::from("/cache")}@@ -1176,7 +1283,7 @@ mod tests {)}- fn seed_bundle(+ pub(super) fn seed_bundle(fs: &FakeFs,cache_dir: &Path,dir_name: &str,@@ -1193,7 +1300,7 @@ mod tests {dir}- fn seed_persisted_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {+ pub(super) fn seed_persisted_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {fs.write_file(cache_dir.join("bundle_root"),bundle_dir.to_string_lossy().to_string(),@@ -1210,15 +1317,22 @@ mod tests {fn service_with_network(network_type: &str) -> (Service<FakeFs>, FakeSystemQuery) {let system_query = FakeSystemQuery::new(network_type);let (update_repo, _) = fake_update_repo(Some(BundleAction::Update(bundle_update())), true);- let service = Service::new(update_repo, FakeFs::default(), system_query.clone(), 0);+ let service = Service::new::<_, _, TestTaskSpawner>(+ update_repo,+ FakeFs::default(),+ system_query.clone(),+ 0,+ 0,+ BundleRoutes::new(0),+ );(service, system_query)}- fn service_with_status(status: UpdateStatus) -> (Service<FakeFs>, StartRx) {+ pub(super) fn service_with_status(status: UpdateStatus) -> (Service<FakeFs>, StartRx) {service_with_status_fs_and_embedded_build(status, FakeFs::default(), 0)}- fn service_with_status_and_fs(+ pub(super) fn service_with_status_and_fs(status: UpdateStatus,fs_repo: FakeFs,) -> (Service<FakeFs>, StartRx) {@@ -1241,8 +1355,10 @@ mod tests {},fs_repo,embedded_bundle_build,+ native_build: 0,bundle_root: BundleRoot::new(),- reload_pending: false,+ bundle_routes: BundleRoutes::new(embedded_bundle_build),+ pending_reload_bundle_build: None,reload_dispatched_at: None,},start_rx,@@ -1254,7 +1370,7 @@ mod tests {update: Option<BundleAction>,update_dir: PathBuf,native_build: u64,- ) -> Worker<FakeUpdateRepo, FakeFs, FakeSystemQuery> {+ ) -> Worker<FakeUpdateRepo, FakeFs, FakeSystemQuery, TestTaskSpawner> {let (status_tx, _status_rx) = tokio::sync::watch::channel(Ok(UpdateStatus::Idle));let (_start_tx, start_rx) = tokio::sync::mpsc::channel(1);let (update_repo, _) = fake_update_repo(update, false);@@ -1266,6 +1382,8 @@ mod tests {update_dir,native_build,),+ bundle_routes: BundleRoutes::new(0),+ _task_spawner: PhantomData::<TestTaskSpawner>,status_tx,start_rx,}@@ -1296,11 +1414,12 @@ mod tests {fn completed_status() -> UpdateStatus {UpdateStatus::Completed(CompletedStatus {+ bundle_build: 1,entrypoint: PathBuf::from("/tmp/macro-bundle-test/1/index.html"),})}- fn clear_required_status() -> UpdateStatus {+ pub(super) fn clear_required_status() -> UpdateStatus {UpdateStatus::ClearRequired(ClearRequiredStatus {reason: "bundle_revoked".to_string(),})@@ -1479,6 +1598,7 @@ mod tests {seed_pending_bundle_root(&fs, &cache_dir, &bundle_dir);let (mut service, _start_rx) = service_with_status_and_fs(UpdateStatus::Completed(CompletedStatus {+ bundle_build: 20,entrypoint: bundle_dir.join(ENTRYPOINT_NAME),}),fs.clone(),@@ -1525,7 +1645,7 @@ mod tests {assert!(matches!(status,- UpdateStatus::Completed(CompletedStatus { entrypoint })+ UpdateStatus::Completed(CompletedStatus { entrypoint, .. })if entrypoint == bundle_dir.join(ENTRYPOINT_NAME)));}@@ -1810,8 +1930,10 @@ mod tests {},fs_repo: FakeFs::default(),embedded_bundle_build: 0,+ native_build: 0,bundle_root: BundleRoot::new(),- reload_pending: false,+ bundle_routes: BundleRoutes::new(0),+ pending_reload_bundle_build: None,reload_dispatched_at: None,};@@ -1838,14 +1960,27 @@ mod tests {seed_persisted_bundle_root(&fs, &cache_dir, &active_dir);let (mut service, _start_rx) =service_with_status_and_fs(clear_required_status(), fs.clone());- service.bundle_root = BundleRoot::from_path(active_dir);+ service.bundle_root = BundleRoot::from_path(active_dir.clone());+ service+ .bundle_routes+ .restore(BundleSource::ota(20, active_dir))+ .await;let applied = service.apply_update(&cache_dir).await.unwrap();assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);- assert!(service.reload_pending);+ assert_eq!(service.pending_reload_bundle_build, Some(0));assert!(service.bundle_root_path().is_none());assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(fs.dir_exists(cache_dir.join("1")));+ assert!(fs.dir_exists(cache_dir.join("2")));++ assert!(+ service+ .acknowledge_update_reload(&cache_dir, 0)+ .await+ .unwrap()+ );assert!(!fs.dir_exists(cache_dir.join("1")));assert!(!fs.dir_exists(cache_dir.join("2")));assert!(fs.dir_exists(cache_dir.join("logs")));@@ -1863,7 +1998,7 @@ mod tests {let applied = service.apply_update(Path::new("/tmp")).await.unwrap();assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);- assert!(service.reload_pending);+ assert_eq!(service.pending_reload_bundle_build, Some(1));assert!(service.reload_dispatched_at.is_none());assert!(matches!(&*service.status().borrow(),@@ -1871,8 +2006,13 @@ mod tests {));assert!(start_rx.try_recv().is_err());- assert!(service.acknowledge_update_reload().unwrap());- assert!(!service.reload_pending);+ assert!(+ service+ .acknowledge_update_reload(Path::new("/tmp"), 1)+ .await+ .unwrap()+ );+ assert_eq!(service.pending_reload_bundle_build, None);assert!(service.reload_dispatched_at.is_none());assert!(matches!(&*service.status().borrow(),@@ -1887,7 +2027,7 @@ mod tests {#[tokio::test]async fn apply_update_requests_reload_while_dispatch_is_pending() {let (mut service, _start_rx) = service_with_status(UpdateStatus::Idle);- service.reload_pending = true;+ service.pending_reload_bundle_build = Some(1);let applied = service.apply_update(Path::new("/tmp")).await.unwrap();@@ -1951,25 +2091,35 @@ mod tests {);}- #[test]- fn acknowledge_update_reload_returns_false_without_pending_reload() {+ #[tokio::test]+ async fn acknowledge_update_reload_returns_false_without_pending_reload() {let (mut service, _start_rx) = service_with_status(UpdateStatus::Idle);- assert!(!service.acknowledge_update_reload().unwrap());+ assert!(+ !service+ .acknowledge_update_reload(Path::new("/tmp"), 0)+ .await+ .unwrap()+ );}- #[test]- fn acknowledge_update_reload_treats_full_command_queue_as_acknowledged() {+ #[tokio::test]+ async fn acknowledge_update_reload_treats_full_command_queue_as_acknowledged() {let (mut service, _start_rx) = service_with_status(UpdateStatus::Idle);- service.reload_pending = true;+ service.pending_reload_bundle_build = Some(0);service.handle.start_tx.try_send(WorkerCommand::Continue).unwrap();- assert!(service.acknowledge_update_reload().unwrap());- assert!(!service.reload_pending);+ assert!(+ service+ .acknowledge_update_reload(Path::new("/tmp"), 0)+ .await+ .unwrap()+ );+ assert_eq!(service.pending_reload_bundle_build, None);assert!(service.reload_dispatched_at.is_none());assert!(matches!(&*service.status().borrow(),diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/persistence_test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/persistence_test.rsnew file mode 100644index 0000000000..39116d5c1a--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/persistence_test.rs@@ -0,0 +1,33 @@+use super::{+ BundleRoot, BundleSource,+ tests::{+ FakeFs, cache_dir, clear_required_status, seed_bundle, seed_persisted_bundle_root,+ service_with_status_and_fs,+ },+};++#[tokio::test]+async fn failed_bundle_root_persistence_preserves_active_bundle_state() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let active_dir = seed_bundle(&fs, &cache_dir, "1", 20, 0);+ let persisted_root = cache_dir.join("bundle_root");+ seed_persisted_bundle_root(&fs, &cache_dir, &active_dir);+ fs.fail_remove_file(&persisted_root);+ let (mut service, _start_rx) = service_with_status_and_fs(clear_required_status(), fs.clone());+ service.bundle_root = BundleRoot::from_path(active_dir.clone());+ service+ .bundle_routes+ .restore(BundleSource::ota(20, active_dir.clone()))+ .await;++ assert!(service.apply_update(&cache_dir).await.is_err());++ assert_eq!(service.bundle_root_path(), Some(active_dir.as_path()));+ assert_eq!(+ service.bundle_routes.active_identity().await,+ BundleSource::ota(20, active_dir).identity()+ );+ assert!(fs.file_exists(persisted_root));+ assert_eq!(service.pending_reload_bundle_build, None);+}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/reload_test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/reload_test.rsnew file mode 100644index 0000000000..d5afe71c3d--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/reload_test.rs@@ -0,0 +1,34 @@+use std::path::{Path, PathBuf};++use super::{ApplyUpdateResult, CompletedStatus, UpdateStatus, tests::service_with_status};++#[tokio::test]+async fn stale_document_cannot_acknowledge_a_new_bundle_generation() {+ let (mut service, mut start_rx) =+ service_with_status(UpdateStatus::Completed(CompletedStatus {+ bundle_build: 2,+ entrypoint: PathBuf::from("/cache/2/index.html"),+ }));+ assert_eq!(+ service.apply_update(Path::new("/cache")).await.unwrap(),+ ApplyUpdateResult::ReloadNeeded+ );++ let acknowledged = service+ .acknowledge_update_reload(Path::new("/cache"), 1)+ .await+ .unwrap();++ assert!(!acknowledged);+ assert_eq!(service.pending_reload_bundle_build, Some(2));+ assert!(start_rx.try_recv().is_err());+ let routes = service.bundle_routes.read().await;+ assert_eq!(routes.active.identity().bundle_build, 2);+ assert_eq!(+ routes+ .fallback+ .as_ref()+ .map(|source| source.identity().bundle_build),+ Some(0)+ );+}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 dd5f9d80bc..f6b43e91b6 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@@ -8,6 +8,7 @@ use url::Url;use crate::{domain::{+ bundle_routes::BundleRoutes,models::{UpdateError, UpdateStatus},ports::AutoUpdateService,service::{ApplyUpdateResult, Service},@@ -15,6 +16,7 @@ use crate::{outbound::{api_client::BundleClient,fs::FileSystem,+ runtime::TauriTaskSpawner,system_info::{SystemInfo, native_build},},};@@ -137,15 +139,17 @@ impl BundleUpdateEvent {pub struct MacroBundleUpdaterPlugin {base_url: Url,embedded_bundle_build: u64,+ bundle_routes: BundleRoutes,auto_update: bool,}impl MacroBundleUpdaterPlugin {/// Create the plugin targeting the given update server URL.- pub fn new(base_url: Url, embedded_bundle_build: u64) -> Self {+ pub fn new(base_url: Url, embedded_bundle_build: u64, bundle_routes: BundleRoutes) -> Self {Self {base_url,embedded_bundle_build,+ bundle_routes,auto_update: true,}}@@ -282,13 +286,20 @@ pub async fn perform_update<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Resu/// Acknowledge that the webview mounted after an applied bundle update reload.#[tauri::command]-pub async fn ack_bundle_update_reload(+pub async fn ack_bundle_update_reload<R: Runtime>(service: tauri::State<'_, Mutex<PluginService>>,+ app_handle: tauri::AppHandle<R>,+ loaded_bundle_build: u64,) -> Result<bool, String> {+ let cache_dir = app_handle+ .path()+ .app_cache_dir()+ .map_err(|e| e.to_string())?;service.lock().await- .acknowledge_update_reload()+ .acknowledge_update_reload(&cache_dir, loaded_bundle_build)+ .await.map_err(|e| e.to_string())}@@ -326,7 +337,7 @@ pub async fn get_bundle_debug_info(} else {BundleDebugSource::Embedded},- native_build: crate::outbound::system_info::native_build(),+ native_build: service.native_build(),})}@@ -341,15 +352,28 @@ pub async fn clear_bundle<R: Runtime>(.app_cache_dir().map_err(|e| e.to_string())?;- service- .lock()- .await- .clear_bundle_root(&cache_dir)- .await- .map_err(|e| e.to_string())?;+ let apply_result = {+ let mut service = service.lock().await;+ let result = service+ .revert_to_embedded(&cache_dir)+ .await+ .map_err(|e| e.to_string())?;+ if result == ApplyUpdateResult::ReloadNeeded {+ service.mark_update_reload_dispatched();+ }+ result+ };- if let Some(webview) = app_handle.webview_windows().values().next() {- let _ = webview.eval("window.location.reload();");+ if apply_result == ApplyUpdateResult::ReloadNeeded {+ 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();+ }+ } else {+ tracing::warn!("[bundle-update] bundle cleared but no webview was available to reload");+ service.lock().await.unmark_update_reload_dispatched();+ }}Ok(())}@@ -366,18 +390,24 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {) -> Result<(), Box<dyn std::error::Error>> {let client = BundleClient::new(self.base_url.clone());let fs = FileSystem;- let system_info = SystemInfo::new(app.clone(), self.embedded_bundle_build);-- let mut service = Service::new(client, fs, system_info, self.embedded_bundle_build);+ let native_build = native_build();+ let system_info = SystemInfo::new(app.clone(), native_build);++ let mut service = Service::new::<_, _, TauriTaskSpawner>(+ client,+ fs,+ system_info,+ self.embedded_bundle_build,+ native_build,+ self.bundle_routes.clone(),+ );let mut acknowledge_setup_apply = false;let mut start_update_check = false;if !self.auto_update {- tracing::info!(- "[bundle-update] automatic bundle updates are disabled in this build"- );+ tracing::info!("[bundle-update] automatic bundle updates are disabled in this build");} else if let Ok(cache_dir) = app.path().app_cache_dir() {let restored_pending = tauri::async_runtime::block_on(async {- service.load_bundle_root(&cache_dir, native_build()).await+ service.load_bundle_root(&cache_dir, native_build).await});if restored_pending {match tauri::async_runtime::block_on(async {@@ -427,10 +457,22 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {return Ok(());};if acknowledge_setup_apply {- if let Err(e) = service.acknowledge_update_reload() {- tracing::warn!(- "[bundle-update] failed to acknowledge plugin-initialized bundle apply: {e}"- );+ match app.path().app_cache_dir() {+ Ok(cache_dir) => {+ let loaded_bundle_build =+ tauri::async_runtime::block_on(service.bundle_build())+ .unwrap_or(service.embedded_bundle_build());+ if let Err(e) = tauri::async_runtime::block_on(+ service.acknowledge_update_reload(&cache_dir, loaded_bundle_build),+ ) {+ tracing::warn!(+ "[bundle-update] failed to acknowledge plugin-initialized bundle apply: {e}"+ );+ }+ }+ Err(e) => tracing::warn!(+ "[bundle-update] failed to read cache dir for setup acknowledgement: {e}"+ ),}} else if let Err(e) = service.start() {tracing::warn!(diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound.rsindex d5f36c03c6..5ef7211b72 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound.rs@@ -2,5 +2,7 @@pub mod api_client;/// Filesystem operations for bundle extraction and persistence.pub mod fs;+/// Host async runtime integration.+pub mod runtime;/// System information queries (version, arch, target, cache dir).pub mod system_info;diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs.rsindex c08ead8939..0cf12a5a77 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs.rs@@ -1,6 +1,7 @@use crate::domain::{+ asset_service::{BundleAssetPath, BundleAssetReadError},models::{UnzipError, UnzipRequest},- ports::FsRepo,+ ports::{BundleAssetRepo, FsRepo},};use digest::Digest;use sha2::Sha256;@@ -11,6 +12,25 @@ use zip::{read::root_dir_common_filter, result::ZipError};#[derive(Clone)]pub struct FileSystem;+impl BundleAssetRepo for FileSystem {+ async fn read_asset(+ &self,+ root: &std::path::Path,+ path: &BundleAssetPath,+ ) -> Result<Option<Vec<u8>>, BundleAssetReadError> {+ let canonical_root = tokio::fs::canonicalize(root).await?;+ let canonical_file = match tokio::fs::canonicalize(root.join(path.as_path())).await {+ Ok(path) => path,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ };+ if !canonical_file.starts_with(&canonical_root) {+ return Err(BundleAssetReadError::OutsideBundleRoot);+ }+ Ok(Some(tokio::fs::read(canonical_file).await?))+ }+}+fn map_zip_err(err: ZipError) -> UnzipError {match err {ZipError::Io(error) => UnzipError::IoErr(error),diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime.rsnew file mode 100644index 0000000000..d2f4233129--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime.rs@@ -0,0 +1,14 @@+use crate::domain::ports::TaskSpawner;++/// Spawns detached updater tasks on Tauri's application-wide Tokio runtime.+#[derive(Debug, Clone, Copy, Default)]+pub struct TauriTaskSpawner;++impl TaskSpawner for TauriTaskSpawner {+ fn spawn(task: impl Future<Output = ()> + Send + 'static) {+ drop(tauri::async_runtime::spawn(task));+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime/test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime/test.rsnew file mode 100644index 0000000000..c79d4bf1ba--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/runtime/test.rs@@ -0,0 +1,17 @@+use std::{sync::mpsc, time::Duration};++use super::*;++#[test]+fn spawns_without_an_entered_tokio_runtime() {+ assert!(tokio::runtime::Handle::try_current().is_err());+ let (sender, receiver) = mpsc::channel();++ TauriTaskSpawner::spawn(async move {+ sender.send(()).unwrap();+ });++ receiver+ .recv_timeout(Duration::from_secs(1))+ .expect("task should run on Tauri's global runtime");+}diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rsindex 390d0c18f9..3ba54080c8 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs@@ -2,22 +2,22 @@ use tauri::{Manager, Runtime};use tauri_plugin_device_info::DeviceInfoExt;use crate::domain::{- models::{AppInfo, Arch, Target},+ models::{Arch, NativeAppInfo, Target},ports::SystemQuery,};/// Queries the running Tauri app for version, architecture, and OS target.pub struct SystemInfo<R: Runtime> {app_handle: tauri::AppHandle<R>,- embedded_bundle_build: u64,+ native_build: u64,}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>, embedded_bundle_build: u64) -> Self {+ pub fn new(app_handle: tauri::AppHandle<R>, native_build: u64) -> Self {Self {app_handle,- embedded_bundle_build,+ native_build,}}@@ -32,21 +32,6 @@ impl<R: Runtime> SystemInfo<R> {}}- async fn current_bundle_build(&self) -> u64 {- // If an OTA update has been applied, read the bundle build from its- // manifest; otherwise report the build embedded with this native app.- if let Some(s) = self- .app_handle- .try_state::<tokio::sync::Mutex<crate::inbound::plugin::PluginService>>()- {- let service = s.lock().await;- if let Some(build) = service.bundle_build().await {- return build;- }- }- self.embedded_bundle_build- }-fn get_arch(&self) -> Arch {match std::env::consts::ARCH {"aarch64" => Arch::Aarch64,@@ -59,10 +44,9 @@ 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_bundle_build: self.current_bundle_build().await,- native_build: native_build(),+ async fn get_native_app_info(&self) -> Result<NativeAppInfo, rootcause::Report> {+ Ok(NativeAppInfo {+ native_build: self.native_build,arch: self.get_arch(),target: self.get_target(),})diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex a1cc9f4045..7bdb240045 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -1,9 +1,13 @@use logger::Logger;+use macro_bundle_updater_plugin::domain::{+ asset_service::BundleAssetResolver, bundle_routes::BundleRoutes,+};use macro_bundle_updater_plugin::inbound::plugin::retry_waiting_for_wifi;#[cfg(feature = "auto_apply_update")]use macro_bundle_updater_plugin::inbound::plugin::{allow_update_reload_retry, apply_completed_update_from, start_update_check,};+use macro_bundle_updater_plugin::outbound::fs::FileSystem;use navigation_plugin::MacroNavigationPlugin;use navigation_plugin::scheme::MacroScheme;use reqwest::cookie::CookieStore;@@ -129,6 +133,9 @@ pub fn run() {registry.init();+ let embedded_bundle_build = embedded_bundle_build();+ let bundle_routes = BundleRoutes::new(embedded_bundle_build);+ let bundle_asset_resolver = BundleAssetResolver::new(bundle_routes.clone(), FileSystem);let mut builder = tauri::Builder::default();#[cfg(desktop)]@@ -178,7 +185,8 @@ pub fn run() {.bundle_update_base_url().parse().expect("valid url"),- embedded_bundle_build(),+ embedded_bundle_build,+ bundle_routes.clone(),)// Builds without this feature (just ios-dev, ios-build-no-update)// must never check for or apply OTA bundles on their own; manual@@ -218,7 +226,7 @@ pub fn run() {move |ctx, request, responder| {let h = handler.get_or_init(|| {let app = ctx.app_handle();- tauri_protocol::get(app.clone(), &window_origin)+ tauri_protocol::get(app.clone(), &window_origin, bundle_asset_resolver.clone())});h(ctx.webview_label(), request, responder);}diff --git a/apps/web/tauri/src-tauri/src/tauri_protocol.rs b/apps/web/tauri/src-tauri/src/tauri_protocol.rsindex 659df99e78..2115dbef91 100644--- a/apps/web/tauri/src-tauri/src/tauri_protocol.rs+++ b/apps/web/tauri/src-tauri/src/tauri_protocol.rs@@ -1,20 +1,36 @@-// Wrapper around the upstream tauri protocol handler.+// Wrapper around the upstream Tauri protocol handler.//// Adds two behaviors on top of the built-in `tauri://` protocol:-// 1. Strips the `/app/` base path prefix before asset resolution-// 2. Checks `BundleRoot` state to serve from an OTA-updated bundle on disk-//-// When `BundleRoot` is `None`, the request (with `/app/` stripped) is forwarded-// to the upstream handler which handles dev proxy, CSP, security headers, etc.-// When `BundleRoot` is `Some(path)`, files are served directly from disk.+// 1. Strips the `/app/` base path prefix before embedded asset resolution.+// 2. Resolves OTA assets through the bundle updater's domain service.use http::{Response as HttpResponse, StatusCode, header::CONTENT_TYPE};-use tauri::{Manager, Runtime, UriSchemeResponder};+use macro_bundle_updater_plugin::domain::{+ asset_service::{+ BundleAssetPath, BundleAssetReadError, BundleAssetResolution, BundleAssetResolver,+ InvalidBundleAssetPath,+ },+ ports::BundleAssetRepo,+};+use std::time::Duration;+use tauri::{Runtime, UriSchemeResponder};++const ASSET_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(30);++type ProtocolHandlerFn = dyn Fn(&str, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync;+type ProtocolHandler = Box<ProtocolHandlerFn>;-use macro_bundle_updater_plugin::inbound::plugin::PluginService;-use tokio::sync::Mutex;+#[derive(Debug, PartialEq, Eq)]+enum RequestPathError {+ InvalidEncoding,+ Unsafe(InvalidBundleAssetPath),+}-type ProtocolHandler = Box<dyn Fn(&str, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;+enum TimedAssetResolution {+ Resolved(Result<BundleAssetResolution, BundleAssetReadError>),+ TaskFailed(tauri::Error),+ TimedOut,+}/// Strip the `/app` or `/app/` prefix used as the frontend base path./// Only strips when `/app` is a complete path segment (not e.g. `/app.css`).@@ -28,6 +44,29 @@ fn strip_app_prefix(path: &str) -> &str {path}+fn request_asset_path(uri: &http::Uri) -> Result<BundleAssetPath, RequestPathError> {+ let encoded = uri.path();+ let bytes = encoded.as_bytes();+ let mut index = 0;+ while index < bytes.len() {+ if bytes[index] == b'%' {+ let Some(hex) = bytes.get(index + 1..index + 3) else {+ return Err(RequestPathError::InvalidEncoding);+ };+ if !hex.iter().all(u8::is_ascii_hexdigit) {+ return Err(RequestPathError::InvalidEncoding);+ }+ index += 3;+ } else {+ index += 1;+ }+ }+ let decoded = urlencoding::decode(encoded).map_err(|_| RequestPathError::InvalidEncoding)?;+ let path = strip_app_prefix(&decoded);+ let relative = path.strip_prefix('/').unwrap_or(path);+ BundleAssetPath::new(relative).map_err(RequestPathError::Unsafe)+}+/// Rewrite a URI by stripping the `/app/` prefix from the path portion./// e.g. `tauri://localhost/app/index.html` → `tauri://localhost/index.html`fn rewrite_uri(uri: &str) -> String {@@ -40,141 +79,211 @@ fn rewrite_uri(uri: &str) -> String {if let Some(rest) = uri.strip_prefix(prefix) {// Only match bare "/app" when rest is empty or starts with a// path separator — avoid rewriting "/app.css" etc.- if !prefix.ends_with('/') && !rest.is_empty() && !rest.starts_with('/') {+ if !prefix.ends_with('/')+ && !rest.is_empty()+ && !rest.starts_with('/')+ && !rest.starts_with('?')+ {continue;}let origin = prefix.trim_end_matches("/app/").trim_end_matches("/app");- return format!("{}/{}", origin, rest);+ return format!("{origin}/{rest}");}}uri.to_string()}-/// Build the protocol handler that wraps the built-in `tauri://` protocol.-///-/// The upstream handler is called for all requests where `BundleRoot` is not set.-/// When `BundleRoot` is set (after an OTA update), files are served from disk instead.-pub fn get<R: Runtime>(app_handle: tauri::AppHandle<R>, window_origin: &str) -> ProtocolHandler {- let upstream = tauri::protocol::tauri::get(app_handle.clone(), window_origin, None);- let origin = window_origin.to_string();+fn respond_status(+ responder: UriSchemeResponder,+ status: StatusCode,+ origin: &str,+ message: impl Into<Vec<u8>>,+) {+ responder.respond(+ HttpResponse::builder()+ .status(status)+ .header(CONTENT_TYPE, "text/plain; charset=utf-8")+ .header("Access-Control-Allow-Origin", origin)+ .body(message.into())+ .expect("valid custom protocol response"),+ );+}- Box::new(move |webview_id, request, responder| {- let service = app_handle.try_state::<Mutex<PluginService>>();- let root_dir_owned = service- .as_ref()- .and_then(|s| s.try_lock().ok())- .and_then(|s| s.bundle_root_path().map(|p| p.to_path_buf()));-- if let Some(ref root_dir) = root_dir_owned {- // Serve from the OTA bundle directory on disk- let raw_path = request- .uri()- .to_string()- .split(&['?', '#'][..])- .next()- .unwrap_or_default()- .to_string();+fn delegate_to_embedded(+ upstream: &ProtocolHandlerFn,+ webview_id: &str,+ request: http::Request<Vec<u8>>,+ responder: UriSchemeResponder,+) {+ let uri = request.uri().to_string();+ let rewritten = rewrite_uri(&uri);+ if rewritten == uri {+ upstream(webview_id, request, responder);+ return;+ }- let path = raw_path- .strip_prefix("tauri://localhost")- .or_else(|| raw_path.strip_prefix("https://tauri.localhost"))- .unwrap_or(&raw_path);+ let (mut parts, body) = request.into_parts();+ if let Ok(uri) = rewritten.parse() {+ parts.uri = uri;+ }+ upstream(+ webview_id,+ http::Request::from_parts(parts, body),+ responder,+ );+}- let asset_path = strip_app_prefix(path);- // Serve index.html for empty/root paths (SPA fallback)- let asset_path = match asset_path {- "" | "/" => "index.html",- p => p.strip_prefix('/').unwrap_or(p),- };+async fn resolve_asset_with_timeout<Assets: BundleAssetRepo>(+ resolver: BundleAssetResolver<Assets>,+ asset_path: BundleAssetPath,+ timeout: Duration,+) -> TimedAssetResolution {+ // Keep resolution in an independently owned task. If the timeout elapses,+ // dropping its join handle detaches rather than cancels it, so its route+ // read lease remains held until any in-flight filesystem read completes.+ let resolution_task =+ tauri::async_runtime::spawn(async move { resolver.resolve(&asset_path).await });+ match tokio::time::timeout(timeout, resolution_task).await {+ Ok(Ok(resolution)) => TimedAssetResolution::Resolved(resolution),+ Ok(Err(error)) => TimedAssetResolution::TaskFailed(error),+ Err(_) => TimedAssetResolution::TimedOut,+ }+}- // Prevent path traversal: canonicalize both paths and verify- // the resolved file stays within the bundle root.- let canonical_root = match root_dir.canonicalize() {- Ok(p) => p,- Err(_) => {- responder.respond(- HttpResponse::builder()- .status(StatusCode::NOT_FOUND)- .header("Access-Control-Allow-Origin", &*origin)- .body(Vec::new())- .unwrap(),- );- return;- }- };- let file_path = root_dir.join(asset_path);- let canonical_file = match file_path.canonicalize() {- Ok(p) => p,- Err(_) => {- responder.respond(- HttpResponse::builder()- .status(StatusCode::NOT_FOUND)- .header("Access-Control-Allow-Origin", &*origin)- .body(Vec::new())- .unwrap(),- );- return;- }- };- if !canonical_file.starts_with(&canonical_root) {- responder.respond(- HttpResponse::builder()- .status(StatusCode::FORBIDDEN)- .header("Access-Control-Allow-Origin", &*origin)- .body(Vec::new())- .unwrap(),- );- return;- }+async fn resolve_request<Assets: BundleAssetRepo>(+ resolver: BundleAssetResolver<Assets>,+ upstream: &ProtocolHandlerFn,+ webview_id: String,+ request: http::Request<Vec<u8>>,+ responder: UriSchemeResponder,+ origin: String,+) {+ let asset_path = match request_asset_path(request.uri()) {+ Ok(path) => path,+ Err(RequestPathError::InvalidEncoding) => {+ respond_status(+ responder,+ StatusCode::BAD_REQUEST,+ &origin,+ "invalid percent encoding in asset path",+ );+ return;+ }+ Err(RequestPathError::Unsafe(_)) => {+ respond_status(+ responder,+ StatusCode::FORBIDDEN,+ &origin,+ "asset path escaped bundle root",+ );+ return;+ }+ };- match std::fs::read(&canonical_file) {- Ok(data) => {- let mime = mime_guess::from_path(&file_path)- .first_or_octet_stream()- .to_string();- responder.respond(- HttpResponse::builder()- .header(CONTENT_TYPE, &mime)- .header("Access-Control-Allow-Origin", &*origin)- .body(data)- .unwrap(),- );- }- Err(_) => {- // SPA fallback: serve index.html for extensionless paths (client-side routes)- let has_extension = std::path::Path::new(asset_path).extension().is_some();- if !has_extension && let Ok(data) = std::fs::read(root_dir.join("index.html")) {- responder.respond(- HttpResponse::builder()- .header(CONTENT_TYPE, "text/html")- .header("Access-Control-Allow-Origin", &*origin)- .body(data)- .unwrap(),- );- return;- }- responder.respond(- HttpResponse::builder()- .status(StatusCode::NOT_FOUND)- .header("Access-Control-Allow-Origin", &*origin)- .body(Vec::new())- .unwrap(),- );- }- }- } else {- // Strip /app/ prefix and delegate to upstream handler- let uri = request.uri().to_string();- let rewritten = rewrite_uri(&uri);-- if rewritten != uri {- let (mut parts, body) = request.into_parts();- parts.uri = rewritten.parse().unwrap_or(parts.uri);- let request = http::Request::from_parts(parts, body);- upstream(webview_id, request, responder);- } else {- upstream(webview_id, request, responder);- }+ let resolution = match resolve_asset_with_timeout(+ resolver,+ asset_path.clone(),+ ASSET_RESOLUTION_TIMEOUT,+ )+ .await+ {+ TimedAssetResolution::Resolved(Ok(resolution)) => resolution,+ TimedAssetResolution::Resolved(Err(BundleAssetReadError::OutsideBundleRoot)) => {+ respond_status(+ responder,+ StatusCode::FORBIDDEN,+ &origin,+ "resolved asset escaped bundle root",+ );+ return;+ }+ TimedAssetResolution::Resolved(Err(BundleAssetReadError::Io(error))) => {+ tracing::error!(error=?error, path=?asset_path.as_path(), "failed to read OTA asset");+ respond_status(+ responder,+ StatusCode::INTERNAL_SERVER_ERROR,+ &origin,+ "failed to read OTA asset",+ );+ return;+ }+ TimedAssetResolution::TaskFailed(error) => {+ tracing::error!(error=?error, path=?asset_path.as_path(), "bundle asset resolver task failed");+ respond_status(+ responder,+ StatusCode::INTERNAL_SERVER_ERROR,+ &origin,+ "failed to resolve bundle asset",+ );+ return;}+ TimedAssetResolution::TimedOut => {+ tracing::error!(path=?asset_path.as_path(), "timed out resolving bundle asset");+ respond_status(+ responder,+ StatusCode::GATEWAY_TIMEOUT,+ &origin,+ "timed out resolving bundle asset",+ );+ return;+ }+ };++ match resolution {+ BundleAssetResolution::Ota {+ bytes,+ content_path,+ } => {+ let mime = mime_guess::from_path(content_path.as_path())+ .first_or_octet_stream()+ .to_string();+ responder.respond(+ HttpResponse::builder()+ .header(CONTENT_TYPE, mime)+ .header("Access-Control-Allow-Origin", origin)+ .body(bytes)+ .expect("valid OTA asset response"),+ );+ }+ BundleAssetResolution::Embedded => {+ delegate_to_embedded(&*upstream, &webview_id, request, responder);+ }+ BundleAssetResolution::NotFound => {+ respond_status(+ responder,+ StatusCode::NOT_FOUND,+ &origin,+ "bundle asset not found",+ );+ }+ }+}++/// Build the asynchronous protocol handler that wraps Tauri's built-in handler.+pub fn get<R, Assets>(+ app_handle: tauri::AppHandle<R>,+ window_origin: &str,+ resolver: BundleAssetResolver<Assets>,+) -> ProtocolHandler+where+ R: Runtime,+ Assets: BundleAssetRepo,+{+ let upstream = &*Box::leak(tauri::protocol::tauri::get(app_handle, window_origin, None));++ let origin = window_origin.to_string();++ Box::new(move |webview_id, request, responder| {+ tauri::async_runtime::spawn(resolve_request(+ resolver.clone(),+ upstream,+ webview_id.to_owned(),+ request,+ responder,+ origin.clone(),+ ));})}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/src-tauri/src/tauri_protocol/test.rs b/apps/web/tauri/src-tauri/src/tauri_protocol/test.rsnew file mode 100644index 0000000000..d28241c5f4--- /dev/null+++ b/apps/web/tauri/src-tauri/src/tauri_protocol/test.rs@@ -0,0 +1,136 @@+use std::{path::Path, sync::Arc};++use macro_bundle_updater_plugin::domain::bundle_routes::{BundleRoutes, BundleSource};+use tokio::sync::Notify;++use super::*;++#[derive(Clone)]+struct BlockingAssets {+ read_started: Arc<Notify>,+ finish_read: Arc<Notify>,+}++impl BundleAssetRepo for BlockingAssets {+ async fn read_asset(+ &self,+ _root: &Path,+ _path: &BundleAssetPath,+ ) -> Result<Option<Vec<u8>>, BundleAssetReadError> {+ self.read_started.notify_one();+ self.finish_read.notified().await;+ Ok(Some(Vec::new()))+ }+}++#[test]+fn strips_only_complete_app_path_segments() {+ assert_eq!(strip_app_prefix("/app/assets/main.js"), "assets/main.js");+ assert_eq!(strip_app_prefix("/app"), "");+ assert_eq!(strip_app_prefix("/app.css"), "/app.css");+}++#[test]+fn parses_asset_paths_without_query_parameters() {+ let uri = "tauri://localhost/app/assets/main.js?cache=1"+ .parse::<http::Uri>()+ .unwrap();++ let path = request_asset_path(&uri).unwrap();++ assert_eq!(path.as_path(), Path::new("assets/main.js"));+}++#[test]+fn root_path_resolves_to_the_entrypoint() {+ let uri = "tauri://localhost/app".parse::<http::Uri>().unwrap();++ let path = request_asset_path(&uri).unwrap();++ assert_eq!(path.as_path(), Path::new("index.html"));+}++#[test]+fn rejects_percent_encoded_path_traversal() {+ let uri = "tauri://localhost/app/assets/%2e%2e/secret"+ .parse::<http::Uri>()+ .unwrap();++ assert!(matches!(+ request_asset_path(&uri),+ Err(RequestPathError::Unsafe(_))+ ));+}++#[test]+fn rejects_invalid_percent_encoding() {+ let uri = "tauri://localhost/app/assets/%ZZ"+ .parse::<http::Uri>()+ .unwrap();++ assert_eq!(+ request_asset_path(&uri),+ Err(RequestPathError::InvalidEncoding)+ );+}++#[test]+fn rewrites_embedded_asset_uris() {+ assert_eq!(+ rewrite_uri("tauri://localhost/app/assets/main.js?cache=1"),+ "tauri://localhost/assets/main.js?cache=1"+ );+ assert_eq!(+ rewrite_uri("https://tauri.localhost/app/login"),+ "https://tauri.localhost/login"+ );+ assert_eq!(+ rewrite_uri("tauri://localhost/app?cache=1"),+ "tauri://localhost/?cache=1"+ );+ assert_eq!(+ rewrite_uri("tauri://localhost/app.css"),+ "tauri://localhost/app.css"+ );+}++#[tokio::test]+async fn timed_out_asset_read_keeps_route_lease_until_read_finishes() {+ let routes = BundleRoutes::new(1);+ routes+ .transition_to(BundleSource::ota(2, "/cache/2".into()))+ .await;+ let read_started = Arc::new(Notify::new());+ let finish_read = Arc::new(Notify::new());+ let resolver = BundleAssetResolver::new(+ routes.clone(),+ BlockingAssets {+ read_started: read_started.clone(),+ finish_read: finish_read.clone(),+ },+ );++ let resolution = tokio::spawn(resolve_asset_with_timeout(+ resolver,+ BundleAssetPath::new("main.js").unwrap(),+ Duration::from_millis(1),+ ));+ read_started.notified().await;+ assert!(matches!(+ resolution.await.unwrap(),+ TimedAssetResolution::TimedOut+ ));++ let finish_transition = tokio::spawn({+ let routes = routes.clone();+ async move { routes.finish_transition().await }+ });+ tokio::task::yield_now().await;+ assert!(!finish_transition.is_finished());++ finish_read.notify_one();+ assert_eq!(+ finish_transition.await.unwrap(),+ Some(BundleSource::embedded(1))+ );+}