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
121 changes: 121 additions & 0 deletions packaging/app/src-tauri/src/commands/base_models.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
use onde_cli::{hf, hf_search::DownloadEvent, models};
use serde::Serialize;
use tauri::{State, ipc::Channel};

use crate::{
desktop::{
base_models::{self, BaseModelView},
projects::ProjectSummary,
},
error::CommandError,
state_downloads::Downloads,
};

/// What the webview hears while a model downloads.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum DownloadMsg {
Progress {
filename: String,
file_index: usize,
total_files: usize,
file_bytes_done: u64,
file_bytes_total: u64,
},
Done,
Failed {
message: String,
},
Cancelled,
}

#[tauri::command]
pub async fn list_base_models() -> Result<Vec<BaseModelView>, CommandError> {
tauri::async_runtime::spawn_blocking(base_models::list)
.await
.map_err(|e| CommandError::Internal(e.to_string()))
}

#[tauri::command]
pub async fn create_project(
repo_id: String,
base_model_id: String,
) -> Result<ProjectSummary, CommandError> {
tauri::async_runtime::spawn_blocking(move || {
base_models::create_project(&repo_id, &base_model_id)
})
.await
.map_err(|e| CommandError::Internal(e.to_string()))?
.map_err(CommandError::InvalidChoice)
}

/// Download a catalog model into the shared model cache, reporting progress on
/// `on_event`. Resolves when it finishes, fails or is cancelled.
#[tauri::command]
pub async fn download_base_model(
repo_id: String,
on_event: Channel<DownloadMsg>,
downloads: State<'_, Downloads>,
) -> Result<(), CommandError> {
if !base_models::in_catalog(&repo_id) {
return Err(CommandError::InvalidChoice(format!(
"{repo_id} is not one of the base models this app can download."
)));
}
if models::base_model_dir(&repo_id).is_some() {
let _ = on_event.send(DownloadMsg::Done);
return Ok(());
}

let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let task = tokio::spawn(onde_cli::hf_search::download_model(
repo_id.clone(),
hf::preferred_download_hub(),
tx,
));
let Some(ticket) = downloads.begin(&repo_id, task.abort_handle()) else {
task.abort();
return Err(CommandError::InvalidChoice(format!(
"{repo_id} is already downloading."
)));
};

let mut last = DownloadMsg::Cancelled;
while let Some(event) = rx.recv().await {
let msg = match event {
DownloadEvent::Progress(p) => DownloadMsg::Progress {
filename: p.filename,
file_index: p.file_index,
total_files: p.total_files,
file_bytes_done: p.file_bytes_done,
file_bytes_total: p.file_bytes_total,
},
DownloadEvent::Complete => DownloadMsg::Done,
DownloadEvent::Failed(message) => DownloadMsg::Failed { message },
};
let finished = !matches!(msg, DownloadMsg::Progress { .. });
let _ = on_event.send(msg.clone());
last = msg;
if finished {
break;
}
}
downloads.finish(&repo_id, ticket);
// The channel closing with no final message means the task was aborted.
if matches!(last, DownloadMsg::Cancelled) {
let _ = on_event.send(DownloadMsg::Cancelled);
}
Ok(())
}

/// Whether a download of this model is running, for a screen that was closed and
/// opened again while it went on.
#[tauri::command]
pub fn base_download_running(repo_id: String, downloads: State<'_, Downloads>) -> bool {
downloads.is_running(&repo_id)
}

#[tauri::command]
pub fn cancel_base_download(repo_id: String, downloads: State<'_, Downloads>) -> bool {
downloads.cancel(&repo_id)
}
1 change: 1 addition & 0 deletions packaging/app/src-tauri/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod app;
pub mod auth;
pub mod base_models;
pub mod links;
pub mod oauth;
pub mod projects;
85 changes: 85 additions & 0 deletions packaging/app/src-tauri/src/desktop/base_models.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! The base models a project can start from, and creating a project.
//!
//! The catalog is the one the terminal UI offers (`hf_clone::BASE_MODELS`).
//! Whether a model is downloaded is decided by [`onde_cli::models`], which
//! checks that the weights are all there, so a half-finished download does not
//! count.

use std::path::PathBuf;

use onde_cli::{hf_clone::BASE_MODELS, models, paths, project};
use serde::Serialize;

use super::projects::{ProjectSummary, check_repo_id};

/// One entry of the base-model list.
#[derive(Debug, Clone, Serialize)]
pub struct BaseModelView {
pub repo_id: String,
pub display_name: String,
pub size_display: String,
pub params: String,
pub description: String,
/// Where the complete model is on disk, when it is.
pub dir: Option<PathBuf>,
}

pub fn list() -> Vec<BaseModelView> {
BASE_MODELS
.iter()
.map(|m| BaseModelView {
repo_id: m.repo_id.to_string(),
display_name: m.display_name.to_string(),
size_display: m.size_display.to_string(),
params: m.params.to_string(),
description: m.description.to_string(),
dir: models::base_model_dir(m.repo_id),
})
.collect()
}

/// Only models from the catalog can be downloaded from the app.
pub fn in_catalog(repo_id: &str) -> bool {
BASE_MODELS.iter().any(|m| m.repo_id == repo_id)
}

/// Make a new project. `repo_id` is where the model will be published
/// (`org/name`) and names the project folder; it must be new.
pub fn create_project(repo_id: &str, base_model_id: &str) -> Result<ProjectSummary, String> {
check_repo_id(repo_id)?;
check_repo_id(base_model_id)?;
if paths::projects_dir()
.join(repo_id)
.join("project.json")
.exists()
{
return Err(format!("A project named {repo_id} already exists."));
}
project::create_project(repo_id, base_model_id).map_err(|e| format!("{e:#}"))?;
super::projects::list()
.into_iter()
.find(|p| p.repo_id == repo_id)
.ok_or_else(|| "The project was created but could not be read back.".to_string())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn the_catalog_matches_the_terminal_ui_and_every_id_is_valid() {
let models = list();
assert!(models.len() >= 3, "{models:?}");
for m in &models {
assert!(check_repo_id(&m.repo_id).is_ok(), "{}", m.repo_id);
assert!(in_catalog(&m.repo_id));
}
assert!(!in_catalog("someone/else"));
}

#[test]
fn bad_ids_are_refused_before_anything_is_written() {
assert!(create_project("../x", "Qwen/Qwen3-0.6B").is_err());
assert!(create_project("org/name", "not-an-id").is_err());
}
}
1 change: 1 addition & 0 deletions packaging/app/src-tauri/src/desktop/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Logic with no Tauri types, so tests call it directly.
pub mod app;
pub mod auth;
pub mod base_models;
pub mod bookmark;
pub mod links;
pub mod oauth;
Expand Down
5 changes: 4 additions & 1 deletion packaging/app/src-tauri/src/desktop/projects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! Both are checked here before they become part of a path, so a crafted id
//! cannot reach outside the projects folder.

use std::path::Path;
use std::path::{Path, PathBuf};

use onde_cli::{
pipeline::{self, RunRecord, StepRecord},
Expand Down Expand Up @@ -42,6 +42,8 @@ pub struct ProjectDetail {
pub base_model_id: String,
pub created_at: u64,
pub dataset: DatasetState,
/// Where the complete base model is on disk, when it is.
pub base_dir: Option<PathBuf>,
pub runs: Vec<RunRecord>,
/// An `eval/eval_inputs.json` exists, so the project can be evaluated.
pub has_eval: bool,
Expand Down Expand Up @@ -134,6 +136,7 @@ pub fn detail(repo_id: &str) -> Result<ProjectDetail, String> {
base_model_id: p.base_model_id.clone(),
created_at: meta.map_or(0, |m| m.created_at),
dataset: dataset_state(&p.dataset_path),
base_dir: onde_cli::models::base_model_dir(&p.base_model_id),
runs: project::list_runs(&p),
has_eval: p.project_dir.join("eval/eval_inputs.json").is_file(),
})
Expand Down
7 changes: 7 additions & 0 deletions packaging/app/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod desktop;
mod error;
mod picker;
mod state;
mod state_downloads;

#[cfg(test)]
mod capability_tests;
Expand All @@ -28,11 +29,17 @@ pub fn run() {
.plugin(tauri_plugin_os::init())
.manage(state::PendingSignIn::default())
.manage(links)
.manage(state_downloads::Downloads::default())
.invoke_handler(tauri::generate_handler![
commands::app::app_build,
commands::links::projects_location,
commands::links::link_projects_folder,
commands::links::unlink_projects_folder,
commands::base_models::list_base_models,
commands::base_models::create_project,
commands::base_models::download_base_model,
commands::base_models::cancel_base_download,
commands::base_models::base_download_running,
commands::projects::list_projects,
commands::projects::project_detail,
commands::projects::run_steps,
Expand Down
Loading
Loading