Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion apps/tauri/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,11 @@ pub fn run() {
.manage(ExplicitQuit(Arc::new(AtomicBool::new(false))))
.manage(IsRecording(Arc::new(AtomicBool::new(false))))
.manage(whisper::commands::RecorderState(Mutex::new(None)))
.manage(whisper::commands::TranscriberState(Mutex::new(None)));
.manage(whisper::commands::TranscriberState(Mutex::new(None)))
.manage(whisper::watcher::WhisperWatcherState {
models_watcher: Mutex::new(None),
settings_watcher: Mutex::new(None),
});

#[cfg(unix)]
let builder = builder.manage(ipc::SocketState(Mutex::new(None)));
Expand Down Expand Up @@ -497,6 +501,11 @@ pub fn run() {
}
}

// Initialize whisper file watchers (models dir + settings file)
if let Err(e) = whisper::watcher::init(app) {
eprintln!("Failed to setup whisper file watchers: {}", e);
}

let matches = app.cli().matches().ok();
if let Some(matches) = matches {
if let Some(arg) = matches.args.get("file") {
Expand Down
1 change: 1 addition & 0 deletions apps/tauri/src-tauri/src/whisper/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod audio;
pub mod commands;
pub mod model_manager;
pub mod transcriber;
pub mod watcher;
197 changes: 197 additions & 0 deletions apps/tauri/src-tauri/src/whisper/watcher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
use notify::{Event, EventKind, RecursiveMode, Watcher};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter, Manager};

use super::model_manager;

/// Debounce window for filesystem events. 500 ms is enough to collapse
/// rapid events (chunked writes, editor save-then-rename) while still
/// feeling instant to users.
const DEBOUNCE_MS: u64 = 500;

/// Managed state holding the two whisper-related file watchers.
pub struct WhisperWatcherState {
pub models_watcher: Mutex<Option<notify::RecommendedWatcher>>,
pub settings_watcher: Mutex<Option<notify::RecommendedWatcher>>,
}

/// Timestamp-based deduplication: returns `true` if enough time has
/// elapsed since the last emitted event. Returns `false` on a
/// poisoned mutex instead of panicking so the watcher thread survives.
fn should_emit(last_event: &Arc<Mutex<Instant>>) -> bool {
let Ok(mut last) = last_event.lock() else {
return false;
};
if last.elapsed() < Duration::from_millis(DEBOUNCE_MS) {
return false;
}
*last = Instant::now();
true
}

/// Only `.bin` files are actual Whisper models — ignore `.tmp` partial
/// downloads and any other files that may live in the models directory.
fn is_model_file(path: &std::path::Path) -> bool {
path.extension().map(|ext| ext == "bin").unwrap_or(false)
}

/// Model-relevant event kinds: creation, deletion, and renames
/// (the download flow does a `.tmp` → `.bin` rename on completion).
fn is_relevant_model_event(kind: &EventKind) -> bool {
matches!(
kind,
EventKind::Create(_)
| EventKind::Remove(_)
| EventKind::Modify(notify::event::ModifyKind::Name(_))
)
}

/// Settings-relevant event kinds: creation and any modification.
fn is_relevant_settings_event(kind: &EventKind) -> bool {
matches!(kind, EventKind::Create(_) | EventKind::Modify(_))
}

/// Create a `RecommendedWatcher` that emits `"whisper:models-changed"`
/// whenever a `.bin` file is created, removed, or renamed in the
/// models directory.
fn create_models_watcher(app: AppHandle) -> Result<notify::RecommendedWatcher, String> {
// Initialise in the past so the very first filesystem event fires.
let last_event = Arc::new(Mutex::new(Instant::now() - Duration::from_secs(10)));

let watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
if let Ok(event) = res {
if !is_relevant_model_event(&event.kind) {
return;
}
let has_model_file = event.paths.iter().any(|p| is_model_file(p));
if !has_model_file {
return;
}
if should_emit(&last_event) {
let _ = app.emit("whisper:models-changed", ());
}
}
})
.map_err(|e| format!("Failed to create models watcher: {}", e))?;

Ok(watcher)
}

/// Create a `RecommendedWatcher` that emits `"whisper:settings-changed"`
/// whenever the settings JSON file is created or modified.
///
/// NOTE: When the app itself calls `save_settings()`, this watcher fires
/// back to the frontend. This is intentional — the frontend guards on
/// modal visibility, so the harmless re-read is cheaper than adding a
/// suppression mechanism.
fn create_settings_watcher(
app: AppHandle,
settings_file: &PathBuf,
) -> Result<notify::RecommendedWatcher, String> {
let last_event = Arc::new(Mutex::new(Instant::now() - Duration::from_secs(10)));
// Canonicalize so the path comparison works reliably on macOS where
// FSEvents may return resolved/canonical paths.
let watched_path =
std::fs::canonicalize(settings_file).unwrap_or_else(|_| settings_file.clone());

let watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
if let Ok(event) = res {
if !is_relevant_settings_event(&event.kind) {
return;
}
// Verify the event is for our specific settings file (we watch
// the parent directory for cross-platform reliability).
let is_settings = event.paths.iter().any(|p| {
std::fs::canonicalize(p)
.map(|cp| cp == watched_path)
.unwrap_or_else(|_| p == &watched_path)
});
if !is_settings {
return;
}
if should_emit(&last_event) {
let _ = app.emit("whisper:settings-changed", ());
}
}
})
.map_err(|e| format!("Failed to create settings watcher: {}", e))?;

Ok(watcher)
}

/// Initialise both whisper file watchers and store them in managed state.
///
/// Called from `lib.rs setup()`. Errors are non-fatal — each watcher is
/// set up independently so a failure in one doesn't prevent the other.
pub fn init(app: &tauri::App) -> Result<(), String> {
let app_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;

let models_path = model_manager::models_dir(&app_data_dir);
let settings_file = model_manager::settings_path(&app_data_dir);

let state = app.state::<WhisperWatcherState>();

// --- Models directory watcher ---
match setup_models_watcher(app, &models_path, &state) {
Ok(()) => {}
Err(e) => eprintln!("Whisper models watcher failed: {}", e),
}

// --- Settings file watcher ---
match setup_settings_watcher(app, &settings_file, &app_data_dir, &state) {
Ok(()) => {}
Err(e) => eprintln!("Whisper settings watcher failed: {}", e),
}

Ok(())
}

fn setup_models_watcher(
app: &tauri::App,
models_path: &PathBuf,
state: &WhisperWatcherState,
) -> Result<(), String> {
// Ensure the models directory exists before watching.
std::fs::create_dir_all(models_path)
.map_err(|e| format!("Failed to create models dir: {}", e))?;

let mut watcher = create_models_watcher(app.handle().clone())?;
watcher
.watch(models_path, RecursiveMode::NonRecursive)
.map_err(|e| format!("Failed to watch models dir: {}", e))?;

let mut guard = state.models_watcher.lock().map_err(|e| e.to_string())?;
*guard = Some(watcher);
Ok(())
}

fn setup_settings_watcher(
app: &tauri::App,
settings_file: &PathBuf,
app_data_dir: &PathBuf,
state: &WhisperWatcherState,
) -> Result<(), String> {
// Ensure the settings file's parent directory exists.
if let Some(parent) = settings_file.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create settings dir: {}", e))?;
}

// Watch the parent directory because macOS FSEvents doesn't reliably
// watch individual files that may not exist yet.
let settings_watch_path = settings_file
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| app_data_dir.clone());

let mut watcher = create_settings_watcher(app.handle().clone(), settings_file)?;
watcher
.watch(&settings_watch_path, RecursiveMode::NonRecursive)
.map_err(|e| format!("Failed to watch settings file: {}", e))?;

let mut guard = state.settings_watcher.lock().map_err(|e| e.to_string())?;
*guard = Some(watcher);
Ok(())
}
28 changes: 28 additions & 0 deletions apps/tauri/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,34 @@ listen("file-changed", async (event) => {
}
});

// Whisper file-watcher events — auto-refresh UI when models or settings
// change on disk (e.g. external download, another instance, manual edit).

listen("whisper:models-changed", async () => {
const modal = document.getElementById("whisper-settings-modal");
if (modal && modal.style.display === "flex") {
await loadModelList();
}
});

listen("whisper:settings-changed", async () => {
const modal = document.getElementById("whisper-settings-modal");
if (modal && modal.style.display === "flex") {
try {
// Refresh model list (handles active_model button states)
await loadModelList();
// Update settings fields that loadModelList doesn't cover
const settings = await invoke("get_whisper_settings");
const shortcutInput = document.getElementById("shortcut-input");
const thresholdInput = document.getElementById("threshold-input");
if (shortcutInput) shortcutInput.value = settings.shortcut || "Alt+Space";
if (thresholdInput) thresholdInput.value = settings.long_recording_threshold || 60;
} catch (e) {
console.warn("Failed to refresh whisper settings:", e);
}
}
});
Comment on lines 1105 to 1121
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Refresh model activation UI on settings-file changes.

Line 1109 reloads settings, but this handler only updates shortcut/threshold inputs. If active_model changes externally, the modal’s model buttons can stay stale until reopening.

💡 Proposed fix
 listen("whisper:settings-changed", async () => {
   const modal = document.getElementById("whisper-settings-modal");
   if (modal && modal.style.display === "flex") {
     try {
       const settings = await invoke("get_whisper_settings");
       const shortcutInput = document.getElementById("shortcut-input");
       const thresholdInput = document.getElementById("threshold-input");
       if (shortcutInput) shortcutInput.value = settings.shortcut || "Alt+Space";
       if (thresholdInput) thresholdInput.value = settings.long_recording_threshold || 60;
+      await loadModelList();
     } catch (e) {
       console.warn("Failed to refresh whisper settings:", e);
     }
   }
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/tauri/src/main.js` around lines 1105 - 1118, The settings-changed
handler (listen("whisper:settings-changed") / invoke("get_whisper_settings"))
currently only updates shortcut/threshold inputs; extend it to also refresh the
modal's model selection UI so external changes to active_model are reflected
without reopening. After fetching settings, locate the model buttons inside the
modal (e.g., elements with a class or data attribute used for model selection,
such as ".model-btn" or data-model), remove any existing "active" state from
them, and add the "active" class/state to the button whose model id matches
settings.active_model (also handle a null/undefined active_model by clearing
active state). Ensure the logic runs only when modal && modal.style.display ===
"flex" to avoid unnecessary DOM ops.


// Voice-to-text recording state

const recordingBtn = document.getElementById("recording-btn");
Expand Down