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.

fix(mobile): auto-update ux (#3656)

Peter Chinman42259418f927
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index c5f488cecf..b973ae59f3 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -678,17 +678,19 @@ function NotificationNotSupported() {
function bundleUpdateAction(
status: BundleUpdateStatus,
- cancelWifiWait: () => void,
): { label: string; action: () => void } | null {
+ const grantBundleUpdate = () =>
+ invoke('grant_bundle_update', { approved: true }).catch(console.error);
+
switch (status.status) {
case 'Idle':
return { label: 'Check for Update', action: () => invoke('check_for_update') };
case 'Error':
return { label: 'Retry', action: () => invoke('check_for_update') };
case 'UpdateFound':
- return { label: 'Download', action: () => invoke('grant_bundle_update', { approved: true }).catch(console.error) };
+ return { label: 'Download', action: grantBundleUpdate };
case 'WaitingForWifi':
- return { label: 'Download anyway', action: cancelWifiWait };
+ return { label: 'Download anyway', action: grantBundleUpdate };
case 'Completed':
return { label: 'Update', action: () => invoke('perform_update') };
default:
@@ -702,7 +704,7 @@ function BundleUpdateRow() {
<Show when={tauri}>
{(ctx) => {
const status = () => ctx().bundleUpdateStatus();
- const action = () => bundleUpdateAction(status(), ctx().cancelWifiWait);
+ const action = () => bundleUpdateAction(status());
return (
<Row label="App Update">
<div class="flex items-center gap-3">
diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsx
index cd7cfff9d9..014aa23f5e 100644
--- a/js/app/packages/tauri/src/TauriProvider.tsx
+++ b/js/app/packages/tauri/src/TauriProvider.tsx
@@ -7,16 +7,13 @@ import { listen } from '@tauri-apps/api/event';
import { type OsType, type as osType } from '@tauri-apps/plugin-os';
import {
type Accessor,
- batch,
createContext,
- createEffect,
createSignal,
type JSX,
onCleanup,
onMount,
useContext,
} from 'solid-js';
-import { getNetworkInfo } from 'tauri-plugin-device-info-api';
import { getInsets, type Insets } from 'tauri-plugin-safe-area-insets';
import { useTauriNavigationEffect } from './navigation';
import { MaybePushNotificationRegistration } from './PushNotification';
@@ -39,7 +36,6 @@ interface TauriContextValue {
os: OsType;
runtimeInsets: Accessor<Insets | NotAndroid>;
bundleUpdateStatus: Accessor<BundleUpdateStatus>;
- cancelWifiWait: () => void;
}
const TauriContext = createContext<TauriContextValue | undefined>(undefined);
@@ -51,99 +47,21 @@ function TauriProvider(props: { children: JSX.Element }) {
const [insets, setInsets] = createSignal<NotAndroid | Insets>('not-android');
const [bundleUpdateStatus, setBundleUpdateStatus] =
createSignal<BundleUpdateStatus>({ status: 'Idle' });
- const [waitingForWifi, setWaitingForWifi] = createSignal(false);
- function grantBundleUpdate() {
- invoke('grant_bundle_update', { approved: true }).catch((e) =>
- console.error('[bundle-update] grant_bundle_update failed', e)
+ function performBundleUpdate() {
+ invoke<boolean>('perform_update').catch((e) =>
+ console.error('[bundle-update] perform_update failed', e)
);
}
- function cancelWifiWait() {
- batch(() => {
- setWaitingForWifi(false);
- setBundleUpdateStatus({ status: 'CheckingForUpdate' });
- });
- grantBundleUpdate();
- }
-
if (isTauri() && isPlatform('ios')) useCallKitSetup();
const value: TauriContextValue = {
runtimeInsets: insets,
os: osType(),
bundleUpdateStatus,
- cancelWifiWait,
};
- // When an update is found, only approve the download if we're on wifi/ethernet.
- // On cellular, wait and poll until a suitable connection is available.
- createEffect(() => {
- const status = bundleUpdateStatus();
- if (status.status !== 'UpdateFound') return;
-
- let aborted = false;
- onCleanup(() => {
- aborted = true;
- });
-
- console.info('[bundle-update] update found, checking network');
- getNetworkInfo()
- .then((info) => {
- if (aborted) return;
- if (['wifi', 'ethernet'].includes(info.networkType ?? '')) {
- console.info('[bundle-update] network ok, approving download');
- grantBundleUpdate();
- } else {
- console.info('[bundle-update] cellular network, waiting for wifi');
- batch(() => {
- setBundleUpdateStatus({ status: 'WaitingForWifi' });
- setWaitingForWifi(true);
- });
- }
- })
- .catch((e) => {
- if (aborted) return;
- // If network detection fails, allow the download rather than blocking it.
- console.warn(
- '[bundle-update] network check failed, approving download',
- e
- );
- grantBundleUpdate();
- });
- });
-
- // While waiting for wifi, poll on a 30s interval and on app foreground.
- createEffect(() => {
- if (!waitingForWifi()) return;
-
- async function tryGrant() {
- try {
- const info = await getNetworkInfo();
- // Re-check after the async gap — cancelWifiWait or a prior tick may have already fired.
- if (!waitingForWifi()) return;
- if (['wifi', 'ethernet'].includes(info.networkType ?? '')) {
- setWaitingForWifi(false);
- console.info('[bundle-update] wifi detected, approving download');
- grantBundleUpdate();
- }
- } catch {
- // Ignore — will retry on next tick.
- }
- }
-
- const intervalId = setInterval(() => void tryGrant(), 30_000);
- const onVisibilityChange = () => {
- if (!document.hidden) void tryGrant();
- };
- document.addEventListener('visibilitychange', onVisibilityChange);
-
- onCleanup(() => {
- clearInterval(intervalId);
- document.removeEventListener('visibilitychange', onVisibilityChange);
- });
- });
-
onMount(() => {
console.info('[bundle-update] registering listener');
let loggedDownloading = false;
@@ -162,12 +80,12 @@ function TauriProvider(props: { children: JSX.Element }) {
console.info('[bundle-update] received', JSON.stringify(ev.payload));
loggedDownloading = false;
}
- batch(() => {
- setBundleUpdateStatus(ev.payload);
- if (ev.payload.status !== 'WaitingForWifi') setWaitingForWifi(false);
- });
+ setBundleUpdateStatus(ev.payload);
}
);
+ invoke<boolean>('ack_bundle_update_reload').catch((e) =>
+ console.error('[bundle-update] ack_bundle_update_reload failed', e)
+ );
// Fetch current status since events emitted before the listener registered are missed
invoke<BundleUpdateStatus>('get_bundle_update_status').then((status) => {
console.info('[bundle-update] initial status', JSON.stringify(status));
@@ -202,6 +120,25 @@ function TauriProvider(props: { children: JSX.Element }) {
document.body.classList.add('tauri');
document.body.classList.add(`tauri-${value.os}`);
+
+ const onBundleUpdateVisibilityChange = () => {
+ // iOS gives us a short JS execution window after the app is backgrounded.
+ // Use it to ask Rust to apply a completed bundle before suspension;
+ // native Ready/Resumed handlers cover cases where this window is missed.
+ if (document.hidden) {
+ performBundleUpdate();
+ }
+ };
+ document.addEventListener(
+ 'visibilitychange',
+ onBundleUpdateVisibilityChange
+ );
+ onCleanup(() => {
+ document.removeEventListener(
+ 'visibilitychange',
+ onBundleUpdateVisibilityChange
+ );
+ });
});
return (
diff --git a/js/app/tauri/Cargo.lock b/js/app/tauri/Cargo.lock
index a71ba13f9a..0fbcd05208 100644
--- a/js/app/tauri/Cargo.lock
+++ b/js/app/tauri/Cargo.lock
@@ -2805,6 +2805,7 @@ dependencies = [
"sha2",
"strum",
"tauri",
+ "tauri-plugin-device-info",
"thiserror 2.0.18",
"tokio",
"tracing",
diff --git a/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml b/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml
index 23b17ede1e..404d71efde 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml
+++ b/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml
@@ -14,8 +14,12 @@ serde = { workspace = true, features = ["derive"] }
serde_json = "1"
strum = { version = "0.27", features = ["derive"] }
tauri = { workspace = true }
+tauri-plugin-device-info = "1.0.1"
thiserror = { workspace = true }
-tokio = { workspace = true, features = ["fs", "sync"] }
+tokio = { workspace = true, features = ["fs", "sync", "time"] }
tracing = { workspace = true }
url = { workspace = true }
zip = "6"
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt"] }
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 5e3e8d0832..4762209070 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
@@ -331,19 +331,6 @@ pub enum UpdateError {
#[derive(Debug, Clone, Default)]
pub struct UpdateGranted(());
-/// denotes that an update was denied
-#[derive(Debug, Clone, Copy, Default)]
-pub struct 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 {
@@ -389,6 +376,8 @@ pub enum UpdateStatus {
CheckingForDownload(AppInfo),
/// An update is available and awaiting approval.
UpdateFound(UpdateFoundStatus),
+ /// An update is available, but download is deferred until Wi-Fi or Ethernet is available.
+ WaitingForWifi(UpdateFoundStatus),
/// The app is already on the latest version.
NoUpdateNeeded,
/// The bundle zip is being downloaded.
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 f1dca65266..a2469a5c5c 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
@@ -2,7 +2,7 @@ use rootcause::Report;
use crate::domain::models::{
AppInfo, BundleUpdate, DownloadBundleError, DownloadBundleRequest, UnzipError, UnzipRequest,
- UpdateApproval, UpdateError, UpdateStatus,
+ UpdateError, UpdateStatus,
};
use std::path::{Path, PathBuf};
@@ -78,6 +78,10 @@ pub trait FsRepo: Clone + Send + Sync + 'static {
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 current network type, such as `wifi`, `ethernet`, or `cellular`.
+ fn get_network_type(
+ &self,
+ ) -> impl Future<Output = Result<Option<String>, 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;
}
@@ -87,11 +91,10 @@ 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(
- &mut self,
- ) -> Result<tokio::sync::oneshot::Sender<UpdateApproval>, Report>;
+ /// Approve or deny a pending update that has not started downloading.
+ fn approve_pending_update(&self, approved: bool) -> Result<(), Report>;
+ /// Resume the worker if it is waiting for a Wi-Fi or Ethernet connection.
+ fn retry_waiting_for_wifi(&self) -> Result<bool, Report>;
/// Signal the worker to start the checker loop from Idle.
fn start(&self) -> Result<(), Report>;
}
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 38b47cbc83..383ce7ce22 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,42 +1,60 @@
use crate::domain::{
models::{
- BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus, UpdateApproval,
- UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
+ BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus,
+ UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateGranted, UpdateStatus,
},
ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},
};
use rootcause::{Report, prelude::ResultExt, report};
-use std::path::{Path, PathBuf};
+use std::{
+ path::{Path, PathBuf},
+ time::{Duration, Instant},
+};
+use tokio::sync::mpsc::error::TrySendError;
+
+const RELOAD_DISPATCH_RETRY_DELAY: Duration = Duration::from_secs(5);
/// Manages the update worker and the active bundle root.
pub struct Service<Fs: FsRepo> {
handle: WorkerHandle,
fs_repo: Fs,
bundle_root: BundleRoot,
+ reload_pending: bool,
+ reload_dispatched_at: Option<Instant>,
}
-/// Sender half the worker uses to offer a oneshot back to the main thread.
-type GrantOfferTx = tokio::sync::mpsc::Sender<tokio::sync::oneshot::Sender<UpdateApproval>>;
-/// Receiver half the main thread uses to obtain the oneshot sender.
-type GrantOfferRx = tokio::sync::mpsc::Receiver<tokio::sync::oneshot::Sender<UpdateApproval>>;
+enum WorkerCommand {
+ Restart,
+ Continue,
+}
+
+/// Result of attempting to apply a completed bundle update.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ApplyUpdateResult {
+ /// There is no completed update to apply.
+ NoUpdate,
+ /// The bundle root was applied, or remains applied, and a reload should be dispatched.
+ ReloadNeeded,
+ /// The bundle root was already applied and a reload has already been dispatched.
+ ReloadAlreadyDispatched,
+}
/// Main thread sends on this to start the checker loop.
-type StartTx = tokio::sync::mpsc::Sender<()>;
+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<()>;
+type StartRx = tokio::sync::mpsc::Receiver<WorkerCommand>;
struct Worker<U, Fs, Q> {
update_repo: U,
fs_repo: Fs,
system_query: Q,
status_tx: tokio::sync::watch::Sender<Result<UpdateStatus, Report<UpdateError>>>,
- grant_offer_tx: GrantOfferTx,
start_rx: StartRx,
}
struct WorkerHandle {
status_rx: tokio::sync::watch::Receiver<Result<UpdateStatus, Report<UpdateError>>>,
- grant_offer_rx: GrantOfferRx,
+ status_tx: tokio::sync::watch::Sender<Result<UpdateStatus, Report<UpdateError>>>,
start_tx: StartTx,
}
@@ -46,22 +64,20 @@ const ENTRYPOINT_NAME: &str = "index.html";
impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
fn new_handle(update_repo: U, fs_repo: Fs, system_query: Q) -> WorkerHandle {
let (status_tx, status_rx) = tokio::sync::watch::channel(Ok(UpdateStatus::Idle));
- let (grant_offer_tx, grant_offer_rx) = tokio::sync::mpsc::channel(1);
let (start_tx, start_rx) = tokio::sync::mpsc::channel(1);
Worker {
update_repo,
fs_repo,
system_query,
- status_tx,
- grant_offer_tx,
+ status_tx: status_tx.clone(),
start_rx,
}
.run_background();
WorkerHandle {
status_rx,
- grant_offer_rx,
+ status_tx,
start_tx,
}
}
@@ -70,10 +86,12 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
tauri::async_runtime::spawn(async move {
// Run the checker loop once on startup, then again each time we
// receive a restart signal from the main thread.
- while let Some(()) = self.start_rx.recv().await {
- // Reset status to Idle for the new run
- if self.status_tx.send(Ok(UpdateStatus::Idle)).is_err() {
- break;
+ while let Some(command) = self.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() {
+ break;
+ }
}
self.run_check_loop().await;
@@ -91,10 +109,20 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
}
let next = self.next_status(status).await;
+ let should_stop = matches!(
+ &next,
+ Ok(UpdateStatus::NoUpdateNeeded)
+ | Ok(UpdateStatus::WaitingForWifi(_))
+ | Ok(UpdateStatus::Completed(_))
+ | Err(_)
+ );
let Ok(()) = self.status_tx.send(next) else {
break;
};
+ if should_stop {
+ break;
+ }
}
}
@@ -138,25 +166,29 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
}
}
UpdateStatus::UpdateFound(update_found_status) => {
- let (tx, rx) = tokio::sync::oneshot::channel();
- // Send the oneshot sender to the main thread so it can respond
- self.grant_offer_tx.send(tx).await.map_err(|_| {
- report!("Grant offer receiver was dropped").context(UpdateError::GrantErr)
- })?;
- // Wait for the main thread to send approval back
- let res = rx.await.map_err(|e| {
- rootcause::report!("Failed to receive grant {e:?}. The sender was dropped")
- .context(UpdateError::GrantErr)
- })?;
- match res {
- UpdateApproval::Granted(grant) => {
- Ok(UpdateStatus::DownloadingBundle(UpdateDownloadingStatus {
- grant,
- update: update_found_status.bundle,
- progress: ProgressPercentage::default(),
- }))
+ match self.should_download_now().await {
+ Ok(true) => Ok(start_download(update_found_status)),
+ Ok(false) => Ok(UpdateStatus::WaitingForWifi(update_found_status)),
+ Err(e) => {
+ tracing::warn!(
+ error = %e,
+ "Network check failed; waiting for Wi-Fi"
+ );
+ Ok(UpdateStatus::WaitingForWifi(update_found_status))
+ }
+ }
+ }
+ UpdateStatus::WaitingForWifi(update_found_status) => {
+ match self.should_download_now().await {
+ Ok(true) => Ok(start_download(update_found_status)),
+ Ok(false) => Ok(UpdateStatus::WaitingForWifi(update_found_status)),
+ Err(e) => {
+ tracing::warn!(
+ error = %e,
+ "Network check failed while waiting for Wi-Fi"
+ );
+ Ok(UpdateStatus::WaitingForWifi(update_found_status))
}
- UpdateApproval::Denied(_update_denied) => Ok(UpdateStatus::NoUpdateNeeded),
}
}
UpdateStatus::NoUpdateNeeded => Ok(UpdateStatus::NoUpdateNeeded),
@@ -225,6 +257,18 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
}
}
+ async fn should_download_now(&self) -> Result<bool, Report> {
+ let network_type = self.system_query.get_network_type().await?;
+ tracing::info!(
+ network_type = network_type.as_deref().unwrap_or("unknown"),
+ "Bundle update network check"
+ );
+ Ok(matches!(
+ network_type.as_deref(),
+ Some("wifi") | Some("ethernet")
+ ))
+ }
+
/// Create a monotonically increasing download directory and return the
/// path where the zip should be placed.
async fn create_download_directory(
@@ -239,6 +283,14 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
}
}
+fn start_download(update_found_status: UpdateFoundStatus) -> UpdateStatus {
+ UpdateStatus::DownloadingBundle(UpdateDownloadingStatus {
+ grant: UpdateGranted::default(),
+ update: update_found_status.bundle,
+ progress: ProgressPercentage::default(),
+ })
+}
+
/// Determine the next monotonic bundle index from a list of directory names.
pub(crate) fn next_bundle_index(names: &[String]) -> u64 {
names
@@ -318,6 +370,8 @@ impl<Fs: FsRepo> Service<Fs> {
handle,
fs_repo,
bundle_root: BundleRoot::new(),
+ reload_pending: false,
+ reload_dispatched_at: None,
}
}
@@ -331,25 +385,28 @@ impl<Fs: FsRepo> Service<Fs> {
self.bundle_root.path()
}
- /// Apply the update by modifying the bundle root and resetting the worker thread to the initial state.
+ /// Apply the update by modifying the bundle root.
///
- /// Returns `Ok(false)` when there is no pending update or another caller
- /// is already applying one.
- pub async fn apply_update(&mut self, cache_dir: &Path) -> Result<bool, Report> {
+ /// Returns `Ok(ReloadNeeded)` when a webview reload should be dispatched.
+ /// 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 {
+ return Ok(if self.reload_dispatched_at.is_some() {
+ ApplyUpdateResult::ReloadAlreadyDispatched
+ } else {
+ ApplyUpdateResult::ReloadNeeded
+ });
+ }
+
let entrypoint = {
let status = self.status().borrow();
match status.as_ref() {
Ok(UpdateStatus::Completed(bundle_location)) => bundle_location.entrypoint.clone(),
- _ => return Ok(false),
+ _ => return Ok(ApplyUpdateResult::NoUpdate),
}
};
- // Claim the worker restart slot before doing any work. If the channel
- // is full another apply_update is already in flight — short-circuit.
- if self.start().is_err() {
- return Ok(false);
- }
-
let bundle_dir = entrypoint
.parent()
.ok_or_else(|| report!("entrypoint {entrypoint:?} has no parent directory"))?
@@ -357,10 +414,61 @@ impl<Fs: FsRepo> Service<Fs> {
tracing::info!("Setting bundle root to {bundle_dir:?}");
self.set_bundle_root(bundle_dir.clone(), cache_dir).await?;
+ self.reload_pending = true;
+ 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 {
+ 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() {
+ return false;
+ }
+
+ self.reload_dispatched_at = None;
+ true
+ }
+
+ /// 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() {
+ return false;
+ }
+
+ if self
+ .reload_dispatched_at
+ .is_some_and(|dispatched_at| dispatched_at.elapsed() < RELOAD_DISPATCH_RETRY_DELAY)
+ {
+ return false;
+ }
+
+ self.reload_dispatched_at = None;
+ true
+ }
+
+ /// Acknowledge that the webview has reloaded after applying an update.
+ ///
+ /// 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 {
+ return Ok(false);
+ }
+
+ self.restart_run_after_reload_ack()?;
+ self.reload_pending = false;
+ self.reload_dispatched_at = None;
Ok(true)
}
@@ -417,20 +525,525 @@ impl<Fs: FsRepo> AutoUpdateService for Service<Fs> {
&self.handle.status_rx
}
- fn try_recv_grant_sender(
- &mut self,
- ) -> Result<tokio::sync::oneshot::Sender<UpdateApproval>, Report> {
- self.handle
- .grant_offer_rx
- .try_recv()
- .map_err(|e| report!("No pending grant offer: {e}"))
+ fn approve_pending_update(&self, approved: bool) -> Result<(), Report> {
+ let mut updated = false;
+ self.handle.status_tx.send_if_modified(|cur| {
+ let Ok(status) = cur else {
+ return false;
+ };
+ let pending = match status {
+ UpdateStatus::UpdateFound(found) | UpdateStatus::WaitingForWifi(found) => {
+ Some(found.clone())
+ }
+ _ => None,
+ };
+ let Some(found) = pending else {
+ return false;
+ };
+
+ *status = if approved {
+ start_download(found)
+ } else {
+ UpdateStatus::NoUpdateNeeded
+ };
+ updated = true;
+ true
+ });
+
+ if !updated {
+ return Err(report!("No pending bundle update to approve"));
+ }
+
+ if approved {
+ self.continue_run()?;
+ }
+ Ok(())
+ }
+
+ fn retry_waiting_for_wifi(&self) -> Result<bool, Report> {
+ let waiting = matches!(
+ &*self.handle.status_rx.borrow(),
+ Ok(UpdateStatus::WaitingForWifi(_))
+ );
+ if waiting {
+ self.continue_run()?;
+ }
+ Ok(waiting)
}
#[tracing::instrument(err, skip(self))]
fn start(&self) -> Result<(), Report> {
self.handle
.start_tx
- .try_send(())
+ .try_send(WorkerCommand::Restart)
.map_err(|e| report!("Failed to send start signal: {e}"))
}
}
+
+impl<Fs: FsRepo> Service<Fs> {
+ fn continue_run(&self) -> Result<(), Report> {
+ match self.handle.start_tx.try_send(WorkerCommand::Continue) {
+ Ok(()) | Err(TrySendError::Full(_)) => Ok(()),
+ Err(e) => Err(report!("Failed to send continue signal: {e}")),
+ }
+ }
+
+ fn restart_run_after_reload_ack(&self) -> Result<(), Report> {
+ self.handle
+ .status_tx
+ .send(Ok(UpdateStatus::Idle))
+ .map_err(|e| report!("Failed to reset bundle update status: {e}"))?;
+ self.continue_run()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::domain::{
+ models::{
+ AppInfo, Arch, BundleUpdate, DownloadBundleError, DownloadBundleRequest, Target,
+ UnzipError,
+ },
+ ports::AutoUpdateService,
+ };
+ use std::{
+ future::pending,
+ sync::{Arc, Mutex as StdMutex},
+ time::Duration,
+ };
+
+ #[derive(Clone)]
+ struct FakeUpdateRepo {
+ update: Option<BundleUpdate>,
+ block_download: bool,
+ }
+
+ impl UpdateRepo for FakeUpdateRepo {
+ async fn check_for_update(
+ &self,
+ _request: AppInfo,
+ ) -> Result<Option<BundleUpdate>, rootcause::Report> {
+ Ok(self.update.clone())
+ }
+
+ async fn get_update_bundle<P: AsRef<Path> + Send>(
+ &self,
+ _request: DownloadBundleRequest<P>,
+ ) -> Result<(), Report<DownloadBundleError>> {
+ if self.block_download {
+ pending::<()>().await;
+ }
+ Ok(())
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeFs;
+
+ impl FsRepo for FakeFs {
+ async fn verify_checksum<P: AsRef<Path> + Send>(
+ &self,
+ _path: P,
+ _expected: &str,
+ ) -> Result<(), UnzipError> {
+ Ok(())
+ }
+
+ async fn unzip(&self, request: UnzipRequest) -> Result<PathBuf, UnzipError> {
+ Ok(request.archive_target)
+ }
+
+ async fn create_dir_all<P: AsRef<Path> + Send>(
+ &self,
+ _path: P,
+ ) -> Result<(), std::io::Error> {
+ Ok(())
+ }
+
+ async fn list_dir_names(&self, _dir: &Path) -> Vec<String> {
+ Vec::new()
+ }
+
+ async fn remove_dir_all(&self, _dir: &Path) -> Result<(), std::io::Error> {
+ Ok(())
+ }
+
+ async fn read_to_string(&self, _path: &Path) -> Result<String, std::io::Error> {
+ Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"))
+ }
+
+ async fn write(&self, _path: &Path, _contents: &[u8]) -> Result<(), std::io::Error> {
+ Ok(())
+ }
+
+ async fn remove_file(&self, _path: &Path) -> Result<(), std::io::Error> {
+ Ok(())
+ }
+ }
+
+ #[derive(Clone)]
+ struct FakeSystemQuery {
+ network_type: Arc<StdMutex<Option<String>>>,
+ network_type_error: Arc<StdMutex<bool>>,
+ update_dir: PathBuf,
+ }
+
+ impl FakeSystemQuery {
+ fn new(network_type: &str) -> Self {
+ Self {
+ network_type: Arc::new(StdMutex::new(Some(network_type.to_string()))),
+ network_type_error: Arc::new(StdMutex::new(false)),
+ update_dir: std::env::temp_dir().join("macro_bundle_updater_plugin_tests"),
+ }
+ }
+
+ fn set_network_type(&self, network_type: &str) {
+ *self.network_type.lock().unwrap() = Some(network_type.to_string());
+ }
+
+ fn set_network_type_error(&self, should_error: bool) {
+ *self.network_type_error.lock().unwrap() = should_error;
+ }
+ }
+
+ impl SystemQuery for FakeSystemQuery {
+ async fn get_system_info(&self) -> Result<AppInfo, rootcause::Report> {
+ Ok(AppInfo {
+ current_version: semver::Version::new(0, 0, 0),
+ arch: Arch::Aarch64,
+ target: Target::Ios,
+ })
+ }
+
+ async fn get_network_type(&self) -> Result<Option<String>, rootcause::Report> {
+ if *self.network_type_error.lock().unwrap() {
+ return Err(report!("network info unavailable"));
+ }
+ Ok(self.network_type.lock().unwrap().clone())
+ }
+
+ async fn get_update_dir(&self) -> Result<PathBuf, std::io::Error> {
+ Ok(self.update_dir.clone())
+ }
+ }
+
+ fn bundle_update() -> BundleUpdate {
+ BundleUpdate {
+ version: semver::Version::new(1, 2, 3),
+ notes: None,
+ url: "https://example.com/bundle.zip".parse().unwrap(),
+ checksum: "checksum".to_string(),
+ }
+ }
+
+ fn service_with_network(network_type: &str) -> (Service<FakeFs>, FakeSystemQuery) {
+ let system_query = FakeSystemQuery::new(network_type);
+ let service = Service::new(
+ FakeUpdateRepo {
+ update: Some(bundle_update()),
+ block_download: true,
+ },
+ FakeFs,
+ system_query.clone(),
+ );
+ (service, system_query)
+ }
+
+ fn service_with_status(status: UpdateStatus) -> (Service<FakeFs>, StartRx) {
+ let (status_tx, status_rx) = tokio::sync::watch::channel(Ok(status));
+ let (start_tx, start_rx) = tokio::sync::mpsc::channel(1);
+ (
+ Service {
+ handle: WorkerHandle {
+ status_rx,
+ status_tx,
+ start_tx,
+ },
+ fs_repo: FakeFs,
+ bundle_root: BundleRoot::new(),
+ reload_pending: false,
+ reload_dispatched_at: None,
+ },
+ start_rx,
+ )
+ }
+
+ fn completed_status() -> UpdateStatus {
+ UpdateStatus::Completed(CompletedStatus {
+ entrypoint: PathBuf::from("/tmp/macro-bundle-test/1/index.html"),
+ })
+ }
+
+ async fn wait_for_status(
+ service: &Service<FakeFs>,
+ mut predicate: impl FnMut(&UpdateStatus) -> bool,
+ ) -> UpdateStatus {
+ let mut rx = service.status().clone();
+ tokio::time::timeout(Duration::from_secs(1), async move {
+ loop {
+ {
+ let borrowed = rx.borrow();
+ if let Ok(status) = &*borrowed
+ && predicate(status)
+ {
+ return status.clone();
+ }
+ }
+ rx.changed().await.expect("status sender dropped");
+ }
+ })
+ .await
+ .expect("timed out waiting for status")
+ }
+
+ #[tokio::test]
+ async fn update_found_on_wifi_advances_to_downloading() {
+ let (service, _system_query) = service_with_network("wifi");
+
+ service.start().unwrap();
+
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::DownloadingBundle(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::DownloadingBundle(_)));
+ }
+
+ #[tokio::test]
+ async fn update_found_on_ethernet_advances_to_downloading() {
+ let (service, _system_query) = service_with_network("ethernet");
+
+ service.start().unwrap();
+
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::DownloadingBundle(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::DownloadingBundle(_)));
+ }
+
+ #[tokio::test]
+ async fn update_found_on_cellular_waits_for_wifi() {
+ let (service, _system_query) = service_with_network("cellular");
+
+ service.start().unwrap();
+
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::WaitingForWifi(_)));
+ }
+
+ #[tokio::test]
+ async fn retry_waiting_for_wifi_stays_waiting_on_cellular() {
+ let (service, _system_query) = service_with_network("cellular");
+
+ service.start().unwrap();
+ wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+
+ assert!(service.retry_waiting_for_wifi().unwrap());
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::WaitingForWifi(_)));
+ }
+
+ #[tokio::test]
+ async fn retry_waiting_for_wifi_advances_when_wifi_becomes_available() {
+ let (service, system_query) = service_with_network("cellular");
+
+ service.start().unwrap();
+ wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+
+ system_query.set_network_type("wifi");
+ assert!(service.retry_waiting_for_wifi().unwrap());
+
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::DownloadingBundle(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::DownloadingBundle(_)));
+ }
+
+ #[tokio::test]
+ async fn retry_waiting_for_wifi_stays_waiting_when_network_check_fails() {
+ let (service, system_query) = service_with_network("cellular");
+
+ service.start().unwrap();
+ wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+
+ system_query.set_network_type_error(true);
+ assert!(service.retry_waiting_for_wifi().unwrap());
+
+ let status = wait_for_status(&service, |status| {
+ matches!(status, UpdateStatus::WaitingForWifi(_))
+ })
+ .await;
+ assert!(matches!(status, UpdateStatus::WaitingForWifi(_)));
+ }
+
+ #[tokio::test]
+ async fn duplicate_retry_nudge_is_benign_when_command_already_queued() {
+ let (status_tx, status_rx) =
+ tokio::sync::watch::channel(Ok(UpdateStatus::WaitingForWifi(UpdateFoundStatus {
+ bundle: bundle_update(),
+ })));
+ let (start_tx, _start_rx) = tokio::sync::mpsc::channel(1);
+ start_tx.try_send(WorkerCommand::Continue).unwrap();
+ let service = Service {
+ handle: WorkerHandle {
+ status_rx,
+ status_tx,
+ start_tx,
+ },
+ fs_repo: FakeFs,
+ bundle_root: BundleRoot::new(),
+ reload_pending: false,
+ reload_dispatched_at: None,
+ };
+
+ assert!(service.retry_waiting_for_wifi().unwrap());
+ }
+
+ #[tokio::test]
+ async fn apply_update_returns_no_update_when_status_is_not_completed() {
+ let (mut service, _system_query) = service_with_network("wifi");
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+
+ assert_eq!(applied, ApplyUpdateResult::NoUpdate);
+ }
+
+ #[tokio::test]
+ async fn apply_update_keeps_worker_completed_until_reload_ack() {
+ let (mut service, mut start_rx) = service_with_status(completed_status());
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+
+ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);
+ assert!(service.reload_pending);
+ assert!(service.reload_dispatched_at.is_none());
+ assert!(matches!(
+ &*service.status().borrow(),
+ Ok(UpdateStatus::Completed(_))
+ ));
+ assert!(start_rx.try_recv().is_err());
+
+ assert!(service.acknowledge_update_reload().unwrap());
+ assert!(!service.reload_pending);
+ assert!(service.reload_dispatched_at.is_none());
+ assert!(matches!(
+ &*service.status().borrow(),
+ Ok(UpdateStatus::Idle)
+ ));
+ assert!(matches!(
+ start_rx.try_recv().unwrap(),
+ WorkerCommand::Continue
+ ));
+ }
+
+ #[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;
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+
+ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);
+ }
+
+ #[tokio::test]
+ async fn apply_update_does_not_request_second_reload_after_dispatch() {
+ let (mut service, _start_rx) = service_with_status(completed_status());
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);
+
+ service.mark_update_reload_dispatched();
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+ assert_eq!(applied, ApplyUpdateResult::ReloadAlreadyDispatched);
+ }
+
+ #[tokio::test]
+ async fn allow_update_reload_retry_waits_for_stale_dispatch() {
+ let (mut service, _start_rx) = service_with_status(completed_status());
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);
+
+ service.mark_update_reload_dispatched();
+ assert_eq!(
+ service.apply_update(Path::new("/tmp")).await.unwrap(),
+ ApplyUpdateResult::ReloadAlreadyDispatched
+ );
+
+ assert!(!service.allow_update_reload_retry());
+ service.reload_dispatched_at = Some(Instant::now() - RELOAD_DISPATCH_RETRY_DELAY);
+
+ assert!(service.allow_update_reload_retry());
+ assert!(service.reload_dispatched_at.is_none());
+ assert_eq!(
+ service.apply_update(Path::new("/tmp")).await.unwrap(),
+ ApplyUpdateResult::ReloadNeeded
+ );
+ }
+
+ #[tokio::test]
+ async fn unmark_update_reload_dispatched_bypasses_stale_retry_gate() {
+ let (mut service, _start_rx) = service_with_status(completed_status());
+
+ let applied = service.apply_update(Path::new("/tmp")).await.unwrap();
+ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);
+
+ service.mark_update_reload_dispatched();
+ assert_eq!(
+ service.apply_update(Path::new("/tmp")).await.unwrap(),
+ ApplyUpdateResult::ReloadAlreadyDispatched
+ );
+
+ assert!(service.unmark_update_reload_dispatched());
+ assert_eq!(
+ service.apply_update(Path::new("/tmp")).await.unwrap(),
+ ApplyUpdateResult::ReloadNeeded
+ );
+ }
+
+ #[test]
+ 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());
+ }
+
+ #[test]
+ 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
+ .handle
+ .start_tx
+ .try_send(WorkerCommand::Continue)
+ .unwrap();
+
+ assert!(service.acknowledge_update_reload().unwrap());
+ assert!(!service.reload_pending);
+ assert!(service.reload_dispatched_at.is_none());
+ assert!(matches!(
+ &*service.status().borrow(),
+ Ok(UpdateStatus::Idle)
+ ));
+ }
+}
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 5f4bf8bd16..5862fdc365 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
@@ -2,14 +2,15 @@ use tokio::sync::Mutex;
use rootcause::Report;
use serde::Serialize;
+use std::time::Duration;
use tauri::{Emitter, Manager, Runtime, plugin::Plugin};
use url::Url;
use crate::{
domain::{
- models::{UpdateApproval, UpdateDenied, UpdateError, UpdateGranted, UpdateStatus},
+ models::{UpdateError, UpdateStatus},
ports::AutoUpdateService,
- service::Service,
+ service::{ApplyUpdateResult, Service},
},
outbound::{api_client::BundleClient, fs::FileSystem, system_info::SystemInfo},
};
@@ -18,6 +19,7 @@ use crate::{
pub type PluginService = Service<FileSystem>;
const EVENT_NAME: &str = "bundle-update-status";
+const WIFI_RETRY_INTERVAL: Duration = Duration::from_secs(30);
/// Serializable event emitted to the frontend via Tauri's event system.
#[derive(Clone, Serialize)]
@@ -34,6 +36,8 @@ pub enum BundleUpdateEvent {
/// Optional release notes.
notes: Option<String>,
},
+ /// An update is available, but download is deferred until Wi-Fi or Ethernet is available.
+ WaitingForWifi,
/// Already on the latest version.
NoUpdateNeeded,
/// Bundle download in progress.
@@ -64,6 +68,7 @@ impl BundleUpdateEvent {
version: found.bundle.version.to_string(),
notes: found.bundle.notes.clone(),
},
+ Ok(UpdateStatus::WaitingForWifi(_found)) => BundleUpdateEvent::WaitingForWifi,
Ok(UpdateStatus::NoUpdateNeeded) => BundleUpdateEvent::NoUpdateNeeded,
Ok(UpdateStatus::DownloadingBundle(dl)) => BundleUpdateEvent::Downloading {
progress: dl.progress.value(),
@@ -97,16 +102,34 @@ pub async fn grant_bundle_update(
service: tauri::State<'_, Mutex<PluginService>>,
approved: bool,
) -> Result<(), String> {
- 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::default())
- } else {
- UpdateApproval::Denied(UpdateDenied::default())
+ let service = service.lock().await;
+ service
+ .approve_pending_update(approved)
+ .map_err(|e| e.to_string())
+}
+
+/// Retry a bundle update that is waiting for Wi-Fi or Ethernet.
+pub async fn retry_waiting_for_wifi<R: Runtime>(
+ app_handle: &tauri::AppHandle<R>,
+) -> Result<bool, String> {
+ let Some(service_state) = app_handle.try_state::<Mutex<PluginService>>() else {
+ return Ok(false);
};
- grant_tx
- .send(approval)
- .map_err(|_| "Worker dropped the grant receiver".to_string())
+
+ let service = service_state.lock().await;
+ service.retry_waiting_for_wifi().map_err(|e| e.to_string())
+}
+
+/// Allow a pending bundle update reload to be dispatched again.
+pub async fn allow_update_reload_retry<R: Runtime>(
+ app_handle: &tauri::AppHandle<R>,
+) -> Result<bool, String> {
+ let Some(service_state) = app_handle.try_state::<Mutex<PluginService>>() else {
+ return Ok(false);
+ };
+
+ let mut service = service_state.lock().await;
+ Ok(service.allow_update_reload_retry())
}
/// Apply a completed bundle update to the live webview.
@@ -125,34 +148,63 @@ pub async fn apply_completed_update<R: Runtime>(
.app_cache_dir()
.map_err(|e| e.to_string())?;
- let mut service = service_state.lock().await;
-
- let applied = service
- .apply_update(&cache_dir)
- .await
- .map_err(|e| e.to_string())?;
-
- drop(service);
+ let apply_result = {
+ let mut service = service_state.lock().await;
+ let result = service
+ .apply_update(&cache_dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ if result == ApplyUpdateResult::ReloadNeeded {
+ service.mark_update_reload_dispatched();
+ }
+ result
+ };
- if applied {
+ if apply_result == ApplyUpdateResult::ReloadNeeded {
// 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, reloading to pick up new assets");
- let _ = webview.eval("window.location.reload();");
+ if let Err(e) = webview.eval("window.location.reload();") {
+ tracing::warn!(error=?e, "Failed to dispatch bundle update reload");
+ service_state
+ .lock()
+ .await
+ .unmark_update_reload_dispatched();
+ }
+ } else {
+ tracing::warn!(
+ "Completed bundle update applied but no webview was available to reload"
+ );
+ service_state
+ .lock()
+ .await
+ .unmark_update_reload_dispatched();
}
}
- Ok(applied)
+ Ok(apply_result != ApplyUpdateResult::NoUpdate)
}
/// Apply a completed bundle update: set the bundle root and navigate to it.
+///
+/// Returns `true` if a completed update was applied, or `false` when there is
+/// no completed update pending.
#[tauri::command]
#[tracing::instrument(err, skip(app_handle))]
-pub async fn perform_update<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {
- match apply_completed_update(&app_handle).await? {
- true => Ok(()),
- false => Err("No pending update".into()),
- }
+pub async fn perform_update<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<bool, String> {
+ apply_completed_update(&app_handle).await
+}
+
+/// Acknowledge that the webview mounted after an applied bundle update reload.
+#[tauri::command]
+pub async fn ack_bundle_update_reload(
+ service: tauri::State<'_, Mutex<PluginService>>,
+) -> Result<bool, String> {
+ service
+ .lock()
+ .await
+ .acknowledge_update_reload()
+ .map_err(|e| e.to_string())
}
/// Trigger a manual check for bundle updates.
@@ -215,6 +267,7 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
let service = Service::new(client, fs, system_info);
let mut status_rx = service.status().clone();
+ let mut wifi_retry_status_rx = service.status().clone();
let _ = service.start();
app.manage(tokio::sync::Mutex::new(service));
@@ -236,6 +289,40 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
}
});
+ let app_handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ if !matches!(
+ &*wifi_retry_status_rx.borrow(),
+ Ok(UpdateStatus::WaitingForWifi(_))
+ ) {
+ if wifi_retry_status_rx.changed().await.is_err() {
+ return;
+ }
+ continue;
+ }
+
+ tokio::select! {
+ _ = tokio::time::sleep(WIFI_RETRY_INTERVAL) => {
+ match retry_waiting_for_wifi(&app_handle).await {
+ Ok(true) => tracing::info!(
+ "[bundle-update] retrying bundle download after Wi-Fi wait"
+ ),
+ Ok(false) => {}
+ Err(e) => tracing::warn!(
+ "[bundle-update] failed to retry bundle download after Wi-Fi wait: {e}"
+ ),
+ }
+ }
+ changed = wifi_retry_status_rx.changed() => {
+ if changed.is_err() {
+ return;
+ }
+ }
+ }
+ }
+ });
+
Ok(())
}
}
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 d35262f47e..95c0a27e36 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
@@ -1,5 +1,6 @@
use semver::Version;
use tauri::{Manager, Runtime};
+use tauri_plugin_device_info::DeviceInfoExt;
use crate::domain::{
models::{AppInfo, Arch, Target},
@@ -63,6 +64,15 @@ impl<R: Runtime> SystemQuery for SystemInfo<R> {
})
}
+ async fn get_network_type(&self) -> Result<Option<String>, rootcause::Report> {
+ let network_info = self
+ .app_handle
+ .device_info()
+ .get_network_info()
+ .map_err(|e| rootcause::report!("Failed to read network info: {e}"))?;
+ Ok(network_info.network_type)
+ }
+
async fn get_update_dir(&self) -> Result<std::path::PathBuf, std::io::Error> {
self.app_handle
.path()
diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rs
index e603e2158c..3b9bf844f7 100644
--- a/js/app/tauri/src-tauri/src/lib.rs
+++ b/js/app/tauri/src-tauri/src/lib.rs
@@ -1,5 +1,7 @@
use logger::Logger;
-use macro_bundle_updater_plugin::inbound::plugin::{PluginService, apply_completed_update};
+use macro_bundle_updater_plugin::inbound::plugin::{
+ PluginService, allow_update_reload_retry, apply_completed_update, retry_waiting_for_wifi,
+};
use navigation_plugin::MacroNavigationPlugin;
use navigation_plugin::scheme::MacroScheme;
use reqwest::cookie::CookieStore;
@@ -188,6 +190,7 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
macro_bundle_updater_plugin::inbound::plugin::grant_bundle_update,
macro_bundle_updater_plugin::inbound::plugin::perform_update,
+ macro_bundle_updater_plugin::inbound::plugin::ack_bundle_update_reload,
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::clear_bundle,
@@ -228,24 +231,47 @@ pub fn run() {
})
.build(tauri::generate_context!())
.expect("error while building tauri application")
- .run(|app_handle, event| {
- #[cfg(feature = "auto_apply_update")]
- {
- if let RunEvent::Resumed = event {
+ .run(move |app_handle, event| match &event {
+ RunEvent::Ready => {
+ #[cfg(feature = "auto_apply_update")]
+ {
let app = app_handle.clone();
tauri::async_runtime::spawn(async move {
match apply_completed_update(&app).await {
- Ok(true) => {
- tracing::info!("auto-applied pending bundle update on foreground");
+ Ok(_) => {}
+ Err(e) => {
+ tracing::error!("Failed to auto-apply bundle update on ready: {e}");
}
- Ok(false) => {}
+ }
+ });
+ }
+ }
+ RunEvent::Resumed => {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(e) = retry_waiting_for_wifi(&app).await {
+ tracing::warn!("Failed to retry bundle update Wi-Fi wait on resume: {e}");
+ }
+ });
+ #[cfg(feature = "auto_apply_update")]
+ {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(e) = allow_update_reload_retry(&app).await {
+ tracing::warn!(
+ "Failed to allow bundle update reload retry on resume: {e}"
+ );
+ }
+ match apply_completed_update(&app).await {
+ Ok(_) => {}
Err(e) => {
- tracing::error!("failed to auto-apply bundle update: {e}");
+ tracing::error!("Failed to auto-apply bundle update: {e}");
}
}
});
}
}
+ _ => {}
});
}