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.

22.6 KB
Raw Blame
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::{
        bundle_routes::BundleRoutes,
        models::{UpdateError, UpdateStatus},
        ports::AutoUpdateService,
        service::{ApplyUpdateResult, Service},
    },
    outbound::{
        api_client::BundleClient,
        fs::FileSystem,
        runtime::TauriTaskSpawner,
        system_info::{SystemInfo, native_build},
    },
};

/// Concrete service type used by the plugin commands.
pub type PluginService = Service<FileSystem>;

const EVENT_NAME: &str = "bundle-update-status";
const WIFI_RETRY_INTERVAL: Duration = Duration::from_secs(30);

#[test]
fn diagnostic_wire_types() {
    let generated = specta_typescript::Typescript::default()
        .export(
            &specta::Types::default().register::<BundleReloadDiagnostics>(),
            specta_serde::Format,
        )
        .expect("export bundle reload types");
    let generated = generated
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n")
        + "\n";
    let output = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../src/observability/generated/bundle-reloads.ts");
    if std::env::var_os("UPDATE_NATIVE_DIAGNOSTIC_TYPES").is_some() {
        std::fs::create_dir_all(output.parent().expect("generated directory"))
            .expect("create directory");
        std::fs::write(&output, &generated).expect("write types");
    }
    assert_eq!(
        std::fs::read_to_string(output).expect("generated types"),
        generated
    );
}

/// Launch-scoped reload dispatches, retained across replacement documents.
#[derive(Clone, Default, Serialize)]
#[cfg_attr(test, derive(specta::Type))]
#[serde(rename_all = "camelCase")]
pub struct BundleReloadDiagnostics {
    #[cfg_attr(test, specta(type = specta_typescript::Number))]
    dispatches: u64,
    last_source: Option<&'static str>,
    last_reload_id: Option<String>,
    #[cfg_attr(test, specta(type = Option<specta_typescript::Number>))]
    last_dispatch_ms: Option<u64>,
}

/// Read reload evidence without waiting for the updater's async service lock.
pub fn bundle_reload_diagnostics<R: Runtime>(
    app: &tauri::AppHandle<R>,
) -> Option<BundleReloadDiagnostics> {
    let state = app.try_state::<std::sync::Mutex<BundleReloadDiagnostics>>()?;
    let diagnostics = state.lock().ok()?;
    Some(diagnostics.clone())
}

fn record_reload_dispatch<R: Runtime>(app: &tauri::AppHandle<R>, source: &'static str) {
    if let Some(state) = app.try_state::<std::sync::Mutex<BundleReloadDiagnostics>>()
        && let Ok(mut diagnostics) = state.lock()
    {
        diagnostics.dispatches += 1;
        diagnostics.last_source = Some(source);
        diagnostics.last_reload_id = Some(uuid::Uuid::new_v4().to_string());
        diagnostics.last_dispatch_ms = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        );
    }
    tracing::info!(source, "Dispatching bundle update WebView reload");
}

/// Serializable event emitted to the frontend via Tauri's event system.
#[derive(Clone, Serialize)]
#[serde(tag = "status", content = "data")]
pub enum BundleUpdateEvent {
    /// No update activity.
    Idle,
    /// Checking the server for updates.
    CheckingForUpdate,
    /// An update is available.
    UpdateFound {
        /// The new version string.
        version: String,
        /// Optional release notes.
        notes: Option<String>,
    },
    /// 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.
    Downloading {
        /// Download progress percentage (0–100).
        progress: f64,
    },
    /// Bundle extraction in progress.
    Unzipping {
        /// Extraction progress percentage (0–100).
        progress: f64,
    },
    /// The active OTA bundle must be cleared.
    ClearRequired {
        /// Reason the server requested a clear.
        reason: String,
    },
    /// A newer bundle exists but requires a newer native app build.
    NativeUpdateRequired {
        /// The newer bundle build that could not be applied.
        #[serde(rename = "bundleBuild")]
        bundle_build: u64,
        /// The minimum native build required by that bundle.
        #[serde(rename = "minNativeBuild")]
        min_native_build: u64,
    },
    /// Update applied successfully.
    Completed,
    /// An error occurred during the update.
    Error {
        /// Human-readable error message.
        message: String,
    },
}

/// Debug metadata about the currently effective JavaScript bundle.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BundleDebugInfo {
    /// Current effective bundle build.
    bundle_build: u64,
    /// Whether the effective bundle came from OTA cache or embedded assets.
    source: BundleDebugSource,
    /// Runtime native app build number.
    native_build: u64,
}

/// Source of the currently effective JavaScript bundle.
#[derive(Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum BundleDebugSource {
    /// The native app's embedded bundle is active.
    Embedded,
    /// A cached OTA bundle is active.
    Ota,
}

impl BundleUpdateEvent {
    fn new(cur: &Result<UpdateStatus, Report<UpdateError>>) -> Self {
        match cur.as_ref() {
            Ok(UpdateStatus::Idle) => BundleUpdateEvent::Idle,
            Ok(UpdateStatus::CheckingForDownload(_)) => BundleUpdateEvent::CheckingForUpdate,
            Ok(UpdateStatus::UpdateFound(found)) => BundleUpdateEvent::UpdateFound {
                version: found.bundle.bundle_build.to_string(),
                notes: found.bundle.notes.clone(),
            },
            Ok(UpdateStatus::WaitingForWifi(_found)) => BundleUpdateEvent::WaitingForWifi,
            Ok(UpdateStatus::NoUpdateNeeded) => BundleUpdateEvent::NoUpdateNeeded,
            Ok(UpdateStatus::ClearRequired(clear)) => BundleUpdateEvent::ClearRequired {
                reason: clear.reason.clone(),
            },
            Ok(UpdateStatus::NativeUpdateRequired(required)) => {
                BundleUpdateEvent::NativeUpdateRequired {
                    bundle_build: required.bundle_build,
                    min_native_build: required.min_native_build,
                }
            }
            Ok(UpdateStatus::DownloadingBundle(dl)) => BundleUpdateEvent::Downloading {
                progress: dl.progress.value(),
            },
            Ok(UpdateStatus::UnzippingBundle(uz)) => BundleUpdateEvent::Unzipping {
                progress: uz.progress.value(),
            },
            Ok(UpdateStatus::Completed(_completed)) => BundleUpdateEvent::Completed,
            Err(e) => BundleUpdateEvent::Error {
                message: e.to_string(),
            },
        }
    }
}

/// Tauri plugin that manages OTA bundle updates.
pub struct MacroBundleUpdaterPlugin {
    base_url: Url,
    embedded_bundle_build: u64,
    bundle_routes: BundleRoutes,
    auto_update: bool,
}

impl MacroBundleUpdaterPlugin {
    /// Create the plugin targeting the given update server URL.
    pub fn new(base_url: Url, embedded_bundle_build: u64, bundle_routes: BundleRoutes) -> Self {
        Self {
            base_url,
            embedded_bundle_build,
            bundle_routes,
            auto_update: true,
        }
    }

    /// Enable or disable automatic update activity.
    ///
    /// When disabled, the plugin never restores or applies a cached OTA bundle
    /// at startup and never starts update checks on its own, so the embedded
    /// bundle (or dev server) always wins. Explicit commands
    /// (`check_for_update`, `perform_update`, `clear_bundle`) still work.
    pub fn with_auto_update(mut self, enabled: bool) -> Self {
        self.auto_update = enabled;
        self
    }
}

/// Approve or deny a pending bundle update.
#[tauri::command]
pub async fn grant_bundle_update(
    service: tauri::State<'_, Mutex<PluginService>>,
    approved: bool,
) -> Result<(), String> {
    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);
    };

    let service = service_state.lock().await;
    service.retry_waiting_for_wifi().map_err(|e| e.to_string())
}

/// Start a fresh bundle update check.
pub async fn start_update_check<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 service = service_state.lock().await;
    service.start().map_err(|e| e.to_string())?;
    Ok(true)
}

/// 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.
///
/// Returns `Ok(true)` if an update was applied, `Ok(false)` if the service is
/// not in the `Completed` state (no pending update to commit).
pub async fn apply_completed_update<R: Runtime>(
    app_handle: &tauri::AppHandle<R>,
) -> Result<bool, String> {
    apply_completed_update_from(app_handle, "command").await
}

/// Apply a completed bundle update and include the caller in operational logs.
pub async fn apply_completed_update_from<R: Runtime>(
    app_handle: &tauri::AppHandle<R>,
    source: &'static str,
) -> Result<bool, String> {
    let service_state = app_handle
        .try_state::<Mutex<PluginService>>()
        .ok_or_else(|| "Bundle updater plugin not initialized".to_string())?;

    let cache_dir = app_handle
        .path()
        .app_cache_dir()
        .map_err(|e| e.to_string())?;

    // Keep application and reload dispatch in one critical section. Native
    // installation holds this same lock while shutting down the webview/cache.
    let mut service = service_state.lock().await;
    let apply_result = {
        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 apply_result == ApplyUpdateResult::Held {
        tracing::info!(source, "[bundle-update] page is holding reloads");
    }

    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() {
            record_reload_dispatch(app_handle, source);
            if let Err(e) = webview.eval("window.location.reload();") {
                tracing::warn!(
                    source,
                    error=?e,
                    "[bundle-update] failed to dispatch webview reload"
                );
                service.unmark_update_reload_dispatched();
            }
        } else {
            tracing::warn!(
                source,
                "[bundle-update] completed bundle update applied but no webview was available to reload"
            );
            service.unmark_update_reload_dispatched();
        }
    }
    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<bool, String> {
    apply_completed_update(&app_handle).await
}

/// Hold or release automatic reloads for work the page would lose to one.
///
/// A native auth sheet returns its result only to the document that opened it,
/// and this process applies completed updates on foreground without asking
/// that document, so the hold has to live here. Each document sends its state
/// on mount, which clears a hold left by one that died holding.
#[tauri::command]
pub async fn set_bundle_reload_hold(
    service: tauri::State<'_, Mutex<PluginService>>,
    held: bool,
) -> Result<(), String> {
    service.lock().await.set_reload_held(held);
    Ok(())
}

/// Acknowledge that the webview mounted after an applied bundle update reload.
#[tauri::command]
pub async fn ack_bundle_update_reload<R: Runtime>(
    service: tauri::State<'_, Mutex<PluginService>>,
    app_handle: tauri::AppHandle<R>,
    loaded_bundle_build: u64,
) -> Result<bool, String> {
    let cache_dir = app_handle
        .path()
        .app_cache_dir()
        .map_err(|e| e.to_string())?;
    service
        .lock()
        .await
        .acknowledge_update_reload(&cache_dir, loaded_bundle_build)
        .await
        .map_err(|e| e.to_string())
}

/// Trigger a manual check for bundle updates.
#[tauri::command]
pub async fn check_for_update(
    service: tauri::State<'_, Mutex<PluginService>>,
) -> Result<(), String> {
    let service = service.lock().await;
    service.start().map_err(|e| e.to_string())
}

/// Return the current bundle update status as a serializable event.
#[tauri::command]
pub async fn get_bundle_update_status(
    service: tauri::State<'_, Mutex<PluginService>>,
) -> Result<BundleUpdateEvent, String> {
    let service = service.lock().await;
    let status = service.status().borrow();
    Ok(BundleUpdateEvent::new(&status))
}

/// Return debug metadata for the currently effective JavaScript bundle.
#[tauri::command]
pub async fn get_bundle_debug_info(
    service: tauri::State<'_, Mutex<PluginService>>,
) -> Result<BundleDebugInfo, String> {
    let service = service.lock().await;
    let embedded_bundle_build = service.embedded_bundle_build();
    let cached_bundle_build = service.bundle_build().await;
    Ok(BundleDebugInfo {
        bundle_build: cached_bundle_build.unwrap_or(embedded_bundle_build),
        source: if cached_bundle_build.is_some() {
            BundleDebugSource::Ota
        } else {
            BundleDebugSource::Embedded
        },
        native_build: service.native_build(),
    })
}

/// Clear the downloaded bundle and revert to built-in assets.
#[tauri::command]
pub async fn clear_bundle<R: Runtime>(
    service: tauri::State<'_, Mutex<PluginService>>,
    app_handle: tauri::AppHandle<R>,
) -> Result<(), String> {
    let cache_dir = app_handle
        .path()
        .app_cache_dir()
        .map_err(|e| e.to_string())?;

    let mut service = service.lock().await;
    let apply_result = {
        let result = service
            .revert_to_embedded(&cache_dir)
            .await
            .map_err(|e| e.to_string())?;
        if result == ApplyUpdateResult::ReloadNeeded {
            service.mark_update_reload_dispatched();
        }
        result
    };

    if apply_result == ApplyUpdateResult::ReloadNeeded {
        if let Some(webview) = app_handle.webview_windows().values().next() {
            record_reload_dispatch(&app_handle, "clear_bundle");
            if let Err(error) = webview.eval("window.location.reload();") {
                tracing::warn!(error=?error, "[bundle-update] failed to reload after clearing bundle");
                service.unmark_update_reload_dispatched();
            }
        } else {
            tracing::warn!("[bundle-update] bundle cleared but no webview was available to reload");
            service.unmark_update_reload_dispatched();
        }
    }
    Ok(())
}

impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
    fn name(&self) -> &'static str {
        "macro-bundle-updater"
    }

    fn initialize(
        &mut self,
        app: &tauri::AppHandle<R>,
        config: serde_json::Value,
    ) -> Result<(), Box<dyn std::error::Error>> {
        app.manage(std::sync::Mutex::new(BundleReloadDiagnostics::default()));
        let client = BundleClient::new(self.base_url.clone());
        let fs = FileSystem;
        // Desktop release builds embed their compatibility number in Tauri config.
        // Mobile continues to use CFBundleVersion / Android versionCode.
        let native_build = if cfg!(not(any(target_os = "ios", target_os = "android"))) {
            config
                .get("nativeBuild")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0)
        } else {
            native_build()
        };
        let system_info = SystemInfo::new(app.clone(), native_build);

        let mut service = Service::new::<_, _, TauriTaskSpawner>(
            client,
            fs,
            system_info,
            self.embedded_bundle_build,
            native_build,
            self.bundle_routes.clone(),
        );
        let mut acknowledge_setup_apply = false;
        let mut start_update_check = false;
        if !self.auto_update {
            tracing::info!("[bundle-update] automatic bundle updates are disabled in this build");
        } else if let Ok(cache_dir) = app.path().app_cache_dir() {
            let restored_pending = tauri::async_runtime::block_on(async {
                service.load_bundle_root(&cache_dir, native_build).await
            });
            if restored_pending {
                match tauri::async_runtime::block_on(async {
                    service.apply_update(&cache_dir).await
                }) {
                    Ok(ApplyUpdateResult::ReloadNeeded) => {
                        acknowledge_setup_apply = true;
                    }
                    Ok(ApplyUpdateResult::ReloadAlreadyDispatched) => {
                        acknowledge_setup_apply = true;
                    }
                    Ok(ApplyUpdateResult::NoUpdate | ApplyUpdateResult::Held) => {
                        tracing::warn!(
                            "[bundle-update] restored pending bundle had no update to apply during plugin initialization"
                        );
                        start_update_check = true;
                    }
                    Err(e) => {
                        tracing::error!(
                            "[bundle-update] failed to apply restored pending bundle during plugin initialization: {e}"
                        );
                        start_update_check = true;
                    }
                }
            } else {
                start_update_check = true;
            }
        } else {
            tracing::warn!(
                "[bundle-update] failed to read app cache dir during plugin initialization"
            );
            start_update_check = true;
        }
        let mut status_rx = service.status().clone();
        let mut wifi_retry_status_rx = service.status().clone();

        app.manage(tokio::sync::Mutex::new(service));
        if acknowledge_setup_apply || start_update_check {
            let Some(service_state) = app.try_state::<Mutex<PluginService>>() else {
                tracing::warn!(
                    "[bundle-update] plugin service state unavailable during initialization"
                );
                return Ok(());
            };
            let Ok(mut service) = service_state.try_lock() else {
                tracing::warn!("[bundle-update] plugin service state locked during initialization");
                return Ok(());
            };
            if acknowledge_setup_apply {
                match app.path().app_cache_dir() {
                    Ok(cache_dir) => {
                        let loaded_bundle_build =
                            tauri::async_runtime::block_on(service.bundle_build())
                                .unwrap_or(service.embedded_bundle_build());
                        if let Err(e) = tauri::async_runtime::block_on(
                            service.acknowledge_update_reload(&cache_dir, loaded_bundle_build),
                        ) {
                            tracing::warn!(
                                "[bundle-update] failed to acknowledge plugin-initialized bundle apply: {e}"
                            );
                        }
                    }
                    Err(e) => tracing::warn!(
                        "[bundle-update] failed to read cache dir for setup acknowledgement: {e}"
                    ),
                }
            } else if let Err(e) = service.start() {
                tracing::warn!(
                    "[bundle-update] failed to start update check during plugin initialization: {e}"
                );
            }
        }

        let app_handle = app.clone();
        tauri::async_runtime::spawn(async move {
            // Emit current state before waiting for changes
            {
                let event = status_rx.borrow_and_update();
                let _ = app_handle.emit(EVENT_NAME, BundleUpdateEvent::new(&event));
            }
            loop {
                if status_rx.changed().await.is_err() {
                    tracing::error!("The sender handle was dropped unexpectedly");
                    break;
                }
                let event = status_rx.borrow_and_update();
                let _ = app_handle.emit(EVENT_NAME, BundleUpdateEvent::new(&event));
            }
        });

        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) | 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(())
    }
}