Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

17.7 KB
Raw Blame
//! Local edition settings commands, the Rust half of
//! `src/edition-local/settings-api.ts`: `get_local_settings`,
//! `save_local_settings`, `local_model_status`, `download_local_model` (plus
//! `cancel_local_model_download`) and the `local-model-progress` event.
//!
//! On Windows the chosen model also downloads by itself
//! ([`spawn_model_setup`]): a fresh install starts it a few seconds after
//! launch, so the first recording can be transcribed, and a take that ends
//! before it finishes waits for it (`edition::transcribe`). Cancelling that
//! download or removing the model turns it off for good; Download in
//! Settings turns it back on.
//!
//! Built only without the `cloud` feature. The validation and the shapes are
//! in `clipy_local_edition::settings`, tested there; this file is the I/O:
//! the preset, model names and base URL go to `settings.json` under
//! `local_edition`, keys go to the owner-only `local-keys.json` in the app
//! data folder through `keychain.rs`. No key is ever returned, logged or put
//! in an error.

// The official app uses only the settings and keys (own-key transcription).

use std::path::PathBuf;

use clipy_local_edition::settings::{
    apply_save, to_dto, transcription_plan, KeyFile, LocalModelId, LocalModelStatusDto,
    LocalSettingsDto, Platform, SaveLocalSettingsRequest, StoredSettings, TranscriptionPlan,
    STORE_KEY,
};
use tauri::{AppHandle, Manager, Runtime};
use tauri_plugin_store::StoreExt;

use crate::commands::SETTINGS_STORE;

/// The key file, beside `session.json` in the app data folder.
const KEY_FILE: &str = "local-keys.json";

/// `settings.json` key: the user turned the automatic model download off
/// (cancelled a download, or removed a model).
const AUTO_DECLINED_KEY: &str = "local_edition_model_auto_declined";

/// Waits between automatic download attempts that failed (offline, a
/// server error), then it stops until the next launch or recording.
const RETRY_AFTER_SECS: [u64; 4] = [60, 300, 900, 3600];

/// Saves read, change and write two files; one at a time.
static SAVE: parking_lot::Mutex<()> = parking_lot::const_mutex(());

pub(crate) const PLATFORM: Platform = Platform::current();

/// What `settings.json` holds, or the defaults.
pub(crate) fn load_settings<R: Runtime>(app: &AppHandle<R>) -> StoredSettings {
    let value = app
        .store(SETTINGS_STORE)
        .ok()
        .and_then(|store| store.get(STORE_KEY));
    StoredSettings::from_value(value.as_ref(), PLATFORM)
}

fn key_path<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
    app.path().app_data_dir().ok().map(|dir| dir.join(KEY_FILE))
}

/// The key file. Unreadable reads as empty: the user is asked again.
pub(crate) fn load_keys<R: Runtime>(app: &AppHandle<R>) -> KeyFile {
    let bytes = key_path(app).and_then(|path| crate::keychain::load(&path).ok().flatten());
    KeyFile::from_bytes(bytes.as_deref())
}

fn save_keys<R: Runtime>(app: &AppHandle<R>, keys: &KeyFile) -> Result<(), String> {
    let path = key_path(app).ok_or_else(|| "Could not find the app data folder.".to_string())?;
    let result = if keys.is_empty() {
        crate::keychain::clear(&path)
    } else {
        crate::keychain::save(&path, &keys.to_bytes())
    };
    result.map_err(|_| "Could not save the key file.".to_string())
}

#[tauri::command]
pub fn get_local_settings(app: AppHandle) -> Result<LocalSettingsDto, String> {
    Ok(to_dto(&load_settings(&app), &load_keys(&app)))
}

#[tauri::command]
pub fn save_local_settings(
    app: AppHandle,
    settings: SaveLocalSettingsRequest,
) -> Result<LocalSettingsDto, String> {
    let _one_at_a_time = SAVE.lock();
    let current = load_settings(&app);
    let keys = load_keys(&app);
    let (next, next_keys) = apply_save(&current, &keys, &settings, PLATFORM)?;
    // Keys first: a key saved for settings that then fail to save is bound
    // to a preset and URL that are not stored, so it is never used.
    if next_keys != keys {
        save_keys(&app, &next_keys)?;
    }
    let store = app
        .store(SETTINGS_STORE)
        .map_err(|_| "Could not open the settings file.".to_string())?;
    store.set(STORE_KEY, next.to_value());
    store
        .save()
        .map_err(|_| "Could not save the settings file.".to_string())?;
    Ok(to_dto(&next, &next_keys))
}

#[tauri::command]
pub fn local_model_status() -> Vec<LocalModelStatusDto> {
    LocalModelId::ALL
        .iter()
        .map(|&id| LocalModelStatusDto::new(id, downloads::installed(id), downloads::running(id)))
        .collect()
}

#[tauri::command]
pub async fn download_local_model(app: AppHandle, model: LocalModelId) -> Result<(), String> {
    // Asking for a model is the opposite of turning the download down.
    set_auto_declined(&app, false);
    downloads::download(app, model).await
}

/// Stops a running download (command 5 of the contract). Nothing is
/// installed, and the download's own caller rejects with "The download was
/// cancelled." The model then no longer downloads by itself.
#[tauri::command]
pub fn cancel_local_model_download(app: AppHandle, model: LocalModelId) {
    if downloads::running(model) {
        set_auto_declined(&app, true);
    }
    downloads::cancel(model);
}

/// Deletes a downloaded model so it reads as not installed and can be
/// downloaded again. Rejects, with a message the screen shows, while the model
/// is downloading or a transcription is using it. The model then no longer
/// downloads by itself.
#[tauri::command]
pub async fn remove_local_model(app: AppHandle, model: LocalModelId) -> Result<(), String> {
    downloads::remove(model).await?;
    set_auto_declined(&app, true);
    Ok(())
}

/// Whether the user turned the automatic download off.
pub(crate) fn auto_declined<R: Runtime>(app: &AppHandle<R>) -> bool {
    app.store(SETTINGS_STORE)
        .ok()
        .and_then(|store| store.get(AUTO_DECLINED_KEY))
        .and_then(|value| value.as_bool())
        .unwrap_or(false)
}

fn set_auto_declined<R: Runtime>(app: &AppHandle<R>, declined: bool) {
    if auto_declined(app) == declined {
        return;
    }
    let saved = app.store(SETTINGS_STORE).map(|store| {
        store.set(AUTO_DECLINED_KEY, declined);
        store.save()
    });
    if !matches!(saved, Ok(Ok(()))) {
        tracing::warn!(declined, "could not save the automatic model download choice");
    }
}

/// The on-device model the settings use, when that is the plan.
fn chosen_local_model<R: Runtime>(app: &AppHandle<R>) -> Option<LocalModelId> {
    match transcription_plan(&load_settings(app)) {
        TranscriptionPlan::Local(model) => Some(model),
        _ => None,
    }
}

/// Whether a download of `model` is running now.
pub(crate) fn model_download_running(model: LocalModelId) -> bool {
    downloads::running(model)
}

/// How far a running download of `model` is, in percent.
pub(crate) fn model_download_percent(model: LocalModelId) -> Option<u32> {
    downloads::percent(model)
}

/// Download `model`, or join the download already running.
pub(crate) async fn download_model<R: Runtime>(
    app: AppHandle<R>,
    model: LocalModelId,
) -> Result<(), String> {
    downloads::download(app, model).await
}

enum Ensured {
    /// Installed, or nothing to download (a provider, no transcription, or
    /// the user turned the download off).
    Done,
    Failed,
}

/// Download the chosen model unless it is there or the user said no.
async fn ensure_model<R: Runtime>(app: &AppHandle<R>) -> Ensured {
    let Some(model) = chosen_local_model(app) else {
        return Ensured::Done;
    };
    if downloads::installed(model) || auto_declined(app) {
        return Ensured::Done;
    }
    tracing::info!(model = model.id(), "downloading the transcription model by itself");
    match downloads::download(app.clone(), model).await {
        Ok(()) => Ensured::Done,
        // Cancelled by the user: `cancel_local_model_download` recorded it.
        Err(_) if auto_declined(app) => Ensured::Done,
        Err(_) => Ensured::Failed,
    }
}

/// A fresh install that never saved its settings gets the model for its
/// language: All languages on a PC that is not in English.
#[cfg(target_os = "windows")]
fn first_run_model_for_language<R: Runtime>(app: &AppHandle<R>) {
    let _one_at_a_time = SAVE.lock();
    let Ok(store) = app.store(SETTINGS_STORE) else {
        return;
    };
    if store.get(STORE_KEY).is_some() {
        return;
    }
    let locale = super::system_language();
    let model = clipy_local_edition::settings::first_run_model(locale.as_deref());
    let mut settings = StoredSettings::defaults(PLATFORM);
    if settings.transcription.local_model == Some(model) {
        return;
    }
    settings.transcription.local_model = Some(model);
    store.set(STORE_KEY, settings.to_value());
    if store.save().is_err() {
        tracing::warn!("could not save the first-run transcription model");
    } else {
        tracing::info!(model = model.id(), "first run: transcription model chosen by language");
    }
}

/// Windows: at launch, download the chosen model if it is missing, retrying
/// a failed attempt after a while. Nothing to do on other platforms (the Mac
/// transcribes with Apple Speech).
pub(crate) fn spawn_model_setup<R: Runtime>(app: AppHandle<R>) {
    if !cfg!(target_os = "windows") {
        return;
    }
    tauri::async_runtime::spawn(async move {
        // Let the app finish starting first.
        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
        #[cfg(target_os = "windows")]
        first_run_model_for_language(&app);
        let mut waits = RETRY_AFTER_SECS.iter();
        loop {
            match ensure_model(&app).await {
                Ensured::Done => return,
                Ensured::Failed => {
                    let Some(&wait) = waits.next() else {
                        return;
                    };
                    tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
                }
            }
        }
    });
}

/// A recording is starting: if the model is still missing (the launch
/// attempt failed offline, say), try again now, so it can be ready when the
/// take ends.
pub(crate) fn kick_model_download<R: Runtime>(app: &AppHandle<R>) {
    if !cfg!(target_os = "windows") {
        return;
    }
    let app = app.clone();
    tauri::async_runtime::spawn(async move {
        let _ = ensure_model(&app).await;
    });
}

/// Model downloads on Windows, through `clipy_local_stt::download_model`.
#[cfg(target_os = "windows")]
mod downloads {
    use std::collections::BTreeMap;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    use clipy_local_edition::settings::{
        LocalModelId, LocalModelProgressDto, EVENT_LOCAL_MODEL_PROGRESS,
    };
    use clipy_local_stt::{CancelToken, SttError};
    use tauri::{AppHandle, Emitter, Runtime};
    use tokio::sync::watch;

    /// At most this often while bytes arrive; stage changes always go out.
    const PROGRESS_EVERY: Duration = Duration::from_millis(250);

    type Outcome = Option<Result<(), String>>;

    struct Job {
        cancel: CancelToken,
        done: watch::Receiver<Outcome>,
        /// Progress in tenths of a percent.
        permille: AtomicU32,
    }

    static JOBS: parking_lot::Mutex<BTreeMap<LocalModelId, Arc<Job>>> =
        parking_lot::const_mutex(BTreeMap::new());

    pub(super) fn installed(model: LocalModelId) -> bool {
        clipy_local_stt::model_status(model.to_stt(), None).installed
    }

    pub(super) fn running(model: LocalModelId) -> bool {
        JOBS.lock().contains_key(&model)
    }

    pub(super) fn cancel(model: LocalModelId) {
        if let Some(job) = JOBS.lock().get(&model) {
            job.cancel.cancel();
        }
    }

    pub(super) fn percent(model: LocalModelId) -> Option<u32> {
        JOBS.lock()
            .get(&model)
            .map(|job| job.permille.load(Ordering::Relaxed) / 10)
    }

    pub(super) async fn remove(model: LocalModelId) -> Result<(), String> {
        if running(model) {
            return Err("Cancel the download before removing the model.".into());
        }
        // Deleting a few hundred MB is file-system work: off the async runtime.
        tauri::async_runtime::spawn_blocking(move || {
            clipy_local_stt::remove_model(model.to_stt(), None)
        })
        .await
        .map_err(|_| "The model could not be removed.".to_string())?
        .map_err(|error| match error {
            SttError::ModelBusy(message) => message,
            other => format!("The model could not be removed: {other}"),
        })?;
        tracing::info!(model = model.id(), "local transcription model removed");
        Ok(())
    }

    /// Start the download, or join the one already running for `model`.
    pub(super) async fn download<R: Runtime>(
        app: AppHandle<R>,
        model: LocalModelId,
    ) -> Result<(), String> {
        let mut done = {
            let mut jobs = JOBS.lock();
            match jobs.get(&model) {
                Some(job) => job.done.clone(),
                None => {
                    let (tx, rx) = watch::channel(None);
                    let cancel = CancelToken::new();
                    let job = Arc::new(Job {
                        cancel: cancel.clone(),
                        done: rx.clone(),
                        permille: AtomicU32::new(0),
                    });
                    jobs.insert(model, job.clone());
                    let thread_app = app.clone();
                    let spawned = std::thread::Builder::new()
                        .name("clipy-model-download".into())
                        .spawn(move || run(thread_app, model, cancel, tx, job));
                    if spawned.is_err() {
                        jobs.remove(&model);
                        return Err("Could not start the download.".into());
                    }
                    rx
                }
            }
        };
        loop {
            // Cloned out first: the borrow guard must not live across an await.
            let current: Outcome = done.borrow().clone();
            if let Some(outcome) = current {
                return outcome;
            }
            if done.changed().await.is_err() {
                // The download thread ended without an answer (it panicked):
                // forget the job so the next call can start again.
                JOBS.lock()
                    .retain(|id, job| *id != model || job.done.has_changed().is_ok());
                let last: Outcome = done.borrow().clone();
                return last.unwrap_or_else(|| Err("The download stopped unexpectedly.".into()));
            }
        }
    }

    fn run<R: Runtime>(
        app: AppHandle<R>,
        model: LocalModelId,
        cancel: CancelToken,
        tx: watch::Sender<Outcome>,
        job: Arc<Job>,
    ) {
        let mut last_sent: Option<Instant> = None;
        let mut last_stage = None;
        let result = clipy_local_stt::download_model(
            model.to_stt(),
            None,
            &mut |fraction| {
                job.permille
                    .store((fraction.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed);
                let progress = LocalModelProgressDto::running(model, fraction);
                let due = last_sent.is_none_or(|at| at.elapsed() >= PROGRESS_EVERY);
                if due || last_stage != Some(progress.stage) {
                    last_sent = Some(Instant::now());
                    last_stage = Some(progress.stage);
                    let _ = app.emit(EVENT_LOCAL_MODEL_PROGRESS, progress);
                }
            },
            &cancel,
        );
        let outcome = match result {
            Ok(_) => {
                let _ = app.emit(
                    EVENT_LOCAL_MODEL_PROGRESS,
                    LocalModelProgressDto::installed(model),
                );
                Ok(())
            }
            Err(error) => {
                // Download errors name the model and what went wrong, never a
                // response body; nothing here is a key.
                let message = match error {
                    SttError::Cancelled => "The download was cancelled.".to_string(),
                    other => other.to_string(),
                };
                tracing::warn!(model = model.id(), "model download failed: {message}");
                let _ = app.emit(
                    EVENT_LOCAL_MODEL_PROGRESS,
                    LocalModelProgressDto::failed(model, message.clone()),
                );
                Err(message)
            }
        };
        // Removed before the answer goes out, so a call that arrives after
        // it starts afresh (and finds the model installed at once).
        JOBS.lock().remove(&model);
        let _ = tx.send(Some(outcome));
    }
}

/// The Mac transcribes with Apple Speech and downloads no model; the
/// WebView shows the model rows on Windows only.
#[cfg(not(target_os = "windows"))]
mod downloads {
    use clipy_local_edition::settings::LocalModelId;
    use tauri::{AppHandle, Runtime};

    pub(super) fn installed(_model: LocalModelId) -> bool {
        false
    }

    pub(super) fn running(_model: LocalModelId) -> bool {
        false
    }

    pub(super) fn cancel(_model: LocalModelId) {}

    pub(super) fn percent(_model: LocalModelId) -> Option<u32> {
        None
    }

    pub(super) async fn remove(_model: LocalModelId) -> Result<(), String> {
        Err(
            "This Mac transcribes on the device with Apple Speech, so there is no model to remove."
                .into(),
        )
    }

    pub(super) async fn download<R: Runtime>(
        _app: AppHandle<R>,
        _model: LocalModelId,
    ) -> Result<(), String> {
        if cfg!(target_os = "linux") {
            return Err(crate::unsupported_on_this_platform("Model download"));
        }
        Err("This Mac transcribes on the device with Apple Speech, so there is no model to download.".into())
    }
}