A free, open source, and extensible speech-to-text application that works completely offline.
use SMAppService so Login Items shows Handy (#1825)
CJ Pais0902937bb179
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex e34f3791..3b482a39 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2468,6 +2468,7 @@ dependencies = ["objc2","objc2-app-kit","objc2-foundation",+ "objc2-service-management","once_cell","rdev","regex",@@ -3973,6 +3974,30 @@ dependencies = ["objc2-foundation",]+[[package]]+name = "objc2-security"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"+dependencies = [+ "bitflags 2.11.0",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-service-management"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b213642d6959cc6023ceb1217aa595eaaf09b8094ce95127c103cab611fe65e8"+dependencies = [+ "block2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-security",+]+[[package]]name = "objc2-ui-kit"version = "0.3.2"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 69342233..fb506dc0 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -141,11 +141,12 @@ transcribe-cpp = { version = "0.1.3", default-features = false, features = [transcribe-cpp = { version = "0.1.3", default-features = false }[target.'cfg(target_os = "macos")'.dependencies]+objc2 = "0.6"+objc2-service-management = "0.3.2"tauri-nspanel = { git = "https://github.com/ahkohd/tauri-nspanel", branch = "v2.1" }transcribe-cpp = { version = "0.1.3", default-features = false, features = ["metal"] }# Used by the receipt-sequenced ("reliable") paste path for lazy NSPasteboard-# promises. Versions track what Tauri already pulls in.-objc2 = "0.6"+# promises (objc2 above is shared). Versions track what Tauri already pulls in.objc2-foundation = "0.3"objc2-app-kit = "0.3"diff --git a/src-tauri/src/autostart.rs b/src-tauri/src/autostart.rsnew file mode 100644index 00000000..bd20b5cf--- /dev/null+++ b/src-tauri/src/autostart.rs@@ -0,0 +1,155 @@+//! Launch-at-login (autostart) handling.+//!+//! All platforms apply the setting through tauri-plugin-autostart, except+//! macOS 13+ where the app registers itself as a login item via+//! `SMAppService`. The plugin's launch agent plist carries no app+//! association, so the System Settings Login Items pane attributes it to the+//! code-signing certificate's developer name instead of the app (#337).+//! `SMAppService` login items are attributed to the app bundle itself and+//! appear under "Open at Login" with the app's name and icon.++use tauri::AppHandle;+use tauri_plugin_autostart::ManagerExt;++/// Apply the user's autostart preference using the best mechanism for the+/// current platform.+///+/// Errors are logged rather than returned: the preference is re-applied on+/// every launch, so a transient failure self-heals and must not block+/// startup. This mirrors the pre-existing behavior of ignoring+/// enable()/disable() results.+pub fn apply_autostart(app: &AppHandle, enabled: bool) {+ #[cfg(target_os = "macos")]+ if macos::login_item_api_available() {+ macos::remove_plugin_launch_agent(app);+ macos::set_login_item(enabled);+ return;+ }++ let manager = app.autolaunch();+ let result = if enabled {+ manager.enable()+ } else {+ manager.disable()+ };+ if let Err(e) = result {+ log::warn!(+ "Failed to apply autostart setting (enabled={}): {}",+ enabled,+ e+ );+ }+}++#[cfg(target_os = "macos")]+mod macos {+ use std::path::{Path, PathBuf};++ use objc2::runtime::AnyClass;+ use objc2_service_management::{SMAppService, SMAppServiceStatus};+ use tauri::{AppHandle, Manager};++ /// `SMAppService` requires macOS 13. The ServiceManagement framework is+ /// linked unconditionally (it has existed since 10.6), so looking up the+ /// class doubles as the OS version check: present exactly when the API is+ /// usable.+ pub fn login_item_api_available() -> bool {+ AnyClass::get(c"SMAppService").is_some()+ }++ /// Register or unregister the app as a login item, skipping the call when+ /// the service is already in the requested state (unregistering a+ /// never-registered service returns an error on every launch otherwise).+ pub fn set_login_item(enabled: bool) {+ let service = unsafe { SMAppService::mainAppService() };+ let status = unsafe { service.status() };++ if enabled {+ if status == SMAppServiceStatus::Enabled {+ return;+ }+ match unsafe { service.registerAndReturnError() } {+ Ok(()) => log::info!("Registered login item via SMAppService"),+ // Fails in dev (no signed app bundle) and when the user has+ // switched the item off in System Settings, which apps are+ // not allowed to override.+ Err(e) => log::warn!("Failed to register login item: {}", e),+ }+ } else {+ if status == SMAppServiceStatus::NotRegistered || status == SMAppServiceStatus::NotFound+ {+ return;+ }+ match unsafe { service.unregisterAndReturnError() } {+ Ok(()) => log::info!("Unregistered login item via SMAppService"),+ Err(e) => log::warn!("Failed to unregister login item: {}", e),+ }+ }+ }++ /// Remove the launch agent plist that tauri-plugin-autostart (via the+ /// auto-launch crate) wrote on older versions, so login doesn't start the+ /// app twice after migrating to `SMAppService`. Runs on every launch;+ /// missing file is the normal case.+ pub fn remove_plugin_launch_agent(app: &AppHandle) {+ let Ok(home) = app.path().home_dir() else {+ return;+ };+ remove_launch_agent_file(&plugin_launch_agent_path(&home, &app.package_info().name));+ }++ /// Path of the plist the auto-launch crate writes:+ /// `~/Library/LaunchAgents/{app name}.plist`.+ fn plugin_launch_agent_path(home: &Path, app_name: &str) -> PathBuf {+ home.join("Library")+ .join("LaunchAgents")+ .join(format!("{}.plist", app_name))+ }++ fn remove_launch_agent_file(path: &Path) {+ match std::fs::remove_file(path) {+ Ok(()) => log::info!("Removed legacy autostart launch agent {:?}", path),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => log::warn!("Failed to remove legacy launch agent {:?}: {}", path, e),+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ /// Validates the assumption `login_item_api_available` rests on: the+ /// ServiceManagement framework is linked into the binary, so the+ /// class lookup finds `SMAppService` whenever the host is macOS 13++ /// (which anything able to build this crate is).+ #[test]+ fn sm_app_service_class_resolves() {+ assert!(login_item_api_available());+ }++ #[test]+ fn launch_agent_path_matches_auto_launch_crate() {+ let path = plugin_launch_agent_path(Path::new("/Users/someone"), "Handy");+ assert_eq!(+ path,+ Path::new("/Users/someone/Library/LaunchAgents/Handy.plist")+ );+ }++ #[test]+ fn removes_existing_launch_agent() {+ let dir = tempfile::tempdir().unwrap();+ let plist = dir.path().join("Handy.plist");+ std::fs::write(&plist, "<plist/>").unwrap();++ remove_launch_agent_file(&plist);+ assert!(!plist.exists());+ }++ #[test]+ fn missing_launch_agent_is_a_no_op() {+ let dir = tempfile::tempdir().unwrap();+ remove_launch_agent_file(&dir.path().join("Handy.plist"));+ }+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5bfcfbeb..c4bdb7e9 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -3,6 +3,7 @@ mod actions;mod apple_intelligence;mod audio_feedback;pub mod audio_toolkit;+mod autostart;mod catalog;pub mod cli;mod clipboard;@@ -40,7 +41,7 @@ pub use transcription_coordinator::TranscriptionCoordinator;use tauri::tray::TrayIconBuilder;use tauri::{AppHandle, Emitter, Listener, Manager};-use tauri_plugin_autostart::{MacosLauncher, ManagerExt};+use tauri_plugin_autostart::MacosLauncher;use tauri_plugin_log::{Builder as LogBuilder, RotationStrategy, Target, TargetKind};use crate::settings::get_settings;@@ -327,17 +328,9 @@ fn initialize_core_logic(app_handle: &AppHandle) {tray::update_tray_menu(&app_handle_for_listener, None);});- // Get the autostart manager and configure based on user setting- let autostart_manager = app_handle.autolaunch();- let settings = settings::get_settings(app_handle);-- if settings.autostart_enabled {- // Enable autostart if user has opted in- let _ = autostart_manager.enable();- } else {- // Disable autostart if user has opted out- let _ = autostart_manager.disable();- }+ // Apply the autostart preference (SMAppService login item on macOS 13+,+ // tauri-plugin-autostart elsewhere)+ autostart::apply_autostart(app_handle, settings.autostart_enabled);// Create the recording overlay window (hidden by default)utils::create_recording_overlay(app_handle);diff --git a/src-tauri/src/shortcut/mod.rs b/src-tauri/src/shortcut/mod.rsindex d69bc0ea..ff3bc01e 100644--- a/src-tauri/src/shortcut/mod.rs+++ b/src-tauri/src/shortcut/mod.rs@@ -17,7 +17,6 @@ use log::{debug, error, info, warn};use serde::Serialize;use specta::Type;use tauri::{AppHandle, Emitter, Manager};-use tauri_plugin_autostart::ManagerExt;#[cfg(all(target_os = "macos", target_arch = "aarch64"))]use crate::settings::APPLE_INTELLIGENCE_DEFAULT_MODEL_ID;@@ -727,12 +726,7 @@ pub fn change_autostart_setting(app: AppHandle, enabled: bool) -> Result<(), Strsettings::write_settings(&app, settings);// Apply the autostart setting immediately- let autostart_manager = app.autolaunch();- if enabled {- let _ = autostart_manager.enable();- } else {- let _ = autostart_manager.disable();- }+ crate::autostart::apply_autostart(&app, enabled);// Notify frontendlet _ = app.emit(