Skip to content

armgit / Handy

Public Imported from GitHub
0

A free, open source, and extensible speech-to-text application that works completely offline.

single writer tray icon (#1952)

CJ Pais5ec2276a40dd
diff --git a/src-tauri/src/actions.rs b/src-tauri/src/actions.rs
index bdf05f12..9f7533bc 100644
--- a/src-tauri/src/actions.rs
+++ b/src-tauri/src/actions.rs
@@ -9,7 +9,7 @@ use crate::managers::transcription::StreamWorkKind;
use crate::managers::transcription::TranscriptionManager;
use crate::settings::{get_settings, AppSettings, OverlayStyle, APPLE_INTELLIGENCE_PROVIDER_ID};
use crate::shortcut;
-use crate::tray::{change_tray_icon, TrayIconState};
+use crate::tray::{set_tray_state, TrayIconState};
use crate::utils::{
self, show_processing_overlay, show_recording_overlay, show_transcribing_overlay,
};
@@ -487,7 +487,7 @@ impl ShortcutAction for TranscribeAction {
let binding_id = binding_id.to_string();
let tray_started = Instant::now();
- change_tray_icon(app, TrayIconState::Recording);
+ set_tray_state(app, TrayIconState::Recording);
let tray_elapsed = tray_started.elapsed();
// Get the microphone mode to determine audio feedback timing
@@ -604,7 +604,7 @@ impl ShortcutAction for TranscribeAction {
// Revert UI state so we don't stay stuck in the recording overlay.
tm.cancel_stream();
utils::hide_recording_overlay(app);
- change_tray_icon(app, TrayIconState::Idle);
+ set_tray_state(app, TrayIconState::Idle);
if let Some(err) = recording_error {
let error_type = if is_microphone_access_denied(&err) {
"microphone_permission_denied"
@@ -646,7 +646,7 @@ impl ShortcutAction for TranscribeAction {
let tm = Arc::clone(&app.state::<Arc<TranscriptionManager>>());
let hm = Arc::clone(&app.state::<Arc<HistoryManager>>());
- change_tray_icon(app, TrayIconState::Transcribing);
+ set_tray_state(app, TrayIconState::Transcribing);
// Stop should give immediate visual feedback. Live streaming can keep
// the larger panel, but it still switches from listening to a working
// spinner while the stream finalizes. Non-streaming paths use the
@@ -690,7 +690,7 @@ impl ShortcutAction for TranscribeAction {
debug!("Transcription operation cancelled after recording stop");
tm.cancel_stream();
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
return;
}
@@ -700,7 +700,7 @@ impl ShortcutAction for TranscribeAction {
// and block the next start_stream.
tm.cancel_stream();
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
} else {
// Save WAV concurrently with transcription
let sample_count = samples.len();
@@ -755,7 +755,7 @@ impl ShortcutAction for TranscribeAction {
if rm.was_cancelled_since(cancel_generation) {
debug!("Transcription operation cancelled before output handling");
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
return;
}
@@ -782,14 +782,14 @@ impl ShortcutAction for TranscribeAction {
else {
debug!("Transcription operation cancelled during output handling");
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
return;
};
if rm.was_cancelled_since(cancel_generation) {
debug!("Transcription operation cancelled before paste");
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
return;
}
@@ -808,7 +808,7 @@ impl ShortcutAction for TranscribeAction {
if processed.final_text.is_empty() {
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
} else {
let ah_clone = ah.clone();
let paste_time = Instant::now();
@@ -818,7 +818,7 @@ impl ShortcutAction for TranscribeAction {
if rm_for_paste.was_cancelled_since(cancel_generation) {
debug!("Transcription operation cancelled before paste");
utils::hide_recording_overlay(&ah_clone);
- change_tray_icon(&ah_clone, TrayIconState::Idle);
+ set_tray_state(&ah_clone, TrayIconState::Idle);
return;
}
@@ -833,12 +833,12 @@ impl ShortcutAction for TranscribeAction {
}
}
utils::hide_recording_overlay(&ah_clone);
- change_tray_icon(&ah_clone, TrayIconState::Idle);
+ set_tray_state(&ah_clone, TrayIconState::Idle);
})
.unwrap_or_else(|e| {
error!("Failed to run paste on main thread: {:?}", e);
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
});
}
}
@@ -848,7 +848,7 @@ impl ShortcutAction for TranscribeAction {
"Transcription operation cancelled after transcription error"
);
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
return;
}
@@ -869,7 +869,7 @@ impl ShortcutAction for TranscribeAction {
}
}
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
}
}
}
@@ -878,7 +878,7 @@ impl ShortcutAction for TranscribeAction {
// Tear down any streaming worker so its channel doesn't leak.
tm.cancel_stream();
utils::hide_recording_overlay(&ah);
- change_tray_icon(&ah, TrayIconState::Idle);
+ set_tray_state(&ah, TrayIconState::Idle);
}
});
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 5c00deb7..ec93568a 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -180,7 +180,7 @@ fn initialize_core_logic(app_handle: &AppHandle) {
app_handle.manage(model_manager.clone());
app_handle.manage(transcription_manager.clone());
app_handle.manage(history_manager.clone());
- app_handle.manage(tray::CurrentTrayIconState::new());
+ app_handle.manage(tray::TrayState::new());
// Note: Shortcuts are NOT initialized here.
// The frontend is responsible for calling the `initialize_shortcuts` command
@@ -305,7 +305,7 @@ fn initialize_core_logic(app_handle: &AppHandle) {
log::error!("Failed to switch model via tray: {}", e);
}
}
- tray::update_tray_menu(&app_clone, None);
+ tray::update_tray_menu(&app_clone);
});
}
_ => {}
@@ -315,7 +315,7 @@ fn initialize_core_logic(app_handle: &AppHandle) {
app_handle.manage(tray);
// Initialize tray menu with idle state
- utils::update_tray_menu(app_handle, None);
+ tray::update_tray_menu(app_handle);
// Apply show_tray_icon setting
let settings = settings::get_settings(app_handle);
@@ -326,7 +326,7 @@ fn initialize_core_logic(app_handle: &AppHandle) {
// Refresh tray menu when model state changes
let app_handle_for_listener = app_handle.clone();
app_handle.listen("model-state-changed", move |_| {
- tray::update_tray_menu(&app_handle_for_listener, None);
+ tray::update_tray_menu(&app_handle_for_listener);
});
// Apply the autostart preference (SMAppService login item on macOS 13+,
@@ -821,6 +821,14 @@ pub fn run(cli_args: CliArgs) {
} else if args.iter().any(|a| a == "--cancel") {
crate::utils::cancel_current_operation(app);
} else {
+ // A second process was launched without remote-control flags
+ // (e.g. the binary run from a shell). On macOS, relaunching the
+ // bundle from Spotlight/Finder/Dock does not start a process —
+ // it arrives as RunEvent::Reopen below — but treat this the
+ // same way: raise the window and recreate a possibly vanished
+ // tray icon (#1948).
+ #[cfg(target_os = "macos")]
+ tray::recreate_tray_icon(app);
show_main_window(app);
}
}));
@@ -1008,6 +1016,19 @@ pub fn run(cli_args: CliArgs) {
.run(|app, event| match &event {
#[cfg(target_os = "macos")]
tauri::RunEvent::Reopen { .. } => {
+ // Fired when the already-running bundle is launched again from
+ // Spotlight/Finder or the Dock icon is clicked. If the settings
+ // window is hidden, the user is likely looking for a tray icon
+ // that vanished (#1948): recreate it. When the window is
+ // already visible this is just a focus request and the tray is
+ // left alone.
+ let window_visible = app
+ .get_webview_window("main")
+ .and_then(|w| w.is_visible().ok())
+ .unwrap_or(false);
+ if !window_visible {
+ tray::recreate_tray_icon(app);
+ }
show_main_window(app);
}
// Teardown transcribe.cpp before exit
diff --git a/src-tauri/src/secure_input.rs b/src-tauri/src/secure_input.rs
index 17afe010..ae421fd0 100644
--- a/src-tauri/src/secure_input.rs
+++ b/src-tauri/src/secure_input.rs
@@ -286,10 +286,9 @@ mod imp {
}
fn refresh_tray(app: &AppHandle) {
- // Tray may be absent (--no-tray)
- if app.try_state::<tauri::tray::TrayIcon>().is_some() {
- crate::tray::refresh_tray_icon(app);
- }
+ // No-op before the tray is built; otherwise a diffed, coalesced,
+ // main-thread apply that never blocks this thread.
+ crate::tray::refresh_tray_icon(app);
}
pub fn start_monitor(app: &AppHandle) {
@@ -320,11 +319,6 @@ mod imp {
}
if !now_enabled {
- // Capture this before clearing the state. Once `sustained`
- // becomes false, warning_active() can no longer tell us that
- // the tray is still displaying the previous warning.
- let warning_was_active = state.warning_active();
-
// Clear recorder impact on every disabled sample. A short
// Secure Input episode can otherwise occur entirely
// between polls and leave this flag latched indefinitely.
@@ -337,12 +331,6 @@ mod imp {
if state.sustained.swap(false, Ordering::SeqCst) {
reconcile_fallback(&app);
- // reconcile_fallback snapshots warning state after the
- // sustained flag changed, so explicitly clear a warning
- // that was visible before deactivation.
- if warning_was_active {
- refresh_tray(&app);
- }
} else if was_enabled || was_blocked {
refresh_tray(&app);
emit_status(&app);
@@ -488,7 +476,6 @@ mod imp {
pub fn reconcile_fallback(app: &AppHandle) {
let state = app.state::<SecureInputState>();
let _operation = state.fallback_operation.lock().unwrap();
- let warning_was_active = state.warning_active();
let previous = {
let mut fallback = state.fallback.lock().unwrap();
@@ -550,16 +537,12 @@ mod imp {
}
*state.fallback.lock().unwrap() = next;
- let warning_is_active = state.warning_active();
drop(_operation);
- // The tray only reflects whether user-visible impact exists; covered
- // bindings and other fallback details are reported through the event.
- // Avoid rebuilding the native tray menu when its visible state did not
- // change, especially during recording lifecycle reconciliation.
- if warning_was_active != warning_is_active {
- refresh_tray(app);
- }
+ // The tray sync diffs against what is displayed, so this is free when
+ // the warning state did not change. Lock is released first: the sync
+ // reads app state and must not nest under the operation mutex.
+ refresh_tray(app);
emit_status(app);
}
diff --git a/src-tauri/src/shortcut/mod.rs b/src-tauri/src/shortcut/mod.rs
index 57ae254b..1a1e76aa 100644
--- a/src-tauri/src/shortcut/mod.rs
+++ b/src-tauri/src/shortcut/mod.rs
@@ -1287,7 +1287,7 @@ pub fn change_app_language_setting(app: AppHandle, language: String) -> Result<(
settings::write_settings(&app, settings);
// Refresh the tray menu with the new language
- tray::update_tray_menu(&app, Some(&language));
+ tray::update_tray_menu(&app);
Ok(())
}
diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs
index b4841944..aba2f045 100644
--- a/src-tauri/src/tray.rs
+++ b/src-tauri/src/tray.rs
@@ -1,38 +1,128 @@
+//! System tray icon and menu.
+//!
+//! The tray is driven by a single *desired state* snapshot ([`TrayDesired`])
+//! that callers update through [`set_tray_state`], [`refresh_tray_icon`] and
+//! [`update_tray_menu`]. Every such call just records intent and schedules a
+//! single applier on the main thread, which diffs the desired snapshot against
+//! what is currently displayed and touches the native tray only for the parts
+//! that actually changed. Requests that arrive while an apply is pending are
+//! coalesced into it, so bursts of state changes never queue up native work.
+//!
+//! Why: native tray updates are the lever we control for the macOS tray
+//! disappearance bug (tauri-apps/tauri#12060, Handy #1948). Before this, every
+//! recording cycle rebuilt the full menu 3-6 times from several threads, and
+//! concurrent rebuilds could interleave and leave a stale menu behind.
+//!
+//! Exception: [`set_tray_visibility`] and [`recreate_tray_icon`] call the tray
+//! directly. Visibility is a separate attribute that never participates in the
+//! icon/menu diff, both are rare and user-initiated, and Tauri marshals them
+//! onto the main thread so they serialize with the applier anyway. Re-showing
+//! a hidden tray relies on tray-icon recreating it from the last applied
+//! icon/menu/tooltip, so those must only ever be set through the applier.
+
use crate::managers::history::{HistoryEntry, HistoryManager};
use crate::managers::model::ModelManager;
use crate::managers::transcription::TranscriptionManager;
use crate::settings;
use crate::tray_i18n::get_tray_translations;
-use log::{debug, error, info, warn};
+use log::{debug, error, info, trace, warn};
+use std::collections::HashMap;
use std::path::PathBuf;
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, MutexGuard};
+use std::time::Instant;
use tauri::image::Image;
use tauri::menu::{CheckMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
use tauri::tray::TrayIcon;
use tauri::{AppHandle, Manager, Theme};
use tauri_plugin_clipboard_manager::ClipboardExt;
-#[derive(Clone, Copy, Debug, PartialEq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrayIconState {
Idle,
Recording,
Transcribing,
}
-/// Tauri managed state holding the last icon state set via `change_tray_icon`.
-pub struct CurrentTrayIconState(pub Mutex<TrayIconState>);
+impl TrayIconState {
+ /// Recording and Transcribing share the same menu ("Cancel" instead of the
+ /// model submenu), so only the idle/busy distinction matters for the menu.
+ fn is_busy(self) -> bool {
+ self != TrayIconState::Idle
+ }
+}
+
+/// Everything the tray *menu* (and tooltip) depends on. When two snapshots
+/// compare equal the menu is not rebuilt.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct MenuInputs {
+ busy: bool,
+ warning: bool,
+ model_loaded: bool,
+ selected_model: String,
+ /// `(id, name)` of downloaded models, sorted by name.
+ downloaded_models: Vec<(String, String)>,
+ locale: String,
+ update_checks_enabled: bool,
+}
+
+/// Complete description of what the tray should look like.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct TrayDesired {
+ icon_path: &'static str,
+ menu: MenuInputs,
+}
-impl CurrentTrayIconState {
+struct TrayInner {
+ /// Intent set by [`set_tray_state`].
+ icon_state: TrayIconState,
+ /// Latest computed snapshot, waiting to be (or just) applied.
+ desired: Option<TrayDesired>,
+ /// Icon the native tray currently shows. Only updated when `set_icon`
+ /// succeeds, so a failed update is retried on the next sync.
+ applied_icon: Option<&'static str>,
+ /// Inputs the native menu was last successfully built from. The tooltip
+ /// is derived from the same inputs and set best-effort alongside the menu;
+ /// it is not tracked separately.
+ applied_menu: Option<MenuInputs>,
+ /// An apply is scheduled on the main thread.
+ pending: bool,
+ /// Decoded icons by resource path so the main thread never touches disk.
+ icons: HashMap<&'static str, Image<'static>>,
+ /// Handed out to each sync request in trigger order, so a slow request
+ /// can't overwrite the snapshot of one that was triggered after it.
+ next_seq: u64,
+ /// Sequence number of the request that produced `desired`.
+ desired_seq: u64,
+}
+
+/// Tauri managed state owning the tray's desired/applied snapshots.
+pub struct TrayState(Mutex<TrayInner>);
+
+impl TrayState {
pub fn new() -> Self {
- Self(Mutex::new(TrayIconState::Idle))
+ Self(Mutex::new(TrayInner {
+ icon_state: TrayIconState::Idle,
+ desired: None,
+ applied_icon: None,
+ applied_menu: None,
+ pending: false,
+ icons: HashMap::new(),
+ next_seq: 0,
+ desired_seq: 0,
+ }))
}
- pub fn get(&self) -> TrayIconState {
- *self.0.lock().unwrap()
+ fn lock(&self) -> MutexGuard<'_, TrayInner> {
+ self.0.lock().unwrap_or_else(|poisoned| {
+ warn!("Tray state mutex was poisoned, recovering");
+ poisoned.into_inner()
+ })
}
+}
- fn set(&self, state: TrayIconState) {
- *self.0.lock().unwrap() = state;
+impl Default for TrayState {
+ fn default() -> Self {
+ Self::new()
}
}
@@ -124,46 +214,226 @@ pub fn get_icon_path(theme: AppTheme, state: TrayIconState, warning: bool) -> &'
}
}
-pub fn change_tray_icon(app: &AppHandle, icon: TrayIconState) {
- let tray = app.state::<TrayIcon>();
- let theme = get_current_theme(app);
+/// Sets the recording state shown by the tray (icon + Cancel/model menu).
+pub fn set_tray_state(app: &AppHandle, state: TrayIconState) {
+ sync_tray_with(app, |inner| inner.icon_state = state);
+}
+
+/// Re-syncs the tray after something other than the recording state changed
+/// (theme, Secure Input warning). The recording state itself is preserved.
+pub fn refresh_tray_icon(app: &AppHandle) {
+ sync_tray(app);
+}
+
+/// Re-syncs the tray after something the menu depends on changed (model
+/// list/selection/loaded state, language, settings).
+pub fn update_tray_menu(app: &AppHandle) {
+ sync_tray(app);
+}
- // Store current state
- app.state::<CurrentTrayIconState>().set(icon);
+/// Records the current desired tray state and schedules one apply on the main
+/// thread (or lets an already-pending apply pick it up). Never blocks on the
+/// main thread.
+///
+/// The snapshot (settings, model list, loaded state) is computed on the
+/// *calling* thread on purpose: the main-thread applier must not take manager
+/// locks that a worker may hold across slow work (see #1716).
+pub fn sync_tray(app: &AppHandle) {
+ sync_tray_with(app, |_| {});
+}
+fn sync_tray_with(app: &AppHandle, update: impl FnOnce(&mut TrayInner)) {
+ let Some(state) = app.try_state::<TrayState>() else {
+ return;
+ };
+
+ // Record intent and claim a sequence number in one critical section, so
+ // sequence order == the order in which state changes were requested.
+ let (seq, icon_state) = {
+ let mut inner = state.lock();
+ update(&mut inner);
+ inner.next_seq += 1;
+ (inner.next_seq, inner.icon_state)
+ };
+
+ // Tray not built yet (early secure-input monitor callbacks). The intent
+ // is kept and picked up by the first sync after the tray exists.
+ if app.try_state::<TrayIcon>().is_none() {
+ return;
+ }
+
+ let desired = compute_desired(app, icon_state);
+
+ // Decode the icon off the main thread, once per path, outside the lock.
+ let needs_icon = !state.lock().icons.contains_key(desired.icon_path);
+ let loaded_icon = if needs_icon {
+ match load_tray_icon(
+ app.path()
+ .resolve(desired.icon_path, tauri::path::BaseDirectory::Resource),
+ ) {
+ Ok(image) => Some(image),
+ Err(err) => {
+ error!("Failed to load tray icon '{}': {err}", desired.icon_path);
+ None
+ }
+ }
+ } else {
+ None
+ };
+
+ let schedule = {
+ let mut inner = state.lock();
+ if let Some(image) = loaded_icon {
+ inner.icons.insert(desired.icon_path, image);
+ }
+ if seq < inner.desired_seq {
+ // A request triggered after this one already stored its snapshot
+ // (and scheduled an apply). Ours is stale; drop it.
+ trace!(
+ "tray sync: request {seq} superseded by {}",
+ inner.desired_seq
+ );
+ return;
+ }
+ inner.desired = Some(desired);
+ inner.desired_seq = seq;
+ // If an apply is already pending it will read the snapshot we just
+ // stored; otherwise schedule one.
+ !std::mem::replace(&mut inner.pending, true)
+ };
+
+ if schedule {
+ post_apply(app);
+ } else {
+ trace!("tray sync: apply already pending");
+ }
+}
+
+fn compute_desired(app: &AppHandle, icon_state: TrayIconState) -> TrayDesired {
+ let settings = settings::get_settings(app);
+ let theme = get_current_theme(app);
let warning = crate::secure_input::tray_warning_active(app);
- let icon_path = get_icon_path(theme, icon, warning);
-
- let icon_started = std::time::Instant::now();
- if let Err(err) = load_tray_icon(
- app.path()
- .resolve(icon_path, tauri::path::BaseDirectory::Resource),
- )
- .and_then(|image| tray.set_icon_with_as_template(Some(image), true))
+ let model_loaded = app.state::<Arc<TranscriptionManager>>().is_model_loaded();
+
+ let mut downloaded_models: Vec<(String, String)> = app
+ .state::<Arc<ModelManager>>()
+ .get_available_models()
+ .into_iter()
+ .filter(|m| m.is_downloaded)
+ .map(|m| (m.id, m.name))
+ .collect();
+ downloaded_models.sort_by(|a, b| a.1.cmp(&b.1));
+
+ TrayDesired {
+ icon_path: get_icon_path(theme, icon_state, warning),
+ menu: MenuInputs {
+ busy: icon_state.is_busy(),
+ warning,
+ model_loaded,
+ selected_model: settings.selected_model,
+ downloaded_models,
+ locale: settings.app_language,
+ update_checks_enabled: settings.update_checks_enabled,
+ },
+ }
+}
+
+fn post_apply(app: &AppHandle) {
+ let handle = app.clone();
+ if let Err(err) = app.run_on_main_thread(move || apply_on_main(&handle)) {
+ // Event loop is gone (shutdown). Clear `pending` so a later call, if
+ // any, doesn't wait forever for an apply that will never run.
+ error!("Failed to dispatch tray update to the main thread: {err}");
+ if let Some(state) = app.try_state::<TrayState>() {
+ state.lock().pending = false;
+ }
+ }
+}
+
+/// The single writer to the native tray. Runs on the main thread.
+fn apply_on_main(app: &AppHandle) {
+ let Some(state) = app.try_state::<TrayState>() else {
+ return;
+ };
+ let Some(tray) = app.try_state::<TrayIcon>() else {
+ return;
+ };
+
+ let started = Instant::now();
+ let (desired, icon, icon_changed, menu_changed) = {
+ let mut inner = state.lock();
+ inner.pending = false;
+ let Some(desired) = inner.desired.clone() else {
+ return;
+ };
+ let icon_changed = inner.applied_icon != Some(desired.icon_path);
+ let menu_changed = inner.applied_menu.as_ref() != Some(&desired.menu);
+ if !icon_changed && !menu_changed {
+ trace!("tray apply: nothing changed");
+ return;
+ }
+ let icon = inner.icons.get(desired.icon_path).cloned();
+ (desired, icon, icon_changed, menu_changed)
+ };
+
+ // Each part is recorded as applied only if its native call succeeded, so a
+ // transient failure is retried on the next sync instead of being
+ // remembered as displayed.
+ let mut icon_ok = false;
+ if icon_changed {
+ match icon {
+ Some(image) => match tray.set_icon_with_as_template(Some(image), true) {
+ Ok(()) => icon_ok = true,
+ Err(err) => error!("Failed to update tray icon '{}': {err}", desired.icon_path),
+ },
+ None => error!("Tray icon '{}' is not loaded", desired.icon_path),
+ }
+ }
+
+ let mut menu_ok = false;
+ if menu_changed {
+ match build_menu(app, &desired.menu) {
+ Ok((menu, tooltip)) => match tray.set_menu(Some(menu)) {
+ Ok(()) => {
+ menu_ok = true;
+ // Best-effort: logged, not retried. The tooltip is cosmetic
+ // and can only fail on Windows, where a failing
+ // Shell_NotifyIcon call means the icon is failing too.
+ // Gating `menu_ok` on it would re-run the full menu
+ // rebuild on every sync for the cheapest mutation.
+ if let Err(err) = tray.set_tooltip(Some(tooltip)) {
+ error!("Failed to set tray tooltip: {err}");
+ }
+ }
+ Err(err) => error!("Failed to set tray menu: {err}"),
+ },
+ Err(err) => error!("Failed to build tray menu: {err}"),
+ }
+ }
+
{
- error!("Failed to update tray icon '{icon_path}': {err}");
+ let mut inner = state.lock();
+ if icon_ok {
+ inner.applied_icon = Some(desired.icon_path);
+ }
+ if menu_ok {
+ inner.applied_menu = Some(desired.menu.clone());
+ }
}
- let icon_elapsed = icon_started.elapsed();
- // Update menu based on state
- let menu_started = std::time::Instant::now();
- update_tray_menu(app, None);
debug!(
- "tray icon change ({:?}): icon={} set_icon={:?} menu={:?}",
- icon,
- icon_path,
- icon_elapsed,
- menu_started.elapsed()
+ "tray apply: icon={} menu={} busy={} took={:?}",
+ if icon_changed {
+ desired.icon_path
+ } else {
+ "unchanged"
+ },
+ if menu_changed { "rebuilt" } else { "unchanged" },
+ desired.menu.busy,
+ started.elapsed()
);
}
-/// Re-applies the last known tray state — for when only the *theme* changed
-/// and the state itself (idle/recording/transcribing) should be preserved.
-pub fn refresh_tray_icon(app: &AppHandle) {
- let icon = app.state::<CurrentTrayIconState>().get();
- change_tray_icon(app, icon);
-}
-
fn load_tray_icon(resolved_icon_path: tauri::Result<PathBuf>) -> tauri::Result<Image<'static>> {
let resolved_icon_path = resolved_icon_path?;
Image::from_path(&resolved_icon_path).map(Image::to_owned)
@@ -181,26 +451,31 @@ fn version_label() -> String {
}
}
-pub fn update_tray_menu(app: &AppHandle, locale: Option<&str>) {
- let state = app.state::<CurrentTrayIconState>().get();
- let settings = settings::get_settings(app);
-
- let locale = locale.unwrap_or(&settings.app_language);
- let strings = get_tray_translations(Some(locale.to_string()));
+/// Builds the tray menu and tooltip for the given inputs. Pure with respect
+/// to app state: everything it depends on is in `inputs`.
+fn build_menu(app: &AppHandle, inputs: &MenuInputs) -> tauri::Result<(Menu<tauri::Wry>, String)> {
+ let strings = get_tray_translations(Some(inputs.locale.clone()));
// Secure Input warning entry (macOS): clicking opens the settings window
// where the full warning banner explains the situation. Locales that
// haven't translated the key yet get the English string rather than a
// blank menu item (build.rs emits "" for missing keys).
- let secure_input_warning = crate::secure_input::tray_warning_active(app).then(|| {
+ let secure_input_warning = if inputs.warning {
let label = if strings.secure_input_warning.is_empty() {
get_tray_translations(Some("en".to_string())).secure_input_warning
} else {
strings.secure_input_warning.clone()
};
- MenuItem::with_id(app, "secure_input_warning", &label, true, None::<&str>)
- .expect("failed to create secure input warning item")
- });
+ Some(MenuItem::with_id(
+ app,
+ "secure_input_warning",
+ &label,
+ true,
+ None::<&str>,
+ )?)
+ } else {
+ None
+ };
// Platform-specific accelerators
#[cfg(target_os = "macos")]
@@ -210,128 +485,101 @@ pub fn update_tray_menu(app: &AppHandle, locale: Option<&str>) {
// Create common menu items
let version_label = version_label();
- let version_i = MenuItem::with_id(app, "version", &version_label, false, None::<&str>)
- .expect("failed to create version item");
+ let version_i = MenuItem::with_id(app, "version", &version_label, false, None::<&str>)?;
let settings_i = MenuItem::with_id(
app,
"settings",
&strings.settings,
true,
settings_accelerator,
- )
- .expect("failed to create settings item");
+ )?;
let check_updates_i = MenuItem::with_id(
app,
"check_updates",
&strings.check_updates,
- settings.update_checks_enabled,
+ inputs.update_checks_enabled,
None::<&str>,
- )
- .expect("failed to create check updates item");
+ )?;
let copy_last_transcript_i = MenuItem::with_id(
app,
"copy_last_transcript",
&strings.copy_last_transcript,
true,
None::<&str>,
- )
- .expect("failed to create copy last transcript item");
- let model_loaded = app.state::<Arc<TranscriptionManager>>().is_model_loaded();
- let quit_i = MenuItem::with_id(app, "quit", &strings.quit, true, quit_accelerator)
- .expect("failed to create quit item");
- let separator = || PredefinedMenuItem::separator(app).expect("failed to create separator");
-
- // Build model submenu — label is the active model name
- let model_manager = app.state::<Arc<ModelManager>>();
- let models = model_manager.get_available_models();
- let current_model_id = &settings.selected_model;
-
- let mut downloaded: Vec<_> = models.into_iter().filter(|m| m.is_downloaded).collect();
- downloaded.sort_by(|a, b| a.name.cmp(&b.name));
-
- let submenu_label = downloaded
- .iter()
- .find(|m| m.id == *current_model_id)
- .map(|m| m.name.clone())
- .unwrap_or_else(|| strings.model.clone());
-
- let model_submenu = {
- let submenu = Submenu::with_id(app, "model_submenu", &submenu_label, true)
- .expect("failed to create model submenu");
-
- for model in &downloaded {
- let is_active = model.id == *current_model_id;
- let item_id = format!("model_select:{}", model.id);
- let item =
- CheckMenuItem::with_id(app, &item_id, &model.name, true, is_active, None::<&str>)
- .expect("failed to create model item");
- let _ = submenu.append(&item);
+ )?;
+ let quit_i = MenuItem::with_id(app, "quit", &strings.quit, true, quit_accelerator)?;
+ let separator = || PredefinedMenuItem::separator(app);
+
+ let menu = if inputs.busy {
+ let cancel_i = MenuItem::with_id(app, "cancel", &strings.cancel, true, None::<&str>)?;
+ Menu::with_items(
+ app,
+ &[
+ &version_i,
+ &separator()?,
+ &cancel_i,
+ &separator()?,
+ &copy_last_transcript_i,
+ &separator()?,
+ &settings_i,
+ &check_updates_i,
+ &separator()?,
+ &quit_i,
+ ],
+ )?
+ } else {
+ // Build model submenu — label is the active model name
+ let submenu_label = inputs
+ .downloaded_models
+ .iter()
+ .find(|(id, _)| *id == inputs.selected_model)
+ .map(|(_, name)| name.clone())
+ .unwrap_or_else(|| strings.model.clone());
+
+ let model_submenu = Submenu::with_id(app, "model_submenu", &submenu_label, true)?;
+ for (id, name) in &inputs.downloaded_models {
+ let is_active = *id == inputs.selected_model;
+ let item_id = format!("model_select:{}", id);
+ let item = CheckMenuItem::with_id(app, &item_id, name, true, is_active, None::<&str>)?;
+ model_submenu.append(&item)?;
}
- submenu
- };
+ let unload_model_i = MenuItem::with_id(
+ app,
+ "unload_model",
+ &strings.unload_model,
+ inputs.model_loaded,
+ None::<&str>,
+ )?;
- let unload_model_i = MenuItem::with_id(
- app,
- "unload_model",
- &strings.unload_model,
- model_loaded,
- None::<&str>,
- )
- .expect("failed to create unload model item");
-
- let menu = match state {
- TrayIconState::Recording | TrayIconState::Transcribing => {
- let cancel_i = MenuItem::with_id(app, "cancel", &strings.cancel, true, None::<&str>)
- .expect("failed to create cancel item");
- Menu::with_items(
- app,
- &[
- &version_i,
- &separator(),
- &cancel_i,
- &separator(),
- &copy_last_transcript_i,
- &separator(),
- &settings_i,
- &check_updates_i,
- &separator(),
- &quit_i,
- ],
- )
- .expect("failed to create menu")
- }
- TrayIconState::Idle => Menu::with_items(
+ Menu::with_items(
app,
&[
&version_i,
- &separator(),
+ &separator()?,
&copy_last_transcript_i,
- &separator(),
+ &separator()?,
&model_submenu,
&unload_model_i,
- &separator(),
+ &separator()?,
&settings_i,
&check_updates_i,
- &separator(),
+ &separator()?,
&quit_i,
],
- )
- .expect("failed to create menu"),
+ )?
};
// Both layouts start with [version, separator, ...]; slot the warning in
// right below the version line so it's the first actionable thing seen.
let mut tooltip = version_label;
if let Some(warning_item) = secure_input_warning {
- let _ = menu.insert(&warning_item, 2);
- let _ = menu.insert(&separator(), 3);
+ menu.insert(&warning_item, 2)?;
+ menu.insert(&separator()?, 3)?;
tooltip = format!("{} — {}", tooltip, warning_item.text().unwrap_or_default());
}
- let tray = app.state::<TrayIcon>();
- let _ = tray.set_menu(Some(menu));
- let _ = tray.set_tooltip(Some(tooltip));
+ Ok((menu, tooltip))
}
fn last_transcript_text(entry: &HistoryEntry) -> &str {
@@ -350,6 +598,31 @@ pub fn set_tray_visibility(app: &AppHandle, visible: bool) {
}
}
+/// Recovery for the macOS tray-disappearance bug (#1948, tauri-apps/tauri#12060):
+/// the `NSStatusItem` can silently vanish with no error surfaced to the app.
+/// Hiding and re-showing the tray recreates it with its current icon, menu and
+/// tooltip. Called when the user "relaunches" Handy while it is already running
+/// (`RunEvent::Reopen` for Spotlight/Finder/Dock, the single-instance callback
+/// for a second process) — the natural "where did my icon go?" moment — so a
+/// relaunch brings the icon back without a full quit.
+#[cfg(target_os = "macos")]
+pub fn recreate_tray_icon(app: &AppHandle) {
+ let no_tray = app
+ .try_state::<crate::cli::CliArgs>()
+ .map(|args| args.no_tray)
+ .unwrap_or(false);
+ if no_tray || !settings::get_settings(app).show_tray_icon {
+ return;
+ }
+ let Some(tray) = app.try_state::<TrayIcon>() else {
+ return;
+ };
+ info!("Recreating tray icon on relaunch");
+ if let Err(e) = tray.set_visible(false).and_then(|_| tray.set_visible(true)) {
+ error!("Failed to recreate tray icon: {}", e);
+ }
+}
+
pub fn copy_last_transcript(app: &AppHandle) {
let history_manager = app.state::<Arc<HistoryManager>>();
let entry = match history_manager.get_latest_completed_entry() {
@@ -383,7 +656,7 @@ pub fn copy_last_transcript(app: &AppHandle) {
#[cfg(test)]
mod tests {
- use super::{last_transcript_text, load_tray_icon};
+ use super::{last_transcript_text, load_tray_icon, MenuInputs, TrayDesired, TrayIconState};
use crate::managers::history::HistoryEntry;
fn build_entry(transcription: &str, post_processed: Option<&str>) -> HistoryEntry {
@@ -400,6 +673,18 @@ mod tests {
}
}
+ fn inputs(busy: bool) -> MenuInputs {
+ MenuInputs {
+ busy,
+ warning: false,
+ model_loaded: true,
+ selected_model: "small".to_string(),
+ downloaded_models: vec![("small".to_string(), "Small".to_string())],
+ locale: "en".to_string(),
+ update_checks_enabled: true,
+ }
+ }
+
#[test]
fn uses_post_processed_text_when_available() {
let entry = build_entry("raw", Some("processed"));
@@ -423,4 +708,25 @@ mod tests {
let missing = dir.path().join("does_not_exist.png");
assert!(load_tray_icon(Ok(missing)).is_err());
}
+
+ #[test]
+ fn recording_and_transcribing_share_a_menu() {
+ // The icon differs but the menu inputs are identical, so a
+ // Recording -> Transcribing transition must not rebuild the menu.
+ let recording = TrayDesired {
+ icon_path: "resources/tray_recording.png",
+ menu: inputs(TrayIconState::Recording.is_busy()),
+ };
+ let transcribing = TrayDesired {
+ icon_path: "resources/tray_transcribing.png",
+ menu: inputs(TrayIconState::Transcribing.is_busy()),
+ };
+ assert_ne!(recording.icon_path, transcribing.icon_path);
+ assert_eq!(recording.menu, transcribing.menu);
+ }
+
+ #[test]
+ fn idle_and_busy_menus_differ() {
+ assert_ne!(inputs(false), inputs(true));
+ }
}
diff --git a/src-tauri/src/utils.rs b/src-tauri/src/utils.rs
index 30e8e0fd..763fed75 100644
--- a/src-tauri/src/utils.rs
+++ b/src-tauri/src/utils.rs
@@ -89,7 +89,7 @@ pub fn cancel_current_operation(app: &AppHandle) {
tm.cancel_stream();
// Update tray icon and hide overlay
- change_tray_icon(app, crate::tray::TrayIconState::Idle);
+ set_tray_state(app, crate::tray::TrayIconState::Idle);
hide_recording_overlay(app);
// Unload model if immediate unload is enabled