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.

feat(tauri): autoupdate ui and persistence (#2657)

Sean Aye718e9acc8604
diff --git a/js/app/bun.lock b/js/app/bun.lock
index a265db8541..7f76cdbc2a 100644
--- a/js/app/bun.lock
+++ b/js/app/bun.lock
@@ -662,7 +662,7 @@
"@ibm-cloud/openapi-ruleset-utilities": ["@ibm-cloud/[email protected]", "", {}, "sha512-AoFbSarOqFBYH+1TZ9Ahkm2IWYSi5v0pBk88fpV+5b3qGJukypX8PwvCWADjuyIccKg48/F73a6hTTkBzDQ2UA=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009"],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009", "sha512-XLN+niDA9BkzrxiZqBjYf+DL4TLoMIcI80ypCowacVfrfAjWt0qLwLkzWVUXjD7k3v0DB/G+BP4OLJNkGygHIw=="],
"@internationalized/date": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-jLxQjefH9VI5P9UQuqB6qNKnvFt1Ky1TPIzHGsIlCi7sZZoMR8SdYbBGRvM0y+Jtb+ez4ieBzmiAUcpmPYpyOw=="],
@@ -2350,7 +2350,7 @@
"pathval": ["[email protected]", "", {}, "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/js/app/flake.nix b/js/app/flake.nix
index e9492e6baf..e5d761245c 100644
--- a/js/app/flake.nix
+++ b/js/app/flake.nix
@@ -90,6 +90,7 @@
gst_all_1.gst-plugins-good
gst_all_1.gst-plugins-bad
jdk
+ xdg-utils
];
packages = basePackages ++ pkgs.lib.optionals isLinux (linuxPackages ++ [ android_sdk ]);
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index 75138409d1..af806b6aea 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -39,10 +39,25 @@ import {
useNotificationSettings,
} from '@notifications';
import { useAnalytics } from '@app/component/analytics-context';
+import { useTauri, type BundleUpdateStatus } from '@macro/tauri';
+import { invoke } from '@tauri-apps/api/core';
// NOTE: solid directives
false && fileSelector;
+function formatBundleUpdateStatus(status: BundleUpdateStatus): string {
+ switch (status.status) {
+ case 'Idle': return 'Idle';
+ case 'CheckingForUpdate': return 'Checking for update...';
+ case 'UpdateFound': return `Update available: v${status.data.version}`;
+ case 'NoUpdateNeeded': return 'Up to date';
+ case 'Downloading': return `Downloading: ${Math.round(status.data.progress)}%`;
+ case 'Unzipping': return `Installing: ${Math.round(status.data.progress)}%`;
+ case 'Completed': return 'Update ready';
+ case 'Error': return 'An error occurred when checking for updates';
+ }
+}
+
function useUserName() {
const fetchUserName = async () => {
const [_, response] = await authServiceClient.getUserName();
@@ -220,6 +235,7 @@ export function Account() {
/>
</Show>
</div>
+ <BundleUpdateRow />
<Show when={ENABLE_EMAIL && (!emailActive() || DEV_MODE_ENV)}>
<Show
when={!emailActive()}
@@ -435,3 +451,45 @@ function NotificationNotSupported() {
</div>
);
}
+
+function bundleUpdateAction(status: BundleUpdateStatus): { label: string; action: () => void } | null {
+ 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 }) };
+ case 'Completed':
+ return { label: 'Update', action: () => invoke('perform_update') };
+ default:
+ return null;
+ }
+}
+
+function BundleUpdateRow() {
+ const tauri = useTauri();
+ return (
+ <Show when={tauri}>
+ {(ctx) => {
+ const status = () => ctx().bundleUpdateStatus();
+ const action = () => bundleUpdateAction(status());
+ return (
+ <div class="flex items-center justify-between mb-[18px]">
+ <TabContentRow
+ text="App Update"
+ subtext={formatBundleUpdateStatus(status())}
+ />
+ <Show when={action()}>
+ {(a) => (
+ <Button variant="accent" size="sm" onClick={a().action}>
+ {a().label}
+ </Button>
+ )}
+ </Show>
+ </div>
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsx
index 2025108645..663ba8cf31 100644
--- a/js/app/packages/tauri/src/TauriProvider.tsx
+++ b/js/app/packages/tauri/src/TauriProvider.tsx
@@ -12,6 +12,7 @@ import {
useContext,
} from 'solid-js';
import { getInsets, type Insets } from 'tauri-plugin-safe-area-insets';
+import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { listenForHeartbeat } from './heartbeat';
import { useTauriNavigationEffect } from './navigation';
@@ -19,9 +20,20 @@ import { MaybePushNotificationRegistration } from './PushNotification';
type NotAndroid = 'not-android';
+export type BundleUpdateStatus =
+ | { status: 'Idle' }
+ | { status: 'CheckingForUpdate' }
+ | { status: 'UpdateFound'; data: { version: string; notes: string | null } }
+ | { status: 'NoUpdateNeeded' }
+ | { status: 'Downloading'; data: { progress: number } }
+ | { status: 'Unzipping'; data: { progress: number } }
+ | { status: 'Completed' }
+ | { status: 'Error'; data: { message: string } };
+
interface TauriContextValue {
os: OsType;
runtimeInsets: Accessor<Insets | NotAndroid>;
+ bundleUpdateStatus: Accessor<BundleUpdateStatus>;
}
const TauriContext = createContext<TauriContextValue | undefined>(undefined);
@@ -33,16 +45,29 @@ function TauriProvider(props: { children: JSX.Element }) {
const [insets, setInsets] = createSignal<NotAndroid | Insets>(
'not-android' as const
);
+ const [bundleUpdateStatus, setBundleUpdateStatus] =
+ createSignal<BundleUpdateStatus>({ status: 'Idle' });
const value: TauriContextValue = {
runtimeInsets: insets,
os: osType(),
+ bundleUpdateStatus,
};
onMount(() => {
listenForHeartbeat();
- const unlistenPromise = listen('bundle-update-status', (ev) => {
- console.info('[bundle-update]', ev.payload);
+ console.info('[bundle-update] registering listener');
+ const unlistenPromise = listen<BundleUpdateStatus>(
+ 'bundle-update-status',
+ (ev) => {
+ console.info('[bundle-update] received', JSON.stringify(ev.payload));
+ setBundleUpdateStatus(ev.payload);
+ }
+ );
+ // 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));
+ setBundleUpdateStatus(status);
});
onCleanup(() => {
unlistenPromise.then((unlisten) => unlisten());
diff --git a/js/app/packages/tauri/src/index.ts b/js/app/packages/tauri/src/index.ts
index 762ef03697..14400dbc5f 100644
--- a/js/app/packages/tauri/src/index.ts
+++ b/js/app/packages/tauri/src/index.ts
@@ -1 +1,2 @@
export { MaybeTauriProvider, useTauri } from './TauriProvider';
+export type { BundleUpdateStatus } from './TauriProvider';
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 ca20907eca..76ae8f263c 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
@@ -199,40 +199,34 @@ pub enum UpdateError {
Other,
}
-/// denotes that an update has been found and we are requesting approval
-#[derive(Debug, Clone, Copy)]
-pub struct UpdateRequested(());
-/// denotes that an update was approved via an [UpdateRequested]
+/// denotes that an update was approved
#[derive(Debug, Clone)]
pub struct UpdateGranted(());
-/// denotes that an update was denied via an [UpdateRequest]
+impl UpdateGranted {
+ pub fn new() -> Self {
+ UpdateGranted(())
+ }
+}
+
+/// denotes that an update was denied
#[derive(Debug, Clone, Copy)]
pub struct UpdateDenied(());
+impl UpdateDenied {
+ pub fn new() -> Self {
+ UpdateDenied(())
+ }
+}
+
#[derive(Debug, Clone)]
pub enum UpdateApproval {
Granted(UpdateGranted),
Denied(UpdateDenied),
}
-impl UpdateRequested {
- pub(crate) fn new_request() -> Self {
- UpdateRequested(())
- }
-
- pub fn grant(self) -> UpdateGranted {
- UpdateGranted(())
- }
-
- pub fn deny(self) -> UpdateDenied {
- UpdateDenied(())
- }
-}
-
#[derive(Debug, Clone)]
pub struct UpdateFoundStatus {
- pub request: UpdateRequested,
pub bundle: BundleUpdate,
}
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 22d7c7b0a2..7f4d790287 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
@@ -43,5 +43,11 @@ pub trait SystemQuery: Send + Sync + 'static {
pub trait AutoUpdateService: 'static {
fn status(&self) -> &tokio::sync::watch::Receiver<Result<UpdateStatus, Report<UpdateError>>>;
- fn grant_or_deny(&mut self, grant: UpdateApproval) -> Result<(), Report>;
+ /// 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>;
+ /// 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 a8fc28b46d..53b4039f57 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,7 +1,7 @@
use crate::domain::{
models::{
CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus, UpdateApproval,
- UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateRequested, UpdateStatus,
+ UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
},
ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},
};
@@ -13,17 +13,29 @@ pub struct Service {
handle: WorkerHandle,
}
+/// 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>>;
+
+/// Main thread sends on this to start the checker loop.
+type StartTx = tokio::sync::mpsc::Sender<()>;
+/// Worker receives on this to know when to run the checker loop.
+type StartRx = tokio::sync::mpsc::Receiver<()>;
+
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_rx: Option<tokio::sync::oneshot::Receiver<UpdateApproval>>,
+ grant_offer_tx: GrantOfferTx,
+ start_rx: StartRx,
}
struct WorkerHandle {
status_rx: tokio::sync::watch::Receiver<Result<UpdateStatus, Report<UpdateError>>>,
- grant_tx: Option<tokio::sync::oneshot::Sender<UpdateApproval>>,
+ grant_offer_rx: GrantOfferRx,
+ start_tx: StartTx,
}
/// the name of the app entrypoint
@@ -32,42 +44,58 @@ 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_tx, grant_rx) = tokio::sync::oneshot::channel();
+ 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_rx: Some(grant_rx),
+ grant_offer_tx,
+ start_rx,
}
.run_background();
WorkerHandle {
status_rx,
- grant_tx: Some(grant_tx),
+ grant_offer_rx,
+ start_tx,
}
}
fn run_background(mut self) {
tauri::async_runtime::spawn(async move {
- loop {
- let Ok(status) = self.status_tx.borrow().as_ref().cloned() else {
- break;
- };
- if let UpdateStatus::NoUpdateNeeded | UpdateStatus::Completed(_) = status {
+ // 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;
}
- let next = self.next_status(status).await;
-
- let Ok(()) = self.status_tx.send(next) else {
- break;
- };
+ self.run_check_loop().await;
}
});
}
+ async fn run_check_loop(&mut self) {
+ loop {
+ let Ok(status) = self.status_tx.borrow().as_ref().cloned() else {
+ break;
+ };
+ if let UpdateStatus::NoUpdateNeeded | UpdateStatus::Completed(_) = status {
+ break;
+ }
+
+ let next = self.next_status(status).await;
+
+ let Ok(()) = self.status_tx.send(next) else {
+ break;
+ };
+ }
+ }
+
#[tracing::instrument(ret, err, skip(self))]
async fn next_status(
&mut self,
@@ -92,18 +120,18 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
match res {
Some(update) => Ok(UpdateStatus::UpdateFound(UpdateFoundStatus {
- request: UpdateRequested::new_request(),
bundle: update,
})),
None => Ok(UpdateStatus::NoUpdateNeeded),
}
}
UpdateStatus::UpdateFound(update_found_status) => {
- let Some(rx) = self.grant_rx.take() else {
- return Err(
- report!("Already granted permission").context(UpdateError::GrantErr)
- );
- };
+ 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)
@@ -233,11 +261,20 @@ impl AutoUpdateService for Service {
&self.handle.status_rx
}
- fn grant_or_deny(&mut self, grant: UpdateApproval) -> Result<(), Report> {
- let Some(tx) = self.handle.grant_tx.take() else {
- return Err(report!("Already granted"));
- };
- tx.send(grant)
- .map_err(|e| rootcause::report!("Failed to send {e:?}. The rx channel was dropped"))
+ 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}"))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ fn start(&self) -> Result<(), Report> {
+ self.handle
+ .start_tx
+ .try_send(())
+ .map_err(|e| report!("Failed to send start signal: {e}"))
}
}
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 432d52bd1a..4ee7424d4a 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
@@ -7,7 +7,7 @@ use url::Url;
use crate::{
domain::{
- models::{UpdateApproval, UpdateError, UpdateStatus},
+ models::{UpdateApproval, UpdateDenied, UpdateError, UpdateGranted, UpdateStatus},
ports::AutoUpdateService,
service::Service,
},
@@ -78,19 +78,15 @@ pub fn grant_bundle_update(
approved: bool,
) -> Result<(), String> {
let mut service = service.lock().unwrap();
- let request = {
- let status = service.status().borrow();
- match status.as_ref() {
- Ok(UpdateStatus::UpdateFound(found)) => found.request,
- _ => return Err("No pending update request".into()),
- }
- };
+ let grant_tx = service.try_recv_grant_sender().map_err(|e| e.to_string())?;
let approval = if approved {
- UpdateApproval::Granted(request.grant())
+ UpdateApproval::Granted(UpdateGranted::new())
} else {
- UpdateApproval::Denied(request.deny())
+ UpdateApproval::Denied(UpdateDenied::new())
};
- service.grant_or_deny(approval).map_err(|e| e.to_string())
+ grant_tx
+ .send(approval)
+ .map_err(|_| "Worker dropped the grant receiver".to_string())
}
#[tauri::command]
@@ -119,16 +115,38 @@ pub fn perform_update<R: Runtime>(
tracing::info!("Setting bundle root to {bundle_dir:?}");
*bundle_root.0.write().map_err(|e| e.to_string())? = Some(bundle_dir);
+ // Persist so subsequent restarts use the updated bundle
+ let cache_dir = app_handle
+ .path()
+ .app_cache_dir()
+ .map_err(|e| e.to_string())?;
+ bundle_root.persist(&cache_dir).map_err(|e| e.to_string())?;
+
// Navigate to the updated bundle, preserving the current hash route.
if let Some(webview) = app_handle.webview_windows().values().next() {
tracing::info!("Bundle update complete, navigating to updated bundle");
let _ = webview.eval(
- "window.location.href = 'tauri://localhost/app/index.html' + window.location.hash;"
+ "window.location.href = 'tauri://localhost/app/index.html' + window.location.hash;",
);
}
Ok(())
}
+#[tauri::command]
+pub fn check_for_update(service: tauri::State<'_, Mutex<Service>>) -> Result<(), String> {
+ let service = service.lock().unwrap();
+ service.start().map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub fn get_bundle_update_status(
+ service: tauri::State<'_, Mutex<Service>>,
+) -> Result<BundleUpdateEvent, String> {
+ let service = service.lock().unwrap();
+ let status = service.status().borrow();
+ Ok(BundleUpdateEvent::new(&status))
+}
+
impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
fn name(&self) -> &'static str {
"macro-bundle-updater"
@@ -146,6 +164,7 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
let service = Service::new(client, fs, system_info);
let mut status_rx = service.status().clone();
+ let _ = service.start();
app.manage(Mutex::new(service));
let app_handle = app.clone();
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs b/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
index 13157aeb41..e46b34ad5a 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/lib.rs
@@ -1,11 +1,65 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::RwLock;
pub mod domain;
pub mod inbound;
pub mod outbound;
+/// Name of the file used to persist the bundle root path across restarts.
+const BUNDLE_ROOT_FILE: &str = "bundle_root";
+
/// Swappable root directory for serving frontend assets.
/// `None` = use built-in asset resolver (initial bundle from `frontendDist`).
/// `Some(path)` = serve files from this directory (after OTA update).
pub struct BundleRoot(pub RwLock<Option<PathBuf>>);
+
+impl BundleRoot {
+ /// Load persisted bundle root from the given cache directory.
+ /// Returns `BundleRoot(None)` if no persisted path exists or if the directory is gone.
+ pub fn load(cache_dir: &Path) -> Self {
+ let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
+ tracing::info!("Loading bundle root from {persist_path:?}");
+ match std::fs::read_to_string(&persist_path) {
+ Ok(contents) => {
+ let path = PathBuf::from(contents.trim());
+ let index = path.join("index.html");
+ if index.exists() {
+ tracing::info!("Restored bundle root: {path:?}");
+ BundleRoot(RwLock::new(Some(path)))
+ } else {
+ tracing::warn!(
+ "Persisted bundle root {path:?} missing index.html at {index:?}"
+ );
+ BundleRoot(RwLock::new(None))
+ }
+ }
+ Err(e) => {
+ tracing::info!("No persisted bundle root: {e}");
+ BundleRoot(RwLock::new(None))
+ }
+ }
+ }
+
+ /// Persist the bundle root path so it survives app restarts.
+ pub fn persist(&self, cache_dir: &Path) -> Result<(), std::io::Error> {
+ let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);
+ let guard = self
+ .0
+ .read()
+ .map_err(|e| std::io::Error::other(e.to_string()))?;
+ match guard.as_ref() {
+ Some(root) => {
+ tracing::info!("Persisting bundle root {root:?} to {persist_path:?}");
+ std::fs::write(&persist_path, root.to_string_lossy().as_bytes())
+ }
+ None => {
+ // Remove the file if bundle root is cleared
+ match std::fs::remove_file(&persist_path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
+ }
+ }
+ }
+ }
+}
diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rs
index ffe041bd11..11e6755ae4 100644
--- a/js/app/tauri/src-tauri/src/lib.rs
+++ b/js/app/tauri/src-tauri/src/lib.rs
@@ -105,6 +105,10 @@ static ALLOWED_DOMAINS: &[&str] = &[
"http://localhost:3009",
];
+type Type = std::sync::OnceLock<
+ Box<dyn Fn(&str, http::Request<Vec<u8>>, tauri::UriSchemeResponder) + Send + Sync + 'static>,
+>;
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
use tracing_subscriber::EnvFilter;
@@ -206,13 +210,34 @@ pub fn run() {
// However, tauri_protocol::get needs AppHandle upfront.
// Use a lazy init pattern via the context.
let window_origin = window_origin.to_string();
- let handler: std::sync::OnceLock<
- Box<dyn Fn(&str, http::Request<Vec<u8>>, tauri::UriSchemeResponder) + Send + Sync>,
- > = std::sync::OnceLock::new();
+ let handler: Type = std::sync::OnceLock::new();
move |ctx, request, responder| {
let h = handler.get_or_init(|| {
- tauri_protocol::get(ctx.app_handle().clone(), &window_origin)
+ // Restore persisted bundle root before the first request is served
+ let app = ctx.app_handle();
+ match app.path().app_cache_dir() {
+ Ok(cache_dir) => {
+ tracing::info!("Protocol handler init: cache_dir={cache_dir:?}");
+ let restored = BundleRoot::load(&cache_dir);
+ if let Ok(val) = restored.0.read()
+ && let Some(ref path) = *val
+ {
+ if let Some(br) = app.try_state::<BundleRoot>() {
+ tracing::info!("Setting managed BundleRoot to {path:?}");
+ if let Ok(mut w) = br.0.write() {
+ *w = Some(path.clone());
+ }
+ } else {
+ tracing::warn!("BundleRoot state not managed yet");
+ }
+ }
+ }
+ Err(e) => {
+ tracing::warn!("Failed to get app_cache_dir: {e}");
+ }
+ }
+ tauri_protocol::get(app.clone(), &window_origin)
});
h(ctx.webview_label(), request, responder);
}
@@ -225,9 +250,25 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
heartbeat_response,
macro_bundle_updater_plugin::inbound::plugin::grant_bundle_update,
- macro_bundle_updater_plugin::inbound::plugin::perform_update
+ macro_bundle_updater_plugin::inbound::plugin::perform_update,
+ macro_bundle_updater_plugin::inbound::plugin::check_for_update,
+ macro_bundle_updater_plugin::inbound::plugin::get_bundle_update_status
])
.setup(|app| {
+ // Restore persisted bundle root on startup
+ if let Ok(cache_dir) = app.path().app_cache_dir() {
+ let restored = BundleRoot::load(&cache_dir);
+ if let Ok(val) = restored.0.read()
+ && let Some(ref path) = *val
+ {
+ let bundle_root = app.state::<BundleRoot>();
+ if let Ok(mut w) = bundle_root.0.write() {
+ *w = Some(path.clone());
+ tracing::info!("Setup: restored BundleRoot to {path:?}");
+ }
+ }
+ }
+
#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]
{
use tauri_plugin_deep_link::DeepLinkExt;
@@ -253,7 +294,7 @@ pub fn run() {
/// fn to merge the headers from the http cookie store into the initial
/// GET request to open a websocket
fn merge_header_callback<R: Runtime>(url: String, headers: &mut HeaderMap, handle: &AppHandle<R>) {
- tracing::debug!("got url {url}");
+ tracing::trace!("got url {url}");
let Some(s) = handle.try_state::<tauri_plugin_http::Http>() else {
return;
};
@@ -265,11 +306,10 @@ fn merge_header_callback<R: Runtime>(url: String, headers: &mut HeaderMap, handl
_ => "https",
})
.ok();
- tracing::debug!("checking cookies for {url}");
+ tracing::trace!("checking cookies for {url}");
if let Some(cookie) = s.inner().cookies_jar.as_ref().cookies(&url) {
- tracing::info!("inserting cookie value for {url}");
- tracing::debug!("{cookie:?}");
+ tracing::trace!("inserting cookie value for {url}, {cookie:?}");
headers.insert(COOKIE, cookie);
}
}
@@ -288,7 +328,7 @@ impl AppChain for tauri::App {
fn attach_deep_link_handler(app: &mut tauri::App) {
fn inner_handler(ev: OpenUrlEvent, handle: &AppHandle) -> Result<(), Report> {
let urls = ev.urls();
- tracing::info!("received open url event {urls:?}");
+ tracing::trace!("received open url event {urls:?}");
let url = urls
.into_iter()
.next()
@@ -316,7 +356,7 @@ fn attach_deep_link_handler(app: &mut tauri::App) {
// we send a navigate event instead of calling navigate directly
// because navigate performs a full browser navigation
- tracing::info!("{payload:?}");
+ tracing::trace!("{payload:?}");
Ok(handle.emit("navigate", payload)?)
}
diff --git a/js/app/tauri/src-tauri/src/tauri_protocol.rs b/js/app/tauri/src-tauri/src/tauri_protocol.rs
index 19eb55492b..429375169c 100644
--- a/js/app/tauri/src-tauri/src/tauri_protocol.rs
+++ b/js/app/tauri/src-tauri/src/tauri_protocol.rs
@@ -8,7 +8,7 @@
// to the upstream handler which handles dev proxy, CSP, security headers, etc.
// When `BundleRoot` is `Some(path)`, files are served directly from disk.
-use http::{header::CONTENT_TYPE, Response as HttpResponse, StatusCode};
+use http::{Response as HttpResponse, StatusCode, header::CONTENT_TYPE};
use tauri::{Manager, Runtime, UriSchemeResponder};
use macro_bundle_updater_plugin::BundleRoot;
@@ -42,9 +42,7 @@ fn rewrite_uri(uri: &str) -> String {
if !prefix.ends_with('/') && !rest.is_empty() && !rest.starts_with('/') {
continue;
}
- let origin = prefix
- .trim_end_matches("/app/")
- .trim_end_matches("/app");
+ let origin = prefix.trim_end_matches("/app/").trim_end_matches("/app");
return format!("{}/{}", origin, rest);
}
}
@@ -55,10 +53,7 @@ fn rewrite_uri(uri: &str) -> String {
///
/// 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 {
+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();
@@ -87,6 +82,11 @@ pub fn get<R: Runtime>(
.unwrap_or(&raw_path);
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),
+ };
let br = bundle_root.unwrap();
let guard = br.0.read().unwrap();
@@ -146,6 +146,18 @@ pub fn get<R: Runtime>(
);
}
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)