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
fix(desktop): honor notification preferences and stabilize bundle updates (#7532)
Eric Hayes371394c06861
diff --git a/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx b/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsxindex 6647bf3269..41b80b4000 100644--- a/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx+++ b/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx@@ -1,4 +1,5 @@import { createTabLeaderSignal } from '@core/cross-tab/tab-leader';+import { makeEventListener } from '@solid-primitives/event-listener';import { makePersisted } from '@solid-primitives/storage';import {type Accessor,@@ -28,7 +29,8 @@ export interface PlatformNotificationInterface {}export type CreateAppNotificationInterface = (- setDisabled: () => Promise<void>+ setDisabled: () => Promise<void>,+ shouldSend: Accessor<boolean>) => PlatformNotificationInterface;export type NotificationUnsupported = 'not-supported';@@ -162,6 +164,24 @@ function PlatformNotificationState(props: {});+ function currentPermission(): NotificationPermission | UiDisabled {+ // A failed native read must leave the setting usable so the user can+ // retry. Reading resource.latest directly would throw into the UI.+ if (permission.error !== undefined) return 'denied';+ return permission.latest ?? 'default';+ }++ async function refreshPermission() {+ try {+ await refetch();+ } catch {+ // currentPermission exposes a failed read as denied, without breaking UI.+ }+ }++ // System Settings can change authorization while this app is open.+ makeEventListener(window, 'focus', refreshPermission);+async function requestPermission() {if (platformNotif === 'not-supported') {console.warn(@@ -172,6 +192,7 @@ function PlatformNotificationState(props: {props.setManuallyDisabled('allowed');const res = await platformNotif.requestPermission();await refetch();+ if (permission.error !== undefined) throw permission.error;return res;}@@ -183,7 +204,17 @@ function PlatformNotificationState(props: {return manuallyDisabled;}- if (permission.latest !== 'granted' || platformNotif === 'not-supported') {+ if (currentPermission() !== 'granted') {+ await refreshPermission();+ }+ if (props.manuallyDisabled() === 'disabled-in-ui') {+ return 'disabled-in-ui';+ }++ if (+ currentPermission() !== 'granted' ||+ platformNotif === 'not-supported'+ ) {return 'not-granted';}@@ -193,7 +224,7 @@ function PlatformNotificationState(props: {return (<NotificationStateContext.Providervalue={{- permission: () => permission.latest ?? 'default',+ permission: currentPermission,requestPermission,unregisterNotification: platformNotif.unregisterNotifications,showNotification,@@ -218,7 +249,8 @@ export function PlatformNotificationProvider(props: {};const value = (props.overrideDefault ?? createDefaultBrowserInterface)(- setDisabled+ setDisabled,+ () => manuallyDisabled() !== 'disabled-in-ui');return (diff --git a/apps/web/src/features/settings/Notifications.tsx b/apps/web/src/features/settings/Notifications.tsxindex 829351adf0..2997862407 100644--- a/apps/web/src/features/settings/Notifications.tsx+++ b/apps/web/src/features/settings/Notifications.tsx@@ -1,6 +1,7 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';import { toast } from '@core/component/Toast/Toast';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { isTauri } from '@core/util/platform';import {EMAIL_DIGEST_NOTIFICATION_TYPE,NOTIFICATION_EVENT_GROUPS,@@ -16,8 +17,9 @@ import {useMutedEntitiesQuery,useUnmuteItemMutation,} from '@queries/notification/unsubscribes';+import { type as osType } from '@tauri-apps/plugin-os';import { ToggleSwitch } from '@ui';-import { For, getOwner, Show } from 'solid-js';+import { createSignal, For, getOwner, Show } from 'solid-js';import { MutedItemRow } from './MutedItemRow';import {SettingsCard,@@ -30,6 +32,7 @@ export function Notifications() {const dialogOwner = getOwner();const analytics = useAnalytics();const platformSettings = useNotificationSettings();+ const [pushPending, setPushPending] = createSignal(false);const preferencesQuery = useNotificationTypePreferencesQuery();const setTypeEnabled = useSetNotificationTypeEnabledMutation();const mutedEntitiesQuery = useMutedEntitiesQuery({ limit: 100 });@@ -54,6 +57,27 @@ export function Notifications() {const isTypeEnabled = (type: string) => !disabledTypes().has(type);+ const togglePush = async (enabled: boolean) => {+ if (!platformSettings.isSupported || pushPending()) return;+ setPushPending(true);+ try {+ analytics.track('notifications_toggled');+ await platformSettings.toggle(enabled);+ if (enabled && !platformSettings.isEnabled()) {+ toast.failure(+ isTauri() && osType() === 'macos'+ ? 'Open System Settings → Notifications → Macro and turn on Allow notifications.'+ : 'Allow notification permissions, then try again.'+ );+ }+ } catch (error) {+ console.error('Could not update notification permission', error);+ toast.failure('Could not update notifications. Try again.');+ } finally {+ setPushPending(false);+ }+ };+const toggleType = async (type: string, enabled: boolean) => {try {await setTypeEnabled.mutateAsync({ type, enabled });@@ -104,11 +128,11 @@ export function Notifications() {<SettingsRow label={pushLabel} description={pushDescription}><ToggleSwitchsize="md"+ label={pushLabel}+ labelClass="sr-only"checked={settings().isEnabled()}- onChange={(enabled) => {- analytics.track('notifications_toggled');- void settings().toggle(enabled);- }}+ disabled={pushPending()}+ onChange={(enabled) => void togglePush(enabled)}/></SettingsRow>)}diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.tsindex 8360dd3806..4e0d14d9ba 100644--- a/apps/web/src/lib/tauri/notification.ts+++ b/apps/web/src/lib/tauri/notification.ts@@ -2,16 +2,37 @@ import type {PlatformNotificationHandle,PlatformNotificationInterface,} from '@notifications';+import { invoke } from '@tauri-apps/api/core';import {isPermissionGranted,requestPermission,sendNotification,} from '@tauri-apps/plugin-notification';+import { type as osType } from '@tauri-apps/plugin-os';export function createTauriNotificationInterface(- setDisabled: () => Promise<void>+ setDisabled: () => Promise<void>,+ shouldSend: () => boolean = () => true): PlatformNotificationInterface {- async function getCur() {+ let hasMacOSPermissionCommands = osType() === 'macos';++ async function getCur(): Promise<NotificationPermission> {+ // The notification plugin always reports permission as granted on desktop.+ // Read the actual OS authorization on macOS instead.+ if (hasMacOSPermissionCommands) {+ try {+ return await invoke<NotificationPermission>(+ 'get_macos_notification_permission'+ );+ } catch (error) {+ // Older native builds can receive this frontend through an OTA update.+ // Preserve their existing behavior only when the command is absent.+ if (error !== 'Command get_macos_notification_permission not found') {+ throw error;+ }+ hasMacOSPermissionCommands = false;+ }+ }return (await isPermissionGranted()) ? 'granted' : 'denied';}return {@@ -20,13 +41,23 @@ export function createTauriNotificationInterface(if (cur === 'granted') {return 'granted';}+ if (hasMacOSPermissionCommands) {+ // macOS will not prompt again after denial; permission must be changed+ // in System Settings.+ if (cur === 'denied') return 'denied';+ return await invoke<NotificationPermission>(+ 'request_macos_notification_permission'+ );+ }return await requestPermission();},getCurrentPermission: getCur,showNotification: async (data) => {const granted = await getCur();- if (granted !== 'granted') {+ // A user can disable notifications while the native permission check+ // is in flight. Check the current preference just before dispatching.+ if (granted !== 'granted' || !shouldSend()) {return 'not-granted';}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex d46d3c24c3..42652cb2a2 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -245,6 +245,7 @@ dependencies = [name = "app"version = "0.1.0"dependencies = [+ "block2","clap","graphql_cache_plugin","http",@@ -257,6 +258,9 @@ dependencies = ["navigation_plugin","nom","objc2 0.5.2",+ "objc2 0.6.4",+ "objc2-foundation",+ "objc2-user-notifications","reqwest","rootcause","rustls-platform-verifier",@@ -4316,6 +4320,8 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"dependencies = [+ "bitflags 2.11.1",+ "block2","objc2 0.6.4","objc2-foundation",]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.rsindex ee4a65f39b..3ce1b68d17 100644--- 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.rs@@ -45,6 +45,10 @@ impl BundleAssetPath {fn has_extension(&self) -> bool {self.0.extension().is_some()}++ fn is_entrypoint(&self) -> bool {+ self.0 == Path::new("index.html")+ }}/// Error returned when an asset path is not safe to resolve.@@ -106,6 +110,7 @@ wherematch &routes.active {BundleSource::Embedded { .. } => {if path.has_extension()+ && !path.is_entrypoint()&& let Some(BundleSource::Ota { root, .. }) = &routes.fallback&& let Some(bytes) = self.assets.read_asset(root, path).await?{@@ -124,6 +129,12 @@ where});}+ // A new document must identify the active generation. Falling+ // back to the old index prevents its reload acknowledgement.+ if path.is_entrypoint() {+ return Ok(BundleAssetResolution::NotFound);+ }+if !path.has_extension() {let entrypoint = BundleAssetPath::entrypoint();return Ok(match self.assets.read_asset(root, &entrypoint).await? {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.rsindex a99cd904bc..a36721e273 100644--- 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.rs@@ -158,3 +158,47 @@ async fn ota_to_embedded_transition_checks_the_previous_ota_first() {});}++#[tokio::test]+async fn rollback_entrypoints_always_use_the_embedded_document() {+ let routes = BundleRoutes::new(100);+ routes+ .restore(BundleSource::ota(101, PathBuf::from("/ota/101")))+ .await;+ routes.transition_to(BundleSource::embedded(100)).await;+ let assets = FakeAssets::default();+ assets+ .insert("/ota/101", "index.html", "revoked document")+ .await;+ let resolver = BundleAssetResolver::new(routes, assets);++ for request in ["", "index.html", "welcome"] {+ assert_eq!(+ resolver.resolve(&path(request)).await.unwrap(),+ BundleAssetResolution::Embedded+ );+ }+}++#[tokio::test]+async fn a_missing_ota_entrypoint_never_uses_the_previous_document() {+ let routes = BundleRoutes::new(100);+ routes+ .restore(BundleSource::ota(101, PathBuf::from("/ota/101")))+ .await;+ routes+ .transition_to(BundleSource::ota(102, PathBuf::from("/ota/102")))+ .await;+ let assets = FakeAssets::default();+ assets+ .insert("/ota/101", "index.html", "stale document")+ .await;+ let resolver = BundleAssetResolver::new(routes, assets);++ for request in ["", "index.html", "welcome"] {+ assert_eq!(+ resolver.resolve(&path(request)).await.unwrap(),+ BundleAssetResolution::NotFound+ );+ }+}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 3031d1a02f..14a1f6ad34 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@@ -9,21 +9,27 @@ use super::ports::FsRepo;/// Name of the file used to persist the bundle root path across restarts.const BUNDLE_ROOT_FILE: &str = "bundle_root";+const EMBEDDED_BUNDLE_MARKER: &str = "embedded";/// Swappable root directory for serving frontend assets.-/// `None` = use built-in asset resolver (initial bundle from `frontendDist`).-/// `Some(path)` = serve files from this directory (after OTA update).-pub(crate) struct BundleRoot(Option<PathBuf>);+pub(crate) enum BundleRoot {+ /// No selection was persisted; legacy completed downloads may be recovered.+ Uninitialized,+ /// Explicitly selected embedded assets, including after an OTA revocation.+ Embedded,+ /// Serve files from an applied OTA directory.+ Ota(PathBuf),+}impl BundleRoot {/// Create an empty bundle root (no OTA update applied).pub(crate) fn new() -> Self {- Self(None)+ Self::Uninitialized}/// Create a bundle root pointing to the given path.pub(crate) fn from_path(path: PathBuf) -> Self {- Self(Some(path))+ Self::Ota(path)}/// Load persisted bundle root from the given cache directory.@@ -32,11 +38,15 @@ impl BundleRoot {tracing::debug!("Loading bundle root from {persist_path:?}");match fs.read_to_string(&persist_path).await {Ok(contents) => {+ if contents.trim() == EMBEDDED_BUNDLE_MARKER {+ return Self::Embedded;+ }+ // Preserve compatibility with the original absolute-path marker.let path = PathBuf::from(contents.trim());let index = path.join("index.html");if fs.read_to_string(&index).await.is_ok() {tracing::debug!("Restored bundle root: {path:?}");- Self(Some(path))+ Self::Ota(path)} else {tracing::warn!("Persisted bundle root {path:?} missing index.html at {index:?}"@@ -44,12 +54,12 @@ impl BundleRoot {if let Err(e) = fs.remove_file(&persist_path).await {tracing::debug!("Failed to remove stale bundle_root file: {e}");}- Self(None)+ Self::Uninitialized}}Err(e) => {tracing::debug!("No persisted bundle root: {e}");- Self(None)+ Self::Uninitialized}}}@@ -61,24 +71,32 @@ impl BundleRoot {fs: &impl FsRepo,) -> Result<(), std::io::Error> {let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);- match self.0.as_ref() {- Some(root) => {+ match self {+ Self::Ota(root) => {tracing::debug!("Persisting bundle root {root:?} to {persist_path:?}");fs.write(&persist_path, root.to_string_lossy().as_bytes()).await}- None => fs.remove_file(&persist_path).await,+ Self::Embedded => {+ fs.create_dir_all(cache_dir).await?;+ fs.write(&persist_path, EMBEDDED_BUNDLE_MARKER.as_bytes())+ .await+ }+ Self::Uninitialized => fs.remove_file(&persist_path).await,}}/// Get the current bundle root path, if any.pub(crate) fn path(&self) -> Option<&Path> {- self.0.as_deref()+ match self {+ Self::Ota(path) => Some(path),+ Self::Uninitialized | Self::Embedded => 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");+ let manifest_path = self.path()?.join("bundle-manifest.json");BundleManifest::read(&manifest_path, fs).await}}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 6b0004a9ea..b29a4d2255 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@@ -2,7 +2,7 @@ use crate::domain::{bundle_routes::{BundleRoutes, BundleSource, BundleSourceKind},models::{AppInfo, BundleAction, BundleManifest, BundleRoot, ClearRequiredStatus, CompletedStatus,- NativeUpdateRequiredStatus, ProgressPercentage, UnzipRequest, UnzipStatus,+ NativeUpdateRequiredStatus, ProgressPercentage, Target, UnzipRequest, UnzipStatus,UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateGranted, UpdateStatus,},ports::{AutoUpdateService, FsRepo, SystemQuery, TaskSpawner, UpdateRepo},@@ -358,6 +358,13 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery, S: TaskSpawner> Worker<U, Fs, Q,}async fn should_download_now(&self) -> Result<bool, Report> {+ match self.system_query.get_native_app_info().await?.target {+ // Desktop updates use any available connection. Interface-name+ // heuristics report VPNs as e.g. "utun0", even over working Wi-Fi.+ // The download itself reports connectivity failures normally.+ Target::Darwin | Target::Linux | Target::Windows => return Ok(true),+ Target::Ios | Target::Android => {}+ }let network_type = self.system_query.get_network_type().await?;tracing::debug!(network_type = network_type.as_deref().unwrap_or("unknown"),@@ -563,8 +570,15 @@ impl<Fs: FsRepo> Service<Fs> {.restore(BundleSource::embedded(self.embedded_bundle_build)).await;- self.restore_pending_completed_update(cache_dir, native_build)- .await+ let restored_pending = self+ .restore_pending_completed_update(cache_dir, native_build)+ .await;+ if matches!(self.bundle_root, BundleRoot::Embedded) && !restored_pending {+ // No previous document is running at startup. Retired files from a+ // rollback interrupted before acknowledgement can now be removed.+ self.cleanup_old_bundles(cache_dir, None).await;+ }+ restored_pending}/// Bundle build embedded in this native app.@@ -723,6 +737,9 @@ impl<Fs: FsRepo> Service<Fs> {) -> bool {let marker = cache_dir.join(PENDING_BUNDLE_ROOT_FILE);let Ok(contents) = self.fs_repo.read_to_string(&marker).await else {+ if matches!(self.bundle_root, BundleRoot::Embedded) {+ return false;+ }return self.restore_latest_completed_download(cache_dir, native_build).await;@@ -832,7 +849,10 @@ impl<Fs: FsRepo> Service<Fs> {/// 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();+ // Persist an explicit embedded selection. Deleting the marker makes+ // retained OTA files indistinguishable from an uncommitted download+ // after a crash, so startup recovery could resurrect a revoked bundle.+ let cleared_bundle_root = BundleRoot::Embedded;cleared_bundle_root.persist(cache_dir, &self.fs_repo).await?;@@ -962,11 +982,15 @@ impl<Fs: FsRepo> Service<Fs> {}}+#[cfg(test)]+mod network_test;#[cfg(test)]mod persistence_test;#[cfg(test)]mod reload_test;#[cfg(test)]+mod rollback_test;+#[cfg(test)]mod tests {use super::*;use crate::domain::{@@ -1025,7 +1049,7 @@ mod tests {removed_dirs: Vec<PathBuf>,unzip_target: Option<PathBuf>,checksum_should_fail: bool,- remove_file_failure: Option<PathBuf>,+ write_failure: Option<PathBuf>,}impl FakeFs {@@ -1046,15 +1070,15 @@ mod tests {self.state.lock().unwrap().unzip_target = Some(path.into());}- pub(super) fn fail_remove_file(&self, path: impl Into<PathBuf>) {- self.state.lock().unwrap().remove_file_failure = Some(path.into());+ pub(super) fn fail_write(&self, path: impl Into<PathBuf>) {+ self.state.lock().unwrap().write_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())}- fn dir_exists(&self, path: impl AsRef<Path>) -> bool {+ pub(super) fn dir_exists(&self, path: impl AsRef<Path>) -> bool {self.state.lock().unwrap().dirs.contains(path.as_ref())}@@ -1162,6 +1186,9 @@ mod tests {}async fn write(&self, path: &Path, contents: &[u8]) -> Result<(), std::io::Error> {+ if self.state.lock().unwrap().write_failure.as_deref() == Some(path) {+ return Err(std::io::Error::other("write failed"));+ }self.write_file(path.to_path_buf(),String::from_utf8_lossy(contents).to_string(),@@ -1171,9 +1198,6 @@ mod tests {async fn remove_file(&self, path: &Path) -> Result<(), std::io::Error> {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(())}@@ -1189,10 +1213,11 @@ mod tests {}#[derive(Clone)]- struct FakeSystemQuery {+ pub(super) struct FakeSystemQuery {network_type: Arc<StdMutex<Option<String>>>,network_type_error: Arc<StdMutex<bool>>,native_build: Arc<StdMutex<u64>>,+ target: Arc<StdMutex<Target>>,update_dir: PathBuf,}@@ -1214,6 +1239,7 @@ mod tests {network_type: Arc::new(StdMutex::new(Some(network_type.to_string()))),network_type_error: Arc::new(StdMutex::new(false)),native_build: Arc::new(StdMutex::new(native_build)),+ target: Arc::new(StdMutex::new(Target::Ios)),update_dir,}}@@ -1222,9 +1248,13 @@ mod tests {*self.network_type.lock().unwrap() = Some(network_type.to_string());}- fn set_network_type_error(&self, should_error: bool) {+ pub(super) fn set_network_type_error(&self, should_error: bool) {*self.network_type_error.lock().unwrap() = should_error;}++ pub(super) fn set_target(&self, target: Target) {+ *self.target.lock().unwrap() = target;+ }}impl SystemQuery for FakeSystemQuery {@@ -1232,7 +1262,7 @@ mod tests {Ok(NativeAppInfo {native_build: *self.native_build.lock().unwrap(),arch: Arch::Aarch64,- target: Target::Ios,+ target: *self.target.lock().unwrap(),})}@@ -1307,14 +1337,14 @@ mod tests {);}- fn seed_pending_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {+ pub(super) fn seed_pending_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {fs.write_file(cache_dir.join(PENDING_BUNDLE_ROOT_FILE),bundle_dir.to_string_lossy().to_string(),);}- fn service_with_network(network_type: &str) -> (Service<FakeFs>, FakeSystemQuery) {+ pub(super) 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::<_, _, TestTaskSpawner>(@@ -1425,7 +1455,7 @@ mod tests {})}- async fn wait_for_status(+ pub(super) async fn wait_for_status(service: &Service<FakeFs>,mut predicate: impl FnMut(&UpdateStatus) -> bool,) -> UpdateStatus {@@ -1460,7 +1490,12 @@ mod tests {service.load_bundle_root(&cache_dir, 0).await;assert!(service.bundle_root_path().is_none());- assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );assert!(!fs.dir_exists(cache_dir.join("1")));assert!(!fs.dir_exists(cache_dir.join("2")));}@@ -1478,7 +1513,12 @@ mod tests {service.load_bundle_root(&cache_dir, 0).await;assert!(service.bundle_root_path().is_none());- assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );assert!(!fs.dir_exists(cache_dir.join("1")));}@@ -1496,7 +1536,12 @@ mod tests {service.load_bundle_root(&cache_dir, 0).await;assert!(service.bundle_root_path().is_none());- assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );assert!(!fs.dir_exists(cache_dir.join("1")));}@@ -1511,7 +1556,12 @@ mod tests {service.load_bundle_root(&cache_dir, 142).await;assert!(service.bundle_root_path().is_none());- assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );assert!(!fs.dir_exists(cache_dir.join("1")));}@@ -1971,7 +2021,12 @@ mod tests {assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);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_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );assert!(fs.dir_exists(cache_dir.join("1")));assert!(fs.dir_exists(cache_dir.join("2")));diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/network_test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/network_test.rsnew file mode 100644index 0000000000..5094e1dac9--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/network_test.rs@@ -0,0 +1,75 @@+use super::{+ Target, UpdateStatus,+ tests::{service_with_network, wait_for_status},+};+use crate::domain::ports::AutoUpdateService;++#[tokio::test]+async fn desktop_updates_download_over_vpn_or_unknown_connections() {+ for target in [Target::Darwin, Target::Linux, Target::Windows] {+ for network_type in ["utun0", "tun0", "unknown"] {+ let (service, system_query) = service_with_network(network_type);+ system_query.set_target(target);++ service.start().unwrap();++ wait_for_status(&service, |status| {+ matches!(status, UpdateStatus::DownloadingBundle(_))+ })+ .await;+ }+ }+}++#[tokio::test]+async fn desktop_updates_do_not_depend_on_network_classification() {+ for target in [Target::Darwin, Target::Linux, Target::Windows] {+ let (service, system_query) = service_with_network("unknown");+ system_query.set_target(target);+ system_query.set_network_type_error(true);++ service.start().unwrap();++ wait_for_status(&service, |status| {+ matches!(status, UpdateStatus::DownloadingBundle(_))+ })+ .await;+ }+}++#[tokio::test]+async fn mobile_updates_still_wait_for_wifi_on_cellular_or_unknown_connections() {+ for target in [Target::Ios, Target::Android] {+ for network_type in ["cellular", "unknown", "utun0"] {+ let (service, system_query) = service_with_network(network_type);+ system_query.set_target(target);++ service.start().unwrap();++ wait_for_status(&service, |status| {+ matches!(status, UpdateStatus::WaitingForWifi(_))+ })+ .await;+ }+ }+}++#[tokio::test]+async fn mobile_users_can_still_approve_a_cellular_download() {+ for target in [Target::Ios, Target::Android] {+ let (service, system_query) = service_with_network("cellular");+ system_query.set_target(target);+ service.start().unwrap();+ wait_for_status(&service, |status| {+ matches!(status, UpdateStatus::WaitingForWifi(_))+ })+ .await;++ service.approve_pending_update(true).unwrap();++ wait_for_status(&service, |status| {+ matches!(status, UpdateStatus::DownloadingBundle(_))+ })+ .await;+ }+}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.rsindex 39116d5c1a..65d84b0fc2 100644--- 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.rs@@ -13,7 +13,7 @@ async fn failed_bundle_root_persistence_preserves_active_bundle_state() {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);+ fs.fail_write(&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());servicediff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/rollback_test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/rollback_test.rsnew file mode 100644index 0000000000..8726dabeca--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/rollback_test.rs@@ -0,0 +1,72 @@+use super::{+ ApplyUpdateResult, BundleRoot, BundleSource, UpdateStatus,+ tests::{+ FakeFs, cache_dir, clear_required_status, seed_bundle, seed_pending_bundle_root,+ seed_persisted_bundle_root, service_with_status_and_fs,+ },+};+use crate::domain::ports::{AutoUpdateService, FsRepo};++#[tokio::test]+async fn rollback_interrupted_before_reload_ack_does_not_restore_retired_bundles() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let active = seed_bundle(&fs, &cache_dir, "1", 101, 0);+ seed_bundle(&fs, &cache_dir, "2", 102, 0);+ seed_persisted_bundle_root(&fs, &cache_dir, &active);+ let (mut service, _rx) = service_with_status_and_fs(clear_required_status(), fs.clone());+ service.bundle_root = BundleRoot::from_path(active.clone());+ service+ .bundle_routes+ .restore(BundleSource::ota(101, active))+ .await;++ assert_eq!(+ service.apply_update(&cache_dir).await.unwrap(),+ ApplyUpdateResult::ReloadNeeded+ );+ assert!(fs.dir_exists(cache_dir.join("1")));+ assert!(fs.dir_exists(cache_dir.join("2")));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ "embedded"+ );++ // No acknowledgement: model quitting or crashing during the live reload.+ drop(service);+ let (mut restarted, _rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());+ assert!(!restarted.load_bundle_root(&cache_dir, 0).await);+ assert_eq!(restarted.bundle_build().await, None);+ assert!(matches!(+ restarted.status().borrow().as_ref().unwrap(),+ UpdateStatus::Idle+ ));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ assert!(!fs.dir_exists(cache_dir.join("2")));+}++#[tokio::test]+async fn an_explicit_embedded_selection_can_restore_a_later_pending_download() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ BundleRoot::Embedded.persist(&cache_dir, &fs).await.unwrap();+ seed_bundle(&fs, &cache_dir, "1", 101, 0);+ let pending = seed_bundle(&fs, &cache_dir, "2", 102, 0);+ seed_pending_bundle_root(&fs, &cache_dir, &pending);+ let (mut service, _rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());++ assert!(service.load_bundle_root(&cache_dir, 0).await);+ assert_eq!(+ service.apply_update(&cache_dir).await.unwrap(),+ ApplyUpdateResult::ReloadNeeded+ );+ assert_eq!(service.bundle_build().await, Some(102));+ assert_eq!(+ fs.read_to_string(&cache_dir.join("bundle_root"))+ .await+ .unwrap(),+ pending.to_string_lossy()+ );+}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 0cf12a5a77..8f5ddb6c77 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@@ -8,6 +8,9 @@ use sha2::Sha256;use std::path::PathBuf;use zip::{read::root_dir_common_filter, result::ZipError};+#[cfg(test)]+mod test;+/// Real filesystem implementation of [`FsRepo`](crate::domain::ports::FsRepo).#[derive(Clone)]pub struct FileSystem;diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs/test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs/test.rsnew file mode 100644index 0000000000..29164eea04--- /dev/null+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/outbound/fs/test.rs@@ -0,0 +1,27 @@+use std::time::{SystemTime, UNIX_EPOCH};++use super::FileSystem;+use crate::domain::models::BundleRoot;++#[tokio::test]+async fn embedded_selection_persists_when_the_cache_directory_does_not_exist() {+ let unique = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let test_dir = std::env::temp_dir().join(format!(+ "macro-embedded-bundle-root-{}-{unique}",+ std::process::id()+ ));+ let cache_dir = test_dir.join("cache");+ assert!(!cache_dir.exists());++ let result = BundleRoot::Embedded.persist(&cache_dir, &FileSystem).await;+ let restored = BundleRoot::load(&cache_dir, &FileSystem).await;+ if test_dir.exists() {+ std::fs::remove_dir_all(&test_dir).unwrap();+ }++ result.expect("persisting an embedded selection must create the missing cache directory");+ assert!(matches!(restored, BundleRoot::Embedded));+}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 8db8913dd4..24e0145846 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -72,7 +72,21 @@ clap = { version = "4", features = ["derive"] }tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }[target.'cfg(target_os = "macos")'.dependencies]+block2 = "0.6"libc = "0.2"+objc2 = "0.6"+objc2-foundation = { version = "0.3", default-features = false, features = [+ "std",+ "NSBundle",+ "NSError",+ "NSString",+] }+objc2-user-notifications = { version = "0.3", default-features = false, features = [+ "std",+ "block2",+ "UNNotificationSettings",+ "UNUserNotificationCenter",+] }[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]tauri-plugin-haptics = "2"diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex ae6f4806ad..038caa1c91 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -36,6 +36,8 @@ use url::Url;mod device;mod diagnostics;mod logging;+#[cfg(target_os = "macos")]+mod macos_notification_permission;mod share_target;mod staged_upload;@@ -263,6 +265,10 @@ pub fn run() {.manage(IsIpad(is_ipad_device)).invoke_handler(tauri::generate_handler![diagnostics::read_desktop_diagnostics,+ #[cfg(target_os = "macos")]+ macos_notification_permission::get_macos_notification_permission,+ #[cfg(target_os = "macos")]+ macos_notification_permission::request_macos_notification_permission,graphql_cache_plugin::commands::graphql_cache_init,graphql_cache_plugin::commands::graphql_cache_current_revision,graphql_cache_plugin::commands::graphql_cache_current_storage_generation,diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission.rsnew file mode 100644index 0000000000..c956e955ae--- /dev/null+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs@@ -0,0 +1,128 @@+//! Read and request this app's notification authorization from macOS.+//!+//! The cross-platform notification plugin always reports permission granted on+//! desktop. Its delivery transport remains in use; these commands provide the+//! actual system permission without prompting during a permission read.++use std::ptr::NonNull;++use block2::RcBlock;+use objc2::runtime::Bool;+use objc2_foundation::{NSBundle, NSError};+use objc2_user_notifications::{+ UNAuthorizationOptions, UNAuthorizationStatus, UNNotificationSettings, UNUserNotificationCenter,+};+use serde::{Serialize, Serializer};+use tokio::sync::mpsc;++#[cfg(test)]+mod test;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum NotificationPermission {+ Default,+ Denied,+ Granted,+}++#[derive(Debug, thiserror::Error)]+pub enum NotificationPermissionError {+ #[error("macOS notification permissions require an application bundle; use the installed app")]+ MissingBundleIdentifier,+ #[error("macOS notification permission callback was dropped")]+ CallbackDropped,+ #[error("macOS notification authorization failed ({domain} {code}): {description}")]+ Native {+ domain: String,+ code: isize,+ description: String,+ },+}++fn ensure_application_bundle() -> Result<(), NotificationPermissionError> {+ NSBundle::mainBundle()+ .bundleIdentifier()+ .filter(|identifier| !identifier.is_empty())+ .ok_or(NotificationPermissionError::MissingBundleIdentifier)?;+ Ok(())+}++impl Serialize for NotificationPermissionError {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.serialize_str(&self.to_string())+ }+}++fn permission_from_status(status: UNAuthorizationStatus) -> NotificationPermission {+ match status {+ UNAuthorizationStatus::NotDetermined => NotificationPermission::Default,+ UNAuthorizationStatus::Authorized+ | UNAuthorizationStatus::Provisional+ | UNAuthorizationStatus::Ephemeral => NotificationPermission::Granted,+ // Unknown future statuses must not enable notification delivery.+ _ => NotificationPermission::Denied,+ }+}++#[tauri::command]+pub async fn get_macos_notification_permission()+-> Result<NotificationPermission, NotificationPermissionError> {+ // UserNotifications raises an Objective-C exception for unbundled dev/test+ // executables. Fail explicitly before asking it to create a center.+ ensure_application_bundle()?;+ let (sender, mut receiver) = mpsc::channel(1);+ {+ let callback = RcBlock::new(move |settings: NonNull<UNNotificationSettings>| {+ // SAFETY: macOS supplies a non-null settings object that remains+ // valid for the duration of this completion handler.+ let status = unsafe { settings.as_ref() }.authorizationStatus();+ let permission = permission_from_status(status);+ // The frontend may have closed while macOS was completing the read.+ let _ = sender.try_send(permission);+ });+ UNUserNotificationCenter::currentNotificationCenter()+ .getNotificationSettingsWithCompletionHandler(&callback);+ }+ receiver+ .recv()+ .await+ .ok_or(NotificationPermissionError::CallbackDropped)+}++#[tauri::command]+pub async fn request_macos_notification_permission()+-> Result<NotificationPermission, NotificationPermissionError> {+ ensure_application_bundle()?;+ let (sender, mut receiver) = mpsc::channel(1);+ {+ let callback = RcBlock::new(move |granted: Bool, error: *mut NSError| {+ // SAFETY: the optional NSError belongs to macOS and remains valid+ // during the callback. Copy its details before returning.+ let result = match unsafe { error.as_ref() } {+ Some(error) => Err(NotificationPermissionError::Native {+ domain: error.domain().to_string(),+ code: error.code(),+ description: error.localizedDescription().to_string(),+ }),+ None => Ok(if granted.as_bool() {+ NotificationPermission::Granted+ } else {+ NotificationPermission::Denied+ }),+ };+ let _ = sender.try_send(result);+ });+ UNUserNotificationCenter::currentNotificationCenter()+ .requestAuthorizationWithOptions_completionHandler(+ UNAuthorizationOptions::Alert+ | UNAuthorizationOptions::Sound+ | UNAuthorizationOptions::Badge,+ &callback,+ );+ }+ receiver+ .recv()+ .await+ .ok_or(NotificationPermissionError::CallbackDropped)?+}diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rsnew file mode 100644index 0000000000..0c901cb3c3--- /dev/null+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs@@ -0,0 +1,57 @@+use super::*;++#[test]+fn an_unanswered_system_prompt_is_not_a_denial() {+ assert_eq!(+ permission_from_status(UNAuthorizationStatus::NotDetermined),+ NotificationPermission::Default+ );+}++#[test]+fn system_denial_and_unknown_statuses_do_not_grant_permission() {+ for status in [UNAuthorizationStatus::Denied, UNAuthorizationStatus(99)] {+ assert_eq!(+ permission_from_status(status),+ NotificationPermission::Denied+ );+ }+}++#[test]+fn authorized_and_limited_authorization_can_deliver_notifications() {+ for status in [+ UNAuthorizationStatus::Authorized,+ UNAuthorizationStatus::Provisional,+ UNAuthorizationStatus::Ephemeral,+ ] {+ assert_eq!(+ permission_from_status(status),+ NotificationPermission::Granted+ );+ }+}++#[test]+fn permission_values_match_the_frontend_notification_permission_contract() {+ for (permission, value) in [+ (NotificationPermission::Default, "default"),+ (NotificationPermission::Denied, "denied"),+ (NotificationPermission::Granted, "granted"),+ ] {+ assert_eq!(serde_json::to_value(permission).unwrap(), value);+ }+}++#[test]+fn native_authorization_errors_reach_the_frontend_with_their_details() {+ let error = NotificationPermissionError::Native {+ domain: "UNErrorDomain".into(),+ code: 1,+ description: "Notifications are not allowed".into(),+ };+ assert_eq!(+ serde_json::to_value(error).unwrap(),+ "macOS notification authorization failed (UNErrorDomain 1): Notifications are not allowed"+ );+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex ace52d3fa0..a24ee6aeed 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2271,6 +2271,21 @@ session were not exercised by that UI check.## Notifications+In the desktop app, **Settings → Notifications → Delivery → Desktop notifications**+controls system notification delivery for this installation. When the Notifications+page is disabled by its feature flag, the existing **Account → Notifications**+switch controls the same preference.+Turning it off takes effect immediately and persists across app restarts; turning+it on requests permission and resumes delivery when authorized. On macOS the+switch reads the actual system authorization, and enabling it requests macOS+permission if it has not been decided. If macOS reports denial, enabling the switch+shows directions to **System Settings → Notifications → Macro → Allow notifications**+without requesting permission again; returning to Macro refreshes the switch.+It does not change inbox items or other devices. Focus and presentation settings+can still suppress alerts even when authorization is granted.+Verify off/on and persistence after restarting; on the Notifications page, a failed+toggle should show an error toast and allow retry.+On native Android, enable notifications in Settings while signed in. Android 13+also asks for system permission; the system's **Activity** notification channelmust be enabled. Remote push owns system notification display after registration,